public static String getActiveProfile() { String p = System.getProperty(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME); String p1 = System.getenv(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME); String active; if (p == null) { if (p1 == null) { System.setProperty(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, DEFAULT);//Used by @Profile active = DEFAULT_PROFILE; } else { active = p1; } } else { active = p; } if (active == null || active.length() == 0) { log.warn(String.format("-D%s=[profile] please set profile name, now default profile used", ACTIVE_PROFILES_PROPERTY_NAME)); return DEFAULT_PROFILE; } return active; }
public static Map<String,String> getAllProperties(AbstractEnvironment env, String prefix){ int prefixLength = prefix.length(); Map<String, Object> map = new TreeMap<>(); for(Iterator it = (env).getPropertySources().iterator(); it.hasNext(); ) { org.springframework.core.env.PropertySource propertySource = (org.springframework.core.env.PropertySource) it.next(); if (propertySource instanceof MapPropertySource) { map.putAll(((MapPropertySource) propertySource).getSource()); } } Map<String,String> result = new TreeMap<>(); for(String name: map.keySet()){ if(name.startsWith(prefix)){ result.put(name.substring(prefixLength + 1, name.length()), env.getProperty(name)); } } return result; }
public static synchronized void start(String[] args) throws IOException { String daqName = getProperty("c2mon.daq.name"); if (daqName == null) { throw new RuntimeException("Please specify the DAQ process name using 'c2mon.daq.name'"); } // The JMS mode (single, double, test) is controlled via Spring profiles String mode = getProperty("c2mon.daq.jms.mode"); if (mode != null) { System.setProperty(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, mode); } if (application == null) { application = new SpringApplicationBuilder(DaqStartup.class) .bannerMode(Banner.Mode.OFF) .build(); } context = application.run(args); driverKernel = context.getBean(DriverKernel.class); driverKernel.init(); log.info("DAQ core is now initialized"); }
/** * druid数据源 * @return */ @Bean @ConfigurationProperties(prefix = DB_PREFIX) public DataSource druidDataSource() { Properties dbProperties = new Properties(); Map<String, Object> map = new HashMap<>(); for (Iterator<PropertySource<?>> it = ((AbstractEnvironment) environment).getPropertySources().iterator(); it.hasNext();) { PropertySource<?> propertySource = it.next(); getPropertiesFromSource(propertySource, map); } dbProperties.putAll(map); DruidDataSource dds = null; try { dds = (DruidDataSource) DruidDataSourceFactory.createDataSource(dbProperties); if (null != dds) { dds.init(); } } catch (Exception e) { throw new RuntimeException("load datasource error, dbProperties is :" + dbProperties, e); } return dds; }
private Map<String, String> getCurrentEnvironmentProperties() { Map<String, String> currentEnvironment = new HashMap<>(); Set<String> keys = new HashSet<>(); for (PropertySource<?> propertySource : ((AbstractEnvironment) this.environment).getPropertySources()) { if (propertySource instanceof MapPropertySource) { keys.addAll(Arrays.asList(((MapPropertySource) propertySource).getPropertyNames())); } } for (String key : keys) { currentEnvironment.put(key, this.environment.getProperty(key)); } return currentEnvironment; }
/** * @param environment Spring Environment * @param beanName name of Conversion Service bean Martini should utilize * @return specified, or Environment default, conversion service. */ @Lazy @Bean ConversionService getConversionService( AbstractEnvironment environment, @Value("${conversion.service.bean.name:#{null}}") String beanName ) { return null == beanName ? environment.getConversionService() : beanFactory.getBean(beanName, ConversionService.class); }
public static Set<String> getAllPropertyNames(AbstractEnvironment env){ Map<String, Object> map = new HashMap<>(); for(Iterator it = (env).getPropertySources().iterator(); it.hasNext(); ) { org.springframework.core.env.PropertySource propertySource = (org.springframework.core.env.PropertySource) it.next(); if (propertySource instanceof MapPropertySource) { map.putAll(((MapPropertySource) propertySource).getSource()); } } return map.keySet(); }
@SuppressWarnings("rawtypes") public Map<String, Object> startWith(String prefix, boolean removePrefix) { HashMap<String, Object> result = new HashMap<String, Object>(); for (Iterator it = ((AbstractEnvironment) env).getPropertySources().iterator(); it.hasNext();) { PropertySource propertySource = (PropertySource) it.next(); processPropertySource(propertySource, prefix, result, removePrefix); } return result; }
@Override public void onStartup(ServletContext servletContext) // Define qual é o contexto ativo no momento throws ServletException { super.onStartup(servletContext); servletContext.addListener(RequestContextListener.class); servletContext.setInitParameter( AbstractEnvironment.DEFAULT_PROFILES_PROPERTY_NAME, "dev"); }
@Test public void securityManagerDisallowsAccessToSystemEnvironmentAndDisallowsAccessToIndividualKey() { SecurityManager securityManager = new SecurityManager() { @Override public void checkPermission(Permission perm) { // Disallowing access to System#getenv means that our // ReadOnlySystemAttributesMap will come into play. if ("getenv.*".equals(perm.getName())) { throw new AccessControlException("Accessing the system environment is disallowed"); } // Disallowing access to the spring.profiles.active property means that // the BeanDefinitionReader won't be able to determine which profiles are // active. We should see an INFO-level message in the console about this // and as a result, any components marked with a non-default profile will // be ignored. if (("getenv." + AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME).equals(perm.getName())) { throw new AccessControlException( format("Accessing system environment variable [%s] is disallowed", AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME)); } } }; System.setSecurityManager(securityManager); DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); AnnotatedBeanDefinitionReader reader = new AnnotatedBeanDefinitionReader(bf); reader.register(C1.class); assertThat(bf.containsBean("c1"), is(false)); }
/*** * This method is used to give RabbitMq properties based on protocol * @return protocol specific RabbitMq properties in map */ public Map<String, RabbitMqProperties> getRabbitMqProperties() { Map<String, Object> map = new HashMap<String, Object>(); String catalina_home = System.getProperty("catalina.home").replace('\\', '/'); for(Iterator it = ((AbstractEnvironment) env).getPropertySources().iterator(); it.hasNext(); ) { PropertySource propertySource = (PropertySource) it.next(); if (propertySource instanceof MapPropertySource) { if(propertySource.getName().contains("[file:"+catalina_home+"/conf/config.properties]")) { map.putAll(((MapPropertySource) propertySource).getSource()); } } } for (Entry<String, Object> entry : map.entrySet()) { String key = entry.getKey(); if (key.contains("rabbitmq")) { String protocol = key.split("\\.")[0]; if (rabbitMqPropertiesMap.get(protocol) == null) { rabbitMqPropertiesMap.put(protocol, new RabbitMqProperties()); } if (key.contains("rabbitmq.host")) { rabbitMqPropertiesMap.get(protocol).setHost(entry.getValue().toString()); } else if (key.contains("rabbitmq.port")) { rabbitMqPropertiesMap.get(protocol).setPort(Integer.getInteger(entry.getValue().toString())); } else if (key.contains("rabbitmq.username")) { rabbitMqPropertiesMap.get(protocol).setUsername(entry.getValue().toString()); } else if (key.contains("rabbitmq.password")) { rabbitMqPropertiesMap.get(protocol).setPassword(entry.getValue().toString()); } else if (key.contains("rabbitmq.tls")) { rabbitMqPropertiesMap.get(protocol).setTlsVer(entry.getValue().toString()); } else if (key.contains("rabbitmq.exchangeName")) { rabbitMqPropertiesMap.get(protocol).setExchangeName(entry.getValue().toString()); } else if (key.contains("rabbitmq.domainId")) { rabbitMqPropertiesMap.get(protocol).setDomainId(entry.getValue().toString()); } } } return rabbitMqPropertiesMap; }
public static Properties mergeProperties(Set<String> profiles, Set<Resource> resources) { Properties merged = new Properties(); if (!CollectionUtils.isEmpty(profiles)) { merged.setProperty(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, StringUtils.join(profiles, ",")); } for (Resource resource : resources) { merged.putAll(mergeProperties(profiles, resource)); } merged.putAll(System.getProperties()); return merged; }
public EventBasedConfigurationChangeDetector(AbstractEnvironment environment, ConfigReloadProperties properties, KubernetesClient kubernetesClient, ConfigurationUpdateStrategy strategy, ConfigMapPropertySourceLocator configMapPropertySourceLocator, SecretsPropertySourceLocator secretsPropertySourceLocator) { super(environment, properties, kubernetesClient, strategy); this.configMapPropertySourceLocator = configMapPropertySourceLocator; this.secretsPropertySourceLocator = secretsPropertySourceLocator; this.watches = new HashMap<>(); }
public PollingConfigurationChangeDetector(AbstractEnvironment environment, ConfigReloadProperties properties, KubernetesClient kubernetesClient, ConfigurationUpdateStrategy strategy, ConfigMapPropertySourceLocator configMapPropertySourceLocator, SecretsPropertySourceLocator secretsPropertySourceLocator) { super(environment, properties, kubernetesClient, strategy); this.configMapPropertySourceLocator = configMapPropertySourceLocator; this.secretsPropertySourceLocator = secretsPropertySourceLocator; }
@Override protected void doStart() throws Exception { AbstractHandler noContentHandler = new NoContentOutputErrorHandler(); // This part is needed to avoid WARN while starting container. noContentHandler.setServer(server); server.addBean(noContentHandler); // Create the servlet context final ServletContextHandler context = new ServletContextHandler(server, "/management/*", ServletContextHandler.SESSIONS); // REST configuration final ServletHolder servletHolder = new ServletHolder(ServletContainer.class); servletHolder.setInitParameter("javax.ws.rs.Application", GraviteeApplication.class.getName()); servletHolder.setInitOrder(0); context.addServlet(servletHolder, "/*"); // Spring configuration System.setProperty(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, "basic"); AnnotationConfigWebApplicationContext webApplicationContext = new AnnotationConfigWebApplicationContext(); webApplicationContext.register(SecurityConfiguration.class); webApplicationContext.setEnvironment((ConfigurableEnvironment) applicationContext.getEnvironment()); webApplicationContext.setParent(applicationContext); context.addEventListener(new ContextLoaderListener(webApplicationContext)); // Spring Security filter context.addFilter(new FilterHolder(new DelegatingFilterProxy("springSecurityFilterChain")),"/*", EnumSet.allOf(DispatcherType.class)); // start the server server.start(); }
@PostConstruct public void init() { id = resolveId(); enabled = resolveEnabled(); port = resolvePort(); host = resolveHost(); if (isHTTPS()) { keyStoreFile = resolveKeyStoreFile(); keyStorePass = resolveKeyStorePass(); certPass = resolveKeyCertPass(); } for (Iterator it = ((AbstractEnvironment) env).getPropertySources().iterator(); it.hasNext(); ) { Object propertySource = it.next(); if (propertySource instanceof MapPropertySource && SpringConstants.APPLICATION_PROPERTIES.equals(((MapPropertySource) propertySource).getName())) { MapPropertySource mapPropertySource = (MapPropertySource) propertySource; for (Map.Entry<String, Object> entry : mapPropertySource.getSource().entrySet()) { String key = entry.getKey(); if (key.startsWith(getScheme()) && key.contains(SpringConstants.PARAMETER_STR)) { parameters.put(key.substring(key.indexOf(SpringConstants.PARAMETER_STR) + 11), (String) entry .getValue()); } } } } }
@Test public void securityManagerDisallowsAccessToSystemEnvironmentAndDisallowsAccessToIndividualKey() { SecurityManager securityManager = new SecurityManager() { @Override public void checkPermission(Permission perm) { // disallowing access to System#getenv means that our // ReadOnlySystemAttributesMap will come into play. if ("getenv.*".equals(perm.getName())) { throw new AccessControlException( "Accessing the system environment is disallowed"); } // disallowing access to the spring.profiles.active property means that // the BeanDefinitionReader won't be able to determine which profiles are // active. We should see an INFO-level message in the console about this // and as a result, any components marked with a non-default profile will // be ignored. if (("getenv."+AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME).equals(perm.getName())) { throw new AccessControlException( format("Accessing system environment variable [%s] is disallowed", AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME)); } } }; System.setSecurityManager(securityManager); DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); AnnotatedBeanDefinitionReader reader = new AnnotatedBeanDefinitionReader(bf); reader.register(C1.class); assertThat(bf.containsBean("c1"), is(false)); }
public static DataSource newDataSource(Environment environment, String prefix){ BasicDataSource basicDataSource = new BasicDataSource(); BeanPropertyUtil.setBeanProperty(basicDataSource, (AbstractEnvironment)environment, prefix); return basicDataSource; }
public static void setBeanProperty(Object bean, AbstractEnvironment environment, String propertyPrefix) { Map<String, String> valueMap = EnvironmentUtil.getAllProperties(environment, propertyPrefix); for(Map.Entry<String, String> entry: valueMap.entrySet()){ setBeanProperty(bean, entry.getKey(), entry.getValue()); } }
@Before public void setUp() { originalSecurityManager = System.getSecurityManager(); env = StandardEnvironmentTests.getModifiableSystemEnvironment(); env.put(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, "p1"); }
@After public void tearDown() { env.remove(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME); System.setSecurityManager(originalSecurityManager); }
private void initialize(String defaultProfile, boolean autoScan) { ServerConfiguration serverConfiguration = mainClass.getAnnotation(ServerConfiguration.class); if (serverConfiguration != null && serverConfiguration.beanNameGenerator() != BeanNameGenerator.class) { try { applicationContext.setBeanNameGenerator(serverConfiguration.beanNameGenerator().newInstance()); } catch (Exception ignored) { } } applicationContext.register(mainClass); if (autoScan) { applicationContext.scan(mainClass.getPackage().getName()); } Set<String> activeProfiles = Sets.newLinkedHashSet(); String profileProperty = System.getProperty(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, defaultProfile); if (StringUtils.isNotBlank(profileProperty)) { applicationContext.getEnvironment().setActiveProfiles(StringUtils.split(profileProperty, ",")); Collections.addAll(activeProfiles, StringUtils.split(profileProperty, ",")); logger.warn("activeProfiles are {}", activeProfiles); } Set<Resource> resources = getPropertiesResources(serverConfiguration == null ? null : serverConfiguration.properties()); ServerPropertiesConfigurer serverPropertiesConfigurer = new ServerPropertiesConfigurer(activeProfiles, resources); serverPropertiesConfigurer.setIgnoreUnresolvablePlaceholders(true); applicationContext.addBeanFactoryPostProcessor(serverPropertiesConfigurer); this.properties = ServerPropertiesConfigurer.mergeProperties(activeProfiles, resources); applicationContext.setEnvironment(new StandardEnvironment() { @Override protected void customizePropertySources(MutablePropertySources propertySources) { propertySources.addFirst(new PropertiesPropertySource("applicationProperties", properties)); super.customizePropertySources(propertySources); } }); for (ServerProcessor serverProcessor : ServerProcessor.values()) { serverProcessor.register(mainClass, applicationContext, properties); } if (defaultProfile != null && !activeProfiles.contains(defaultProfile)) { pidFileWriter = new PidFileWriter(new File(System.getProperty("app.home", "."), "logs/pid")); } applicationContext.refresh(); }
public static void main(String[] args) throws Exception { //new Main().run(args); System.setProperty(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, "production"); new Main().run(new String[]{"server", "monrad.yaml"}); }
@Override public void onStart() { applicationContext = ApplicationContextHolder.get(); if (applicationContext == null) { List<String> configLocations = Lists.newArrayList(getConfiguration().getStringList("spring-plugin.spring-config-locations", Collections.singletonList("classpath*:spring/**/*.xml"))); List<Plugin> plugins = Scala.asJava(getApplication().getWrappedApplication().plugins()); for (play.api.Plugin plugin : plugins) { WithSpringConfig annotation = plugin.getClass().getAnnotation(WithSpringConfig.class); if (annotation != null) { Collections.addAll(configLocations, annotation.value()); } } LOG.info("Starting spring application context with config locations " + configLocations); ClassPathXmlApplicationContext classPathApplicationContext = new ClassPathXmlApplicationContext(); List<String> activeProfiles = getConfiguration().getStringList(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME); List<String> defaultProfiles = getConfiguration().getStringList(AbstractEnvironment.DEFAULT_PROFILES_PROPERTY_NAME); if (activeProfiles != null) { classPathApplicationContext.getEnvironment().setActiveProfiles( activeProfiles.toArray(new String[activeProfiles.size()])); } if (defaultProfiles != null) { classPathApplicationContext.getEnvironment().setDefaultProfiles( defaultProfiles.toArray(new String[defaultProfiles.size()])); } classPathApplicationContext.setConfigLocations( configLocations.toArray(new String[configLocations.size()])); classPathApplicationContext.refresh(); applicationContext = classPathApplicationContext; } else { LOG.info("Using spring application context in ApplicationContextHolder"); } super.onStart(); }
public static void main(String[] args) throws Throwable { ApplicationContextInitializer<AnnotationConfigWebApplicationContext> aci = new ApplicationContextInitializer<AnnotationConfigWebApplicationContext>() { public void initialize(AnnotationConfigWebApplicationContext appContext) { String profile = System.getProperty("profile"); profile = StringUtils.hasText(profile) ? profile : AbstractEnvironment.DEFAULT_PROFILES_PROPERTY_NAME; if (StringUtils.hasText(profile)) { System.out.println(String.format("Current Profile: '%s'", profile)); appContext.getEnvironment().setActiveProfiles(profile); } appContext.refresh(); } }; SpringApplication springApplication = new SpringApplication(); springApplication.addInitializers(aci); springApplication.run(HelloWebConfiguration.class); }