Java Code Examples for org.springframework.core.env.MutablePropertySources#addFirst()

The following examples show how to use org.springframework.core.env.MutablePropertySources#addFirst() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SyndesisCommand.java    From syndesis with Apache License 2.0 6 votes vote down vote up
private AbstractApplicationContext createContext() {
    final AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();

    final YamlPropertySourceLoader propertySourceLoader = new YamlPropertySourceLoader();
    final List<PropertySource<?>> yamlPropertySources;
    try {
        yamlPropertySources = propertySourceLoader.load(name, context.getResource("classpath:" + name + ".yml"));
    } catch (final IOException e) {
        throw new IllegalStateException(e);
    }

    final StandardEnvironment environment = new StandardEnvironment();
    final MutablePropertySources propertySources = environment.getPropertySources();
    propertySources.addFirst(new MapPropertySource("parameters", parameters));
    yamlPropertySources.forEach(propertySources::addLast);

    context.setEnvironment(environment);

    final String packageName = getClass().getPackage().getName();
    context.scan(packageName);

    context.refresh();

    return context;
}
 
Example 2
Source File: PropertiesInitializer.java    From proctor with Apache License 2.0 6 votes vote down vote up
protected boolean tryAddPropertySource(final ConfigurableApplicationContext applicationContext,
                                       final MutablePropertySources propSources,
                                       final String filePath) {

    if (filePath == null) {
        return false;
    }
    Resource propertiesResource = applicationContext.getResource(filePath);
    if (!propertiesResource.exists()) {
        return false;
    }
    try {
        ResourcePropertySource propertySource = new ResourcePropertySource(propertiesResource);
        propSources.addFirst(propertySource);
    } catch (IOException e) {
        return false;
    }
    return true;
}
 
Example 3
Source File: ConfigurationPropertySources.java    From spring-cloud-gray with Apache License 2.0 6 votes vote down vote up
/**
 * Attach a {@link ConfigurationPropertySource} support to the specified
 * {@link Environment}. Adapts each {@link PropertySource} managed by the environment
 * to a {@link ConfigurationPropertySource} and allows classic
 * {@link PropertySourcesPropertyResolver} calls to resolve using
 * {@link ConfigurationPropertyName configuration property names}.
 * <p>
 * The attached resolver will dynamically track any additions or removals from the
 * underlying {@link Environment} property sources.
 *
 * @param environment the source environment (must be an instance of
 *                    {@link ConfigurableEnvironment})
 * @see #get(Environment)
 */
public static void attach(Environment environment) {
    Assert.isInstanceOf(ConfigurableEnvironment.class, environment);
    MutablePropertySources sources = ((ConfigurableEnvironment) environment)
            .getPropertySources();
    PropertySource<?> attached = sources.get(ATTACHED_PROPERTY_SOURCE_NAME);
    if (attached != null && attached.getSource() != sources) {
        sources.remove(ATTACHED_PROPERTY_SOURCE_NAME);
        attached = null;
    }
    if (attached == null) {
        sources.addFirst(new ConfigurationPropertySourcesPropertySource(
                ATTACHED_PROPERTY_SOURCE_NAME,
                new SpringConfigurationPropertySources(sources)));
    }
}
 
Example 4
Source File: TestMetaServer.java    From x-pipe with Apache License 2.0 6 votes vote down vote up
@Override
protected void customizePropertySources(MutablePropertySources propertySources) {
	super.customizePropertySources(propertySources);
	propertySources.addFirst(new PropertySource<Object>("TestAppServerProperty"){

		@Override
		public Object getProperty(String name) {
			
			if(name.equals("server.port")){
				return String.valueOf(serverPort);
			}
			return null;
		}
		
	});
}
 
Example 5
Source File: ScmContextRefresher.java    From super-cloudops with Apache License 2.0 6 votes vote down vote up
/**
 * Don't use ConfigurableEnvironment.merge() in case there are clashes with
 * property source names
 * 
 * @param input
 * @return
 */
private StandardEnvironment copyEnvironment(ConfigurableEnvironment input) {
	StandardEnvironment environment = new StandardEnvironment();
	MutablePropertySources capturedPropertySources = environment.getPropertySources();

	// Only copy the default property source(s) and the profiles over from
	// the main environment (everything else should be pristine, just like
	// it was on startup).
	for (String name : DEFAULT_PROPERTY_SOURCES) {
		if (input.getPropertySources().contains(name)) {
			if (capturedPropertySources.contains(name)) {
				capturedPropertySources.replace(name, input.getPropertySources().get(name));
			} else {
				capturedPropertySources.addLast(input.getPropertySources().get(name));
			}
		}
	}
	environment.setActiveProfiles(input.getActiveProfiles());
	environment.setDefaultProfiles(input.getDefaultProfiles());

	Map<String, Object> map = new HashMap<String, Object>();
	map.put("spring.jmx.enabled", false);
	map.put("spring.main.sources", "");
	capturedPropertySources.addFirst(new MapPropertySource(SCM_REFRESH_PROPERTY_SOURCE, map));
	return environment;
}
 
Example 6
Source File: CamelCloudServiceCallSimpleExpressionTest.java    From camel-spring-boot with Apache License 2.0 5 votes vote down vote up
@Bean
@Lazy(false)
public MutablePropertySources springBootPropertySource() {

    MutablePropertySources sources = env.getPropertySources();
    sources.addFirst(new PropertiesPropertySource("boot-test-property", CamelCloudServiceCallSimpleExpressionTest.getAllProperties()));
    return sources;

}
 
Example 7
Source File: TaskStartTests.java    From spring-cloud-task with Apache License 2.0 5 votes vote down vote up
private SpringApplication getTaskApplication(Integer executionId) {
	SpringApplication myapp = new SpringApplication(TaskStartApplication.class);
	Map<String, Object> myMap = new HashMap<>();
	ConfigurableEnvironment environment = new StandardEnvironment();
	MutablePropertySources propertySources = environment.getPropertySources();
	myMap.put("spring.cloud.task.executionid", executionId);
	propertySources
			.addFirst(new MapPropertySource("EnvrionmentTestPropsource", myMap));
	myapp.setEnvironment(environment);
	return myapp;
}
 
Example 8
Source File: DisableEndpointPostProcessor.java    From edison-microservice with Apache License 2.0 5 votes vote down vote up
private void disableEndpoint(final ConfigurableListableBeanFactory beanFactory) {
    final ConfigurableEnvironment env = beanFactory.getBean(ConfigurableEnvironment.class);
    final MutablePropertySources propertySources = env.getPropertySources();
    propertySources.addFirst(
            new MapPropertySource(endpoint + "PropertySource", singletonMap("endpoints." + endpoint + ".enabled", false))
    );
}
 
Example 9
Source File: QConfigPropertyAnnotationUtil.java    From qconfig with MIT License 5 votes vote down vote up
static StringValueResolver buildStringValueResolver(Map<String, Properties> filenameToPropsMap) {
    MutablePropertySources propertySources = new MutablePropertySources();
    for (Map.Entry<String, Properties> entry : filenameToPropsMap.entrySet()) {
        propertySources.addFirst(new PropertiesPropertySource(entry.getKey(), entry.getValue()));
    }
    return buildStringValueResolver(new PropertySourcesPropertyResolver(propertySources));
}
 
Example 10
Source File: WireMockApplicationListener.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
private void addPropertySource(MutablePropertySources propertySources) {
	if (!propertySources.contains("wiremock")) {
		propertySources.addFirst(
				new MapPropertySource("wiremock", new HashMap<String, Object>()));
	}
	else {
		// Move it up into first place
		PropertySource<?> wiremock = propertySources.remove("wiremock");
		propertySources.addFirst(wiremock);
	}
}
 
Example 11
Source File: ReloadablePropertySourceConfig.java    From tutorials with MIT License 5 votes vote down vote up
@Bean
@ConditionalOnProperty(name = "spring.config.location", matchIfMissing = false)
public ReloadablePropertySource reloadablePropertySource(PropertiesConfiguration properties) {
    ReloadablePropertySource ret = new ReloadablePropertySource("dynamic", properties);
    MutablePropertySources sources = env.getPropertySources();
    sources.addFirst(ret);
    return ret;
}
 
Example 12
Source File: TaskLifecycleListenerTests.java    From spring-cloud-task with Apache License 2.0 5 votes vote down vote up
@Test
public void testParentExecutionId() {
	ConfigurableEnvironment environment = new StandardEnvironment();
	MutablePropertySources propertySources = environment.getPropertySources();
	Map<String, Object> myMap = new HashMap<>();
	myMap.put("spring.cloud.task.parentExecutionId", 789);
	propertySources
			.addFirst(new MapPropertySource("EnvrionmentTestPropsource", myMap));
	this.context.setEnvironment(environment);
	this.context.refresh();
	this.taskExplorer = this.context.getBean(TaskExplorer.class);

	verifyTaskExecution(0, false, null, null, null, 789L);
}
 
Example 13
Source File: GemFirePropertiesFromEnvironmentAutoConfigurationUnitTests.java    From spring-boot-data-geode with Apache License 2.0 4 votes vote down vote up
@Test
public void configuresGemFirePropertiesCorrectlyAndSafely() {

	Map<String, Object> gemfirePropertiesOne = MapBuilder.<String, Object>newMapBuilder()
		.put("gemfire.cache-xml-file", "/path/to/cache.xml")
		.put("gemfire.name", "TestName")
		.put("gemfire.non-existing-property", "TEST")
		.put("geode.enforce-unique-host", "true")
		.put("enable-time-statistics", "true")
		.put("junk.test-property", "MOCK")
		.build();

	Map<String, Object> gemfirePropertiesTwo = MapBuilder.<String, Object>newMapBuilder()
		.put("gemfire.groups", "MockGroup,TestGroup")
		.put("gemfire.mcast-port", " ")
		.put("gemfire.remote-locators", "hellbox[666]")
		.put("mock-property", "MOCK")
		.put("  ", "BLANK")
		.put("", "EMPTY")
		.build();

	CacheFactoryBean mockCacheFactoryBean = mock(CacheFactoryBean.class);

	ConfigurableEnvironment mockEnvironment = mock(ConfigurableEnvironment.class);

	EnumerablePropertySource<?> emptyEnumerablePropertySource = mock(EnumerablePropertySource.class);

	Logger mockLogger = mock(Logger.class);

	MutablePropertySources propertySources = new MutablePropertySources();

	PropertySource<?> nonEnumerablePropertySource = mock(PropertySource.class);

	propertySources.addFirst(new MapPropertySource("gemfirePropertiesOne", gemfirePropertiesOne));
	propertySources.addLast(new MapPropertySource("gemfirePropertiesTwo", gemfirePropertiesTwo));
	propertySources.addLast(emptyEnumerablePropertySource);
	propertySources.addLast(nonEnumerablePropertySource);

	when(mockEnvironment.getPropertySources()).thenReturn(propertySources);

	Properties actualGemFireProperties = new Properties();

	actualGemFireProperties.setProperty("remote-locators", "skullbox[12345]");

	doAnswer(invocation -> actualGemFireProperties).when(mockCacheFactoryBean).getProperties();
	doAnswer(invocation -> {

		Properties gemfireProperties = invocation.getArgument(0);

		actualGemFireProperties.putAll(gemfireProperties);

		return null;

	}).when(mockCacheFactoryBean).setProperties(any(Properties.class));

	doReturn(mockLogger).when(this.configuration).getLogger();

	doAnswer(invocation -> {

		String propertyName = invocation.getArgument(0);

		return gemfirePropertiesOne.getOrDefault(propertyName,
			gemfirePropertiesTwo.getOrDefault(propertyName, null));

	}).when(mockEnvironment).getProperty(anyString());

	this.configuration.configureGemFireProperties(mockEnvironment, mockCacheFactoryBean);

	assertThat(actualGemFireProperties).isNotNull();
	assertThat(actualGemFireProperties).hasSize(4);
	assertThat(actualGemFireProperties).containsKeys("cache-xml-file", "name", "groups");
	assertThat(actualGemFireProperties.getProperty("cache-xml-file")).isEqualTo("/path/to/cache.xml");
	assertThat(actualGemFireProperties.getProperty("name")).isEqualTo("TestName");
	assertThat(actualGemFireProperties.getProperty("groups")).isEqualTo("MockGroup,TestGroup");
	assertThat(actualGemFireProperties.getProperty("remote-locators")).isEqualTo("skullbox[12345]");

	verify(mockLogger, times(1))
		.warn(eq("[gemfire.non-existing-property] is not a valid Apache Geode property"));
	verify(mockLogger, times(1))
		.warn(eq("Apache Geode Property [{}] was not set"), eq("mcast-port"));
}
 
Example 14
Source File: CamelAutoConfiguration.java    From camel-spring-boot with Apache License 2.0 4 votes vote down vote up
static CamelContext doConfigureCamelContext(ApplicationContext applicationContext,
                                            CamelContext camelContext,
                                            CamelConfigurationProperties config) throws Exception {

    camelContext.build();

    // initialize properties component eager
    PropertiesComponent pc = applicationContext.getBeanProvider(PropertiesComponent.class).getIfAvailable();
    if (pc != null) {
        pc.setCamelContext(camelContext);
        camelContext.setPropertiesComponent(pc);
    }

    final Map<String, BeanRepository> repositories = applicationContext.getBeansOfType(BeanRepository.class);
    if (!repositories.isEmpty()) {
        List<BeanRepository> reps = new ArrayList<>();
        // include default bean repository as well
        reps.add(new ApplicationContextBeanRepository(applicationContext));
        // and then any custom
        reps.addAll(repositories.values());
        // sort by ordered
        OrderComparator.sort(reps);
        // and plugin as new registry
        camelContext.adapt(ExtendedCamelContext.class).setRegistry(new DefaultRegistry(reps));
    }

    if (ObjectHelper.isNotEmpty(config.getFileConfigurations())) {
        Environment env = applicationContext.getEnvironment();
        if (env instanceof ConfigurableEnvironment) {
            MutablePropertySources sources = ((ConfigurableEnvironment) env).getPropertySources();
            if (sources != null) {
                if (!sources.contains("camel-file-configuration")) {
                    sources.addFirst(new FilePropertySource("camel-file-configuration", applicationContext, config.getFileConfigurations()));
                }
            }
        }
    }

    camelContext.adapt(ExtendedCamelContext.class).setPackageScanClassResolver(new FatJarPackageScanClassResolver());

    if (config.getRouteFilterIncludePattern() != null || config.getRouteFilterExcludePattern() != null) {
        LOG.info("Route filtering pattern: include={}, exclude={}", config.getRouteFilterIncludePattern(), config.getRouteFilterExcludePattern());
        camelContext.getExtension(Model.class).setRouteFilterPattern(config.getRouteFilterIncludePattern(), config.getRouteFilterExcludePattern());
    }

    // configure the common/default options
    DefaultConfigurationConfigurer.configure(camelContext, config);
    // lookup and configure SPI beans
    DefaultConfigurationConfigurer.afterConfigure(camelContext);
    // and call after all properties are set
    DefaultConfigurationConfigurer.afterPropertiesSet(camelContext);

    return camelContext;
}
 
Example 15
Source File: ClientSecurityAutoConfigurationUnitTests.java    From spring-boot-data-geode with Apache License 2.0 4 votes vote down vote up
@Test
public void configuresSecurityContext() {

	ConfigurableEnvironment mockEnvironment = mock(ConfigurableEnvironment.class);

	Properties vcapProperties = new Properties();

	vcapProperties.setProperty("vcap.application.name", "TestApp");
	vcapProperties.setProperty("vcap.application.uris", "test-app.apps.cloud.skullbox.com");
	vcapProperties.setProperty("vcap.services.test-pcc.credentials.locators", "boombox[10334],skullbox[10334]");
	vcapProperties.setProperty("vcap.services.test-pcc.credentials.urls.gfsh", "https://cloud.skullbox.com:8080/gemfire/v1");
	vcapProperties.setProperty("vcap.services.test-pcc.credentials.urls.pulse", "https://cloud.skullbox.com:8080/pulse");
	vcapProperties.setProperty("vcap.services.test-pcc.credentials.users[0].username", "Abuser");
	vcapProperties.setProperty("vcap.services.test-pcc.credentials.users[0].password", "p@55w0rd");
	vcapProperties.setProperty("vcap.services.test-pcc.credentials.users[0].roles", "cluster_developer");
	vcapProperties.setProperty("vcap.services.test-pcc.credentials.users[1].username", "Master");
	vcapProperties.setProperty("vcap.services.test-pcc.credentials.users[1].password", "p@$$w0rd");
	vcapProperties.setProperty("vcap.services.test-pcc.credentials.users[1].roles", "cluster_operator");
	vcapProperties.setProperty("vcap.services.test-pcc.name", "test-pcc");
	vcapProperties.setProperty("vcap.services.test-pcc.tags", "gemfire,cloudcache,test,geode,pivotal");

	PropertySource vcapPropertySource = new PropertiesPropertySource("vcap", vcapProperties);

	MutablePropertySources propertySources = new MutablePropertySources();

	propertySources.addFirst(vcapPropertySource);

	when(mockEnvironment.getPropertySources()).thenReturn(propertySources);

	AutoConfiguredCloudSecurityEnvironmentPostProcessor environmentPostProcessor =
		spy(new AutoConfiguredCloudSecurityEnvironmentPostProcessor());

	environmentPostProcessor.configureSecurityContext(mockEnvironment);

	verify(mockEnvironment, times(2)).getPropertySources();

	assertThat(propertySources.contains("boot.data.gemfire.cloudcache")).isTrue();

	PropertySource propertySource = propertySources.get("boot.data.gemfire.cloudcache");

	assertThat(propertySource).isNotNull();
	assertThat(propertySource.getName()).isEqualTo("boot.data.gemfire.cloudcache");
	assertThat(propertySource.getProperty("spring.data.gemfire.security.username")).isEqualTo("Master");
	assertThat(propertySource.getProperty("spring.data.gemfire.security.password")).isEqualTo("p@$$w0rd");
	assertThat(propertySource.containsProperty("spring.data.gemfire.security.ssl.use-default-context")).isFalse();
	assertThat(propertySource.getProperty("spring.data.gemfire.pool.locators"))
		.isEqualTo("boombox[10334],skullbox[10334]");
	assertThat(propertySource.getProperty("spring.data.gemfire.management.use-http")).isEqualTo("true");
	assertThat(propertySource.getProperty("spring.data.gemfire.management.require-https")).isEqualTo("true");
	assertThat(propertySource.getProperty("spring.data.gemfire.management.http.host")).isEqualTo("cloud.skullbox.com");
	assertThat(propertySource.getProperty("spring.data.gemfire.management.http.port")).isEqualTo("8080");
}
 
Example 16
Source File: ProfileApplicationListener.java    From spring-cloud-skipper with Apache License 2.0 4 votes vote down vote up
@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
	this.environment = event.getEnvironment();
	Iterable<CloudProfileProvider> cloudProfileProviders = ServiceLoader.load(CloudProfileProvider.class);

	if (ignoreFromSystemProperty()
			|| ignoreFromEnvironmentVariable()
			|| cloudProfilesAlreadySet(cloudProfileProviders)) {
		return;
	}

	boolean addedCloudProfile = false;
	boolean addedKubernetesProfile = false;
	for (CloudProfileProvider cloudProfileProvider : cloudProfileProviders) {
		if (cloudProfileProvider.isCloudPlatform(environment)) {
			String profileToAdd = cloudProfileProvider.getCloudProfile();
			if (!Arrays.asList(environment.getActiveProfiles()).contains(profileToAdd)) {
				if (profileToAdd.equals(KubernetesCloudProfileProvider.PROFILE)) {
					addedKubernetesProfile = true;
				}
				environment.addActiveProfile(profileToAdd);
				addedCloudProfile = true;
			}
		}
	}
	if (!addedKubernetesProfile) {
		Map<String, Object> properties = new LinkedHashMap<>();
		properties.put("spring.cloud.kubernetes.enabled", false);
		logger.info("Setting property 'spring.cloud.kubernetes.enabled' to false.");
		MutablePropertySources propertySources = environment.getPropertySources();
		if (propertySources != null) {
			if (propertySources.contains(
					CommandLinePropertySource.COMMAND_LINE_PROPERTY_SOURCE_NAME)) {
				propertySources.addAfter(
						CommandLinePropertySource.COMMAND_LINE_PROPERTY_SOURCE_NAME,
						new MapPropertySource("skipperProfileApplicationListener", properties));
			}
			else {
				propertySources
						.addFirst(new MapPropertySource("skipperProfileApplicationListener", properties));
			}
		}
	}
	if (!addedCloudProfile) {
		environment.addActiveProfile("local");
	}
}
 
Example 17
Source File: ConfigPropertySourcesFactoryBean.java    From lemon with Apache License 2.0 4 votes vote down vote up
public void init() {
    AppConfig appConfig = AppConfig.getInstance();
    propertySources = new MutablePropertySources();
    propertySources.addFirst(new ConfigPropertySource(appConfig));
}
 
Example 18
Source File: PropertySources.java    From rice with Educational Community License v2.0 4 votes vote down vote up
/**
 * Register {@code propertySource} as the first thing Spring will check when looking up property
 * values.
 */
public static void addFirst(ConfigurableApplicationContext context, PropertySource<?> propertySource) {
    ConfigurableEnvironment env = context.getEnvironment();
    MutablePropertySources propertySources = env.getPropertySources();
    propertySources.addFirst(propertySource);
}
 
Example 19
Source File: CfDataSourceEnvironmentPostProcessor.java    From java-cfenv with Apache License 2.0 4 votes vote down vote up
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment,
		SpringApplication application) {
	increaseInvocationCount();
	if (CloudPlatform.CLOUD_FOUNDRY.isActive(environment)) {
		CfJdbcEnv cfJdbcEnv = new CfJdbcEnv();
		CfJdbcService cfJdbcService = null;
		try {
			cfJdbcService = cfJdbcEnv.findJdbcService();
			cfJdbcService = this.isEnabled(cfJdbcService, environment) ? cfJdbcService : null;
		} catch (Exception e) {

			List<CfJdbcService> jdbcServices = cfJdbcEnv.findJdbcServices().stream()
					.filter(service -> this.isEnabled(service, environment))
					.collect(Collectors.toList());

			if (jdbcServices.size() > 1) {
				if (invocationCount == 1) {
					DEFERRED_LOG.debug(
						"Skipping execution of CfDataSourceEnvironmentPostProcessor. "
							+ e.getMessage());
				}
				return;
			}

			cfJdbcService = jdbcServices.size() == 1 ? jdbcServices.get(0) : null;
		}
		if (cfJdbcService != null) {
			ConnectorLibraryDetector.assertNoConnectorLibrary();
			Map<String, Object> properties = new LinkedHashMap<>();
			properties.put("spring.datasource.url", cfJdbcService.getJdbcUrl());
			properties.put("spring.datasource.username", cfJdbcService.getUsername());
			properties.put("spring.datasource.password", cfJdbcService.getPassword());
			Object driverClassName = cfJdbcService.getDriverClassName();
			if (driverClassName != null) {
				properties.put("spring.datasource.driver-class-name", driverClassName);
			}

			MutablePropertySources propertySources = environment.getPropertySources();
			if (propertySources.contains(
					CommandLinePropertySource.COMMAND_LINE_PROPERTY_SOURCE_NAME)) {
				propertySources.addAfter(
						CommandLinePropertySource.COMMAND_LINE_PROPERTY_SOURCE_NAME,
						new MapPropertySource("cfenvjdbc", properties));
			}
			else {
				propertySources
						.addFirst(new MapPropertySource("cfenvjdbc", properties));
			}
			if (invocationCount == 1) {
				DEFERRED_LOG.info(
						"Setting spring.datasource properties from bound service ["
								+ cfJdbcService.getName() + "]");
			}
		}
	}
	else {
		DEFERRED_LOG.debug(
				"Not setting spring.datasource.url, not in Cloud Foundry Environment");
	}
}
 
Example 20
Source File: TailStreamerApplication.java    From tailstreamer with MIT License 4 votes vote down vote up
@Override
protected void configurePropertySources(ConfigurableEnvironment environment, String[] args) {
    super.configurePropertySources(environment, args);
    MutablePropertySources sources = environment.getPropertySources();
    sources.addFirst(new JOptCommandLinePropertySource(options));
}