Java Code Examples for org.springframework.core.env.MapPropertySource

The following examples show how to use org.springframework.core.env.MapPropertySource. These examples are extracted from open source projects. 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 Project: astrix   Source File: GsRemotingTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void broadcastedServiceInvocationThrowServiceUnavailableWhenProxyIsContextIsClosed() throws Exception {
	AnnotationConfigApplicationContext pingServer = autoClosables.add(new AnnotationConfigApplicationContext());
	pingServer.register(PingAppConfig.class);
	pingServer.getEnvironment().getPropertySources().addFirst(new MapPropertySource("props", new HashMap<String, Object>() {{
		put("serviceRegistryUri", serviceRegistry.getServiceUri());
	}}));
	pingServer.refresh();
	
	AstrixContext context = autoClosables.add(
			new TestAstrixConfigurer().registerApiProvider(PingApi.class)
									  .set(AstrixSettings.SERVICE_REGISTRY_URI, serviceRegistry.getServiceUri())
									  .set(AstrixSettings.BEAN_BIND_ATTEMPT_INTERVAL, 200)
									  .configure());
	Ping ping = context.waitForBean(Ping.class, 10000);
	
	assertEquals("foo", ping.broadcastPing("foo").get(0));
	
	context.destroy();

	assertThrows(() -> ping.broadcastPing("foo"), ServiceUnavailableException.class);
}
 
Example 2
@Test
public void migrateEnvKeys_keyChainPrecedence2() {
    Map<String, String> keyMaps = new LinkedHashMap<>();
    keyMaps.put("bla", "bla2");
    keyMaps.put("bla2", "bla3");
    keyMaps.put("bla3", "bla4");

    Map<String, Object> migrated = new LinkedHashMap<>();
    // higher precedence starts later in the chain order
    SettingsService.migratePropertySourceKeys(keyMaps,
            new MapPropertySource("migrated-properties", ImmutableMap.of("bla3", "1")), migrated);
    SettingsService.migratePropertySourceKeys(keyMaps,
            new MapPropertySource("migrated-properties", ImmutableMap.of("bla", "3")), migrated);

    assertThat(migrated).containsOnly(entry("bla2", "3"), entry("bla3", "3"), entry("bla4", "1"));
}
 
Example 3
private void create(ApplicationContextInitializer<GenericApplicationContext>[] types,
		String... props) {
	this.context = new GenericApplicationContext();
	Map<String, Object> map = new HashMap<>();
	for (String prop : props) {
		String[] array = StringUtils.delimitedListToStringArray(prop, "=");
		String key = array[0];
		String value = array.length > 1 ? array[1] : "";
		map.put(key, value);
	}
	if (!map.isEmpty()) {
		this.context.getEnvironment().getPropertySources()
				.addFirst(new MapPropertySource("testProperties", map));
	}
	for (ApplicationContextInitializer<GenericApplicationContext> type : types) {
		type.initialize(this.context);
	}
	new ContextFunctionCatalogInitializer.ContextFunctionCatalogBeanRegistrar(
			this.context).postProcessBeanDefinitionRegistry(this.context);
	this.context.refresh();
	this.catalog = this.context.getBean(FunctionCatalog.class);
	this.inspector = this.context.getBean(FunctionInspector.class);
}
 
Example 4
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment,
		SpringApplication application) {
	if (!environment.getPropertySources().contains(KAFKA_BINDER_DEFAULT_PROPERTIES)) {
		Map<String, Object> kafkaBinderDefaultProperties = new HashMap<>();
		kafkaBinderDefaultProperties.put("logging.level.org.I0Itec.zkclient",
				"ERROR");
		kafkaBinderDefaultProperties.put("logging.level.kafka.server.KafkaConfig",
				"ERROR");
		kafkaBinderDefaultProperties
				.put("logging.level.kafka.admin.AdminClient.AdminConfig", "ERROR");
		kafkaBinderDefaultProperties.put(SPRING_KAFKA_PRODUCER_KEY_SERIALIZER,
				ByteArraySerializer.class.getName());
		kafkaBinderDefaultProperties.put(SPRING_KAFKA_PRODUCER_VALUE_SERIALIZER,
				ByteArraySerializer.class.getName());
		kafkaBinderDefaultProperties.put(SPRING_KAFKA_CONSUMER_KEY_DESERIALIZER,
				ByteArrayDeserializer.class.getName());
		kafkaBinderDefaultProperties.put(SPRING_KAFKA_CONSUMER_VALUE_DESERIALIZER,
				ByteArrayDeserializer.class.getName());
		environment.getPropertySources().addLast(new MapPropertySource(
				KAFKA_BINDER_DEFAULT_PROPERTIES, kafkaBinderDefaultProperties));
	}
}
 
Example 5
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment,
		SpringApplication application) {
	String appName = environment.getProperty("spring.application.name");
	if (StringUtils.hasText(appName) && !appName.contains("/")) {
		String prefix = environment.getProperty("spring.cloud.zookeeper.prefix");
		if (StringUtils.hasText(prefix)) {
			StringBuilder prefixedName = new StringBuilder();
			if (!prefix.startsWith("/")) {
				prefixedName.append("/");
			}
			prefixedName.append(prefix);
			if (!prefix.endsWith("/")) {
				prefixedName.append("/");
			}
			prefixedName.append(appName);
			MapPropertySource propertySource = new MapPropertySource(
					"zookeeperDependencyEnvironment",
					Collections.singletonMap("spring.application.name",
							(Object) prefixedName.toString()));
			environment.getPropertySources().addFirst(propertySource);
		}
	}
}
 
Example 6
private void mergeDefaultProperties(MutablePropertySources environment,
		MutablePropertySources bootstrap) {
	String name = DEFAULT_PROPERTIES;
	if (bootstrap.contains(name)) {
		PropertySource<?> source = bootstrap.get(name);
		if (!environment.contains(name)) {
			environment.addLast(source);
		}
		else {
			PropertySource<?> target = environment.get(name);
			if (target instanceof MapPropertySource && target != source
					&& source instanceof MapPropertySource) {
				Map<String, Object> targetMap = ((MapPropertySource) target)
						.getSource();
				Map<String, Object> map = ((MapPropertySource) source).getSource();
				for (String key : map.keySet()) {
					if (!target.containsProperty(key)) {
						targetMap.put(key, map.get(key));
					}
				}
			}
		}
	}
	mergeAdditionalPropertySources(environment, bootstrap);
}
 
Example 7
private void conditionallyExcludeRabbitAutoConfiguration() {
	if (appIsBoundToRabbitMQ()) {
		return;
	}

	Map<String, Object> properties = new LinkedHashMap<>();
	String existingExcludes = environment.getProperty(SPRING_AUTOCONFIGURE_EXCLUDE);
	if (existingExcludes == null) {
		properties.put(SPRING_AUTOCONFIGURE_EXCLUDE, RABBIT_AUTOCONFIG_CLASS);
	} else if (!existingExcludes.contains(RABBIT_AUTOCONFIG_CLASS)) {
		properties.put(SPRING_AUTOCONFIGURE_EXCLUDE, RABBIT_AUTOCONFIG_CLASS + "," + existingExcludes);
	}

	PropertySource<?> propertySource = new MapPropertySource("springCloudServicesRabbitAutoconfigExcluder",
			properties);
	environment.getPropertySources().addFirst(propertySource);
}
 
Example 8
@Test
void shouldConfigureSsl() {

	Map<String, Object> map = new HashMap<String, Object>();
	map.put("vault.ssl.key-store", "classpath:certificate.json");
	map.put("vault.ssl.trust-store", "classpath:certificate.json");

	MapPropertySource propertySource = new MapPropertySource("shouldConfigureSsl", map);
	this.configurableEnvironment.getPropertySources().addFirst(propertySource);

	SslConfiguration sslConfiguration = this.configuration.sslConfiguration();

	assertThat(sslConfiguration.getKeyStore()).isInstanceOf(ClassPathResource.class);
	assertThat(sslConfiguration.getKeyStorePassword()).isEqualTo("key store password");

	assertThat(sslConfiguration.getTrustStore()).isInstanceOf(ClassPathResource.class);
	assertThat(sslConfiguration.getTrustStorePassword()).isEqualTo("trust store password");

	this.configurableEnvironment.getPropertySources().remove(propertySource.getName());
}
 
Example 9
@Bean
public ApplicationContextInitializer<ConfigurableApplicationContext> customInitializer() {
	return new ApplicationContextInitializer<ConfigurableApplicationContext>() {

		@Override
		public void initialize(ConfigurableApplicationContext applicationContext) {
			ConfigurableEnvironment environment = applicationContext.getEnvironment();
			environment.getPropertySources()
					.addLast(new MapPropertySource("customProperties",
							Collections.<String, Object>singletonMap("custom.foo",
									environment.resolvePlaceholders(
											"${spring.application.name:bar}"))));
		}

	};
}
 
Example 10
@Test
public void serviceUrlWithCompositePropertySource() {
	CompositePropertySource source = new CompositePropertySource("composite");
	this.context.getEnvironment().getPropertySources().addFirst(source);
	source.addPropertySource(new MapPropertySource("config",
			Collections.<String, Object>singletonMap(
					"eureka.client.serviceUrl.defaultZone",
					"https://example.com,https://example2.com, https://www.hugedomains.com/domain_profile.cfm?d=example3&e=com")));
	this.context.register(PropertyPlaceholderAutoConfiguration.class,
			TestConfiguration.class);
	this.context.refresh();
	assertThat(this.context.getBean(EurekaClientConfigBean.class).getServiceUrl()
			.toString()).isEqualTo(
					"{defaultZone=https://example.com,https://example2.com, https://www.hugedomains.com/domain_profile.cfm?d=example3&e=com}");
	assertThat(getEurekaServiceUrlsForDefaultZone()).isEqualTo(
			"[https://example.com/, https://example2.com/, https://www.hugedomains.com/domain_profile.cfm?d=example3&e=com/]");
}
 
Example 11
@Override
public void bind(Map<String, Object> configurationProperties, boolean ignoreUnknownFields,
                 boolean ignoreInvalidFields, Object configurationBean) {

    Iterable<PropertySource<?>> propertySources = asList(new MapPropertySource("internal", configurationProperties));

    // Converts ConfigurationPropertySources
    Iterable<ConfigurationPropertySource> configurationPropertySources = from(propertySources);

    // Wrap Bindable from DubboConfig instance
    Bindable bindable = Bindable.ofInstance(configurationBean);

    Binder binder = new Binder(configurationPropertySources, new PropertySourcesPlaceholdersResolver(propertySources));

    // Get BindHandler
    BindHandler bindHandler = getBindHandler(ignoreUnknownFields, ignoreInvalidFields);

    // Bind
    binder.bind("", bindable, bindHandler);
}
 
Example 12
@Override
public PropertySource<?> locate(Environment environment) {
	if (this.name != null) {
		then(this.name)
				.isEqualTo(environment.getProperty("spring.application.name"));
	}
	if (this.fail) {
		throw new RuntimeException("Planned");
	}
	CompositePropertySource compositePropertySource = new CompositePropertySource(
			"listTestBootstrap");
	compositePropertySource.addFirstPropertySource(
			new MapPropertySource("testBootstrap1", MAP1));
	compositePropertySource.addFirstPropertySource(
			new MapPropertySource("testBootstrap2", MAP2));
	return compositePropertySource;
}
 
Example 13
Source Project: tutorials   Source File: JsonPropertyContextInitializer.java    License: MIT License 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
    try {
        Resource resource = configurableApplicationContext.getResource("classpath:configprops.json");
        Map readValue = new ObjectMapper().readValue(resource.getInputStream(), Map.class);
        Set<Map.Entry> set = readValue.entrySet();
        List<MapPropertySource> propertySources = convertEntrySet(set, Optional.empty());
        for (PropertySource propertySource : propertySources) {
            configurableApplicationContext.getEnvironment()
                .getPropertySources()
                .addFirst(propertySource);
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 14
Source Project: syndesis   Source File: SyndesisCommand.java    License: 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 15
@Test
void configureBean_withDefaultClientSpecifiedAndNoReadReplicaWithExpressions_configuresFactoryBeanWithoutReadReplicaAndResolvedExpressions()
		throws Exception {
	// @checkstyle:on
	// Arrange
	this.context = new AnnotationConfigApplicationContext();
	HashMap<String, Object> propertySourceProperties = new HashMap<>();
	propertySourceProperties.put("dbInstanceIdentifier", "test");
	propertySourceProperties.put("password", "secret");
	propertySourceProperties.put("username", "admin");

	this.context.getEnvironment().getPropertySources()
			.addLast(new MapPropertySource("test", propertySourceProperties));

	// Act
	this.context
			.register(ApplicationConfigurationWithoutReadReplicaAndExpressions.class);
	this.context.refresh();

	// Assert
	assertThat(this.context.getBean(DataSource.class)).isNotNull();
	assertThat(this.context.getBean(AmazonRdsDataSourceFactoryBean.class))
			.isNotNull();
}
 
Example 16
Source Project: spring-cloud-commons   Source File: ContextRefresher.java    License: Apache License 2.0 5 votes vote down vote up
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", "");
	// gh-678 without this apps with this property set to REACTIVE or SERVLET fail
	map.put("spring.main.web-application-type", "NONE");
	capturedPropertySources
			.addFirst(new MapPropertySource(REFRESH_ARGS_PROPERTY_SOURCE, map));
	return environment;
}
 
Example 17
@Override
public void initialize(ConfigurableWebApplicationContext ctx) {
    // vars are searched in order: spring > jvm > env > app.prop > airsonic.prop > default consts
    // spring: java -jar pkg.jar --var=foo
    // jvm: java -jar -Dvar=foo pkg.jar
    // env: SET var=foo; java -jar pkg.jar

    Map<String, String> migratedProps = SettingsService.getMigratedPropertyKeys();

    // Migrate each property source key to its latest name
    // PropertySource precedence matters. Higher migrates first, lower will skip migration if key has already migrated
    // At lookup time, migrated properties have lower precedence (so more specific properties can override migrated properties)
    // Example for same start: env (higher precedence) and file (lower) need to migrate A -> B and both have A
    //  - env migrates A -> B, file skips chain (migration keys already present)
    //  - Lookup(A) will find env[A] (higher precedence)
    //  - Lookup(B) will find migrated[env[A]] since B does not exist in env and file, and migrated has env[A] (skipped file)
    // Example 1 for in-the-middle chain migration: env has C and file has A in migration A -> B -> C -> D
    //  - env migrates C -> D, file migrates A -> B (skips rest of the chain)
    //  - Lookup(A) finds file[A]
    //  - Lookup(B) finds migrated[file[A]]
    //  - Lookup(C) finds env[C]
    //  - Lookup(D) finds migrated[env[C]]
    // Example 2 for in-the-middle chain migration: env has A and file has C in migration A -> B -> C -> D
    //  - env migrates A -> B -> C -> D, file skips chain (migration keys already present)
    //  - Lookup(A) finds env[A]
    //  - Lookup(B) finds migrated[env[A]]
    //  - Lookup(C) finds file[C] (higher precedence than migrated[env[C]])
    //  - Lookup(D) finds migrated[env[A]]
    ctx.getEnvironment().getPropertySources().forEach(ps -> SettingsService.migratePropertySourceKeys(migratedProps, ps, MIGRATED));
    ctx.getEnvironment().getPropertySources().addLast(new MapPropertySource("migrated-properties", MIGRATED));

    // Migrate external property file
    SettingsService.migratePropFileKeys(migratedProps, ConfigurationPropertiesService.getInstance());
    ctx.getEnvironment().getPropertySources().addLast(new ConfigurationPropertySource("airsonic-properties", ConfigurationPropertiesService.getInstance().getConfiguration()));

    // Set default constants - only set if vars are blank so their PS need to be set first (or blank vars will get picked up first on look up)
    SettingsService.setDefaultConstants(ctx.getEnvironment(), DEFAULT_CONSTANTS);
    ctx.getEnvironment().getPropertySources().addFirst(new MapPropertySource("default-constants", DEFAULT_CONSTANTS));
}
 
Example 18
@Test
public void migrateEnvKeys_noKeys() {
    Map<String, String> keyMaps = new LinkedHashMap<>();
    keyMaps.put("bla", "bla2");
    keyMaps.put("bla2", "bla3");
    Map<String, Object> migrated = new LinkedHashMap<>();
    SettingsService.migratePropertySourceKeys(keyMaps, new MapPropertySource("migrated-properties", Collections.emptyMap()), migrated);

    assertThat(migrated).isEmpty();
}
 
Example 19
Source Project: msf4j   Source File: TransportConfig.java    License: Apache License 2.0 5 votes vote down vote up
@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());
                }
            }
        }
    }
}
 
Example 20
private Map<String, Object> getDefaultProperties(
		ConfigurableEnvironment environment) {
	if (environment.getPropertySources().contains("defaultProperties")) {
		MapPropertySource source = (MapPropertySource) environment
				.getPropertySources().get("defaultProperties");
		return source.getSource();
	}
	HashMap<String, Object> map = new HashMap<String, Object>();
	environment.getPropertySources()
			.addLast(new MapPropertySource("defaultProperties", map));
	return map;
}
 
Example 21
@Override
public String[] selectImports(AnnotationMetadata metadata) {
	String[] imports = super.selectImports(metadata);

	AnnotationAttributes attributes = AnnotationAttributes.fromMap(
			metadata.getAnnotationAttributes(getAnnotationClass().getName(), true));

	boolean autoRegister = attributes.getBoolean("autoRegister");

	if (autoRegister) {
		List<String> importsList = new ArrayList<>(Arrays.asList(imports));
		importsList.add(
				"org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationConfiguration");
		imports = importsList.toArray(new String[0]);
	}
	else {
		Environment env = getEnvironment();
		if (ConfigurableEnvironment.class.isInstance(env)) {
			ConfigurableEnvironment configEnv = (ConfigurableEnvironment) env;
			LinkedHashMap<String, Object> map = new LinkedHashMap<>();
			map.put("spring.cloud.service-registry.auto-registration.enabled", false);
			MapPropertySource propertySource = new MapPropertySource(
					"springCloudDiscoveryClient", map);
			configEnv.getPropertySources().addLast(propertySource);
		}

	}

	return imports;
}
 
Example 22
Source Project: flowable-engine   Source File: SpringAutoDeployTest.java    License: Apache License 2.0 5 votes vote down vote up
protected void createAppContext(Map<String, Object> properties) {
    AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
    applicationContext.register(SpringFormAutoDeployTestConfiguration.class);
    applicationContext.getEnvironment().getPropertySources()
        .addLast(new MapPropertySource("springAutoDeploy", properties));
    applicationContext.refresh();
    this.applicationContext = applicationContext;
    this.repositoryService = applicationContext.getBean(FormRepositoryService.class);
}
 
Example 23
@Test
void credentialsProvider_configWithAccessAndSecretKeyAsPlaceHolders_staticAwsCredentialsProviderConfiguredWithResolvedPlaceHolders()
		throws Exception {
	// @checkstyle:on
	// Arrange
	this.context = new AnnotationConfigApplicationContext();

	Map<String, Object> secretAndAccessKeyMap = new HashMap<>();
	secretAndAccessKeyMap.put("accessKey", "accessTest");
	secretAndAccessKeyMap.put("secretKey", "testSecret");

	this.context.getEnvironment().getPropertySources()
			.addLast(new MapPropertySource("test", secretAndAccessKeyMap));
	PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
	configurer.setPropertySources(this.context.getEnvironment().getPropertySources());

	this.context.getBeanFactory().registerSingleton("configurer", configurer);
	this.context.register(
			ApplicationConfigurationWithAccessKeyAndSecretKeyAsPlaceHolder.class);
	this.context.refresh();
	// Act
	AWSCredentialsProvider awsCredentialsProvider = this.context
			.getBean(AWSCredentialsProvider.class);

	// Assert
	assertThat(awsCredentialsProvider).isNotNull();

	@SuppressWarnings("unchecked")
	List<CredentialsProvider> credentialsProviders = (List<CredentialsProvider>) ReflectionTestUtils
			.getField(awsCredentialsProvider, "credentialsProviders");
	assertThat(credentialsProviders.size()).isEqualTo(1);
	assertThat(AWSStaticCredentialsProvider.class
			.isInstance(credentialsProviders.get(0))).isTrue();

	assertThat(awsCredentialsProvider.getCredentials().getAWSAccessKeyId())
			.isEqualTo("accessTest");
	assertThat(awsCredentialsProvider.getCredentials().getAWSSecretKey())
			.isEqualTo("testSecret");
}
 
Example 24
Source Project: spring4-understanding   Source File: ImportResourceTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void importWithPlaceholder() throws Exception {
	AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
	PropertySource<?> propertySource = new MapPropertySource("test",
			Collections.<String, Object> singletonMap("test", "springframework"));
	ctx.getEnvironment().getPropertySources().addFirst(propertySource);
	ctx.register(ImportXmlConfig.class);
	ctx.refresh();
	assertTrue("did not contain xml-declared bean", ctx.containsBean("xmlDeclaredBean"));
	ctx.close();
}
 
Example 25
Source Project: spring-analysis-note   Source File: ImportResourceTests.java    License: MIT License 5 votes vote down vote up
@Test
public void importWithPlaceholder() throws Exception {
	AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
	PropertySource<?> propertySource = new MapPropertySource("test",
			Collections.<String, Object> singletonMap("test", "springframework"));
	ctx.getEnvironment().getPropertySources().addFirst(propertySource);
	ctx.register(ImportXmlConfig.class);
	ctx.refresh();
	assertTrue("did not contain xml-declared bean", ctx.containsBean("xmlDeclaredBean"));
	ctx.close();
}
 
Example 26
Source Project: flowable-engine   Source File: SpringAutoDeployTest.java    License: Apache License 2.0 5 votes vote down vote up
protected void createAppContext(Map<String, Object> properties) {
    AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
    applicationContext.register(SpringEventAutoDeployTestConfiguration.class);
    applicationContext.getEnvironment().getPropertySources()
        .addLast(new MapPropertySource("springAutoDeploy", properties));
    applicationContext.refresh();
    this.applicationContext = applicationContext;
    this.repositoryService = applicationContext.getBean(EventRepositoryService.class);
}
 
Example 27
@Test
public void testServerUp() {
	PropertySource<?> source = new MapPropertySource("foo",
			Collections.<String, Object>emptyMap());
	doReturn(source).when(this.locator).locate(any(Environment.class));
	assertThat(this.indicator.health().getStatus()).isEqualTo(Status.UP);
	verify(this.locator, times(1)).locate(any(Environment.class));
}
 
Example 28
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 29
Source Project: pmq   Source File: MqEnvPropTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void getEnv1Test() {
	//MapPropertySource
	ConfigurableEnvironment environment=mock(ConfigurableEnvironment.class);
	MutablePropertySources mutablePropertySources=new MutablePropertySources();
	when(environment.getPropertySources()).thenReturn(mutablePropertySources);
	Map<String, Object> map=new HashMap<String, Object>();
	map.put("test", "fa");
	map.put("password", "dfasf");		
	environment.getPropertySources().addFirst(new MapPropertySource("test", map));  
	MqEnvProp mqEnvProp=new MqEnvProp();
	mqEnvProp.setEnvironment(environment);
	assertEquals(2, mqEnvProp.getEnv().size());
}
 
Example 30
Source Project: pmq   Source File: MqEnvPropTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void getEnvTest() {
	ConfigurableEnvironment environment=mock(ConfigurableEnvironment.class);
	MutablePropertySources mutablePropertySources=new MutablePropertySources();
	when(environment.getPropertySources()).thenReturn(mutablePropertySources);
	Map<String, Object> map=new HashMap<String, Object>();
	map.put("test.test2", "fa");
	map.put("test.password", "dfasf");		
	environment.getPropertySources().addFirst(new MapPropertySource("test", map));  
	MqEnvProp mqEnvProp=new MqEnvProp();
	mqEnvProp.setEnvironment(environment);
	assertEquals(2, mqEnvProp.getEnv("test").size());
}