Example usage for org.springframework.core.env MapPropertySource MapPropertySource

List of usage examples for org.springframework.core.env MapPropertySource MapPropertySource

Introduction

In this page you can find the example usage for org.springframework.core.env MapPropertySource MapPropertySource.

Prototype

public MapPropertySource(String name, Map<String, Object> source) 

Source Link

Usage

From source file:com.sitewhere.configuration.TomcatConfigurationResolver.java

@Override
public ApplicationContext resolveTenantContext(ITenant tenant, IVersion version, ApplicationContext global)
        throws SiteWhereException {
    LOGGER.info("Loading Spring configuration ...");
    File sitewhereConf = getSiteWhereConfigFolder();
    File tenantConfigFile = getTenantConfigurationFile(sitewhereConf, tenant, version);
    GenericApplicationContext context = new GenericApplicationContext(global);

    // Plug in custom property source.
    Map<String, Object> properties = new HashMap<String, Object>();
    properties.put("sitewhere.edition", version.getEditionIdentifier().toLowerCase());
    properties.put("tenant.id", tenant.getId());

    MapPropertySource source = new MapPropertySource("sitewhere", properties);
    context.getEnvironment().getPropertySources().addLast(source);

    // Read context from XML configuration file.
    XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(context);
    reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_XSD);
    reader.loadBeanDefinitions(new FileSystemResource(tenantConfigFile));

    context.refresh();//from  ww  w  .  ja  va 2  s  .co m
    return context;
}

From source file:org.springframework.cloud.aws.context.config.annotation.ContextCredentialsConfigurationRegistrarTest.java

@Test
public void credentialsProvider_configWithAccessAndSecretKeyAsPlaceHolders_staticAwsCredentialsProviderConfiguredWithResolvedPlaceHolders()
        throws Exception {
    //Arrange/*  w  w w . j  av  a2s  .c  o  m*/
    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
    assertNotNull(awsCredentialsProvider);

    @SuppressWarnings("unchecked")
    List<CredentialsProvider> credentialsProviders = (List<CredentialsProvider>) ReflectionTestUtils
            .getField(awsCredentialsProvider, "credentialsProviders");
    assertEquals(1, credentialsProviders.size());
    assertTrue(StaticCredentialsProvider.class.isInstance(credentialsProviders.get(0)));

    assertEquals("accessTest", awsCredentialsProvider.getCredentials().getAWSAccessKeyId());
    assertEquals("testSecret", awsCredentialsProvider.getCredentials().getAWSSecretKey());
}

From source file:com.github.eddumelendez.autoconfigure.ldap.embedded.EmbeddedLdapAutoConfiguration.java

private Map<String, Object> getLdapPorts(MutablePropertySources sources) {
    PropertySource<?> propertySource = sources.get("ldap.ports");
    if (propertySource == null) {
        propertySource = new MapPropertySource("ldap.ports", new HashMap<String, Object>());
        sources.addFirst(propertySource);
    }//from  w  w  w. java  2 s .  c  o  m
    return (Map<String, Object>) propertySource.getSource();
}

From source file:io.gravitee.management.idp.core.plugin.impl.IdentityProviderManagerImpl.java

private <T> T create(Plugin plugin, Class<T> identityClass, Map<String, Object> properties) {
    if (identityClass == null) {
        return null;
    }//from   w w  w  .  ja  v a  2  s  .c om

    try {
        T identityObj = createInstance(identityClass);
        final Import annImport = identityClass.getAnnotation(Import.class);
        Set<Class<?>> configurations = (annImport != null) ? new HashSet<>(Arrays.asList(annImport.value()))
                : Collections.emptySet();

        ApplicationContext idpApplicationContext = pluginContextFactory
                .create(new AnnotationBasedPluginContextConfigurer(plugin) {
                    @Override
                    public Set<Class<?>> configurations() {
                        return configurations;
                    }

                    @Override
                    public ConfigurableEnvironment environment() {
                        return new StandardEnvironment() {
                            @Override
                            protected void customizePropertySources(MutablePropertySources propertySources) {
                                propertySources.addFirst(new MapPropertySource(plugin.id(), properties));
                                super.customizePropertySources(propertySources);
                            }
                        };
                    }
                });

        idpApplicationContext.getAutowireCapableBeanFactory().autowireBean(identityObj);

        return identityObj;
    } catch (Exception ex) {
        LOGGER.error("An unexpected error occurs while loading identity provider", ex);
        return null;
    }
}

From source file:com.kixeye.chassis.transport.shared.SharedTest.java

@Test
public void testProperties() throws Exception {
    Map<String, Object> properties = new HashMap<String, Object>();
    properties.put("admin.enabled", "true");
    properties.put("admin.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("admin.hostname", "localhost");

    properties.put("websocket.enabled", "true");
    properties.put("websocket.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("websocket.hostname", "localhost");

    properties.put("http.enabled", "true");
    properties.put("http.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("http.hostname", "localhost");

    AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
    StandardEnvironment environment = new StandardEnvironment();
    environment.getPropertySources().addFirst(new MapPropertySource("default", properties));
    context.setEnvironment(environment);
    context.register(PropertySourcesPlaceholderConfigurer.class);
    context.register(TransportConfiguration.class);
    context.register(MetricsConfiguration.class);

    RestTemplate httpClient = new RestTemplate();

    try {/*from   w ww  .  j  a va 2s  . c o  m*/
        context.refresh();

        httpClient.setInterceptors(Lists.newArrayList(LOGGING_INTERCEPTOR));
        List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
        for (MessageSerDe messageSerDe : context.getBeansOfType(MessageSerDe.class).values()) {
            messageConverters.add(new SerDeHttpMessageConverter(messageSerDe));
        }
        messageConverters.add(new StringHttpMessageConverter(StandardCharsets.UTF_8));
        httpClient.setMessageConverters(messageConverters);

        ResponseEntity<String> response = httpClient.getForEntity(
                new URI("http://localhost:" + properties.get("admin.port") + "/admin/properties"),
                String.class);

        logger.info("Got response: [{}]", response);

        Assert.assertEquals(response.getStatusCode().value(), HttpStatus.OK.value());
        Assert.assertTrue(response.getBody().contains("user.dir=" + System.getProperty("user.dir")));
    } finally {
        context.close();
    }
}

From source file:com.alibaba.dubbo.config.spring.context.annotation.DubboConfigBindingRegistrar.java

private MutablePropertyValues resolveBeanPropertyValues(String beanName, boolean multiple,
        Map<String, String> properties) {

    MutablePropertyValues propertyValues = new MutablePropertyValues();

    if (multiple) { // For Multiple Beans

        MutablePropertySources propertySources = new MutablePropertySources();
        propertySources.addFirst(new MapPropertySource(beanName, new TreeMap<String, Object>(properties)));

        Map<String, String> subProperties = getSubProperties(propertySources, beanName);

        propertyValues.addPropertyValues(subProperties);

    } else { // For Single Bean

        for (Map.Entry<String, String> entry : properties.entrySet()) {
            String propertyName = entry.getKey();
            if (!propertyName.contains(".")) { // ignore property name with "."
                propertyValues.addPropertyValue(propertyName, entry.getValue());
            }//from  w  ww  .j av  a 2 s. c o  m
        }

    }

    return propertyValues;

}

From source file:com.textocat.textokit.eval.matching.MatchingConfigurationInitializerTest.java

private PropertyResolver makePropertyResolver(Map<String, Object> properties) {
    MutablePropertySources propSources = new MutablePropertySources();
    propSources.addFirst(new MapPropertySource("default", properties));
    PropertyResolver result = new PropertySourcesPropertyResolver(propSources);
    return result;
}

From source file:com.kixeye.chassis.transport.HttpTransportTest.java

@Test
public void testHttpServiceWithJson() throws Exception {
    Map<String, Object> properties = new HashMap<String, Object>();
    properties.put("http.enabled", "true");
    properties.put("http.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("http.hostname", "localhost");

    properties.put("websocket.enabled", "false");
    properties.put("websocket.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("websocket.hostname", "localhost");

    AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
    StandardEnvironment environment = new StandardEnvironment();
    environment.getPropertySources().addFirst(new MapPropertySource("default", properties));
    context.setEnvironment(environment);
    context.register(PropertySourcesPlaceholderConfigurer.class);
    context.register(TransportConfiguration.class);
    context.register(TestRestService.class);

    try {//from   ww w  .  j a  v  a  2  s.  c  o  m
        context.refresh();

        final MessageSerDe serDe = context.getBean(JsonJacksonMessageSerDe.class);

        RestTemplate httpClient = new RestTemplate(new HttpComponentsClientHttpRequestFactory());
        httpClient.setErrorHandler(new ResponseErrorHandler() {
            public boolean hasError(ClientHttpResponse response) throws IOException {
                return response.getRawStatusCode() == HttpStatus.OK.value();
            }

            public void handleError(ClientHttpResponse response) throws IOException {

            }
        });

        httpClient.setInterceptors(Lists.newArrayList(LOGGING_INTERCEPTOR));
        httpClient.setMessageConverters(new ArrayList<HttpMessageConverter<?>>(
                Lists.newArrayList(new SerDeHttpMessageConverter(serDe))));

        TestObject response = httpClient.getForObject(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);

        response = httpClient.postForObject(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/"),
                new TestObject("more stuff"), TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);

        response = httpClient.getForObject(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("more stuff", response.value);

        response = httpClient.getForObject(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/getFuture"),
                TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("more stuff", response.value);

        response = httpClient.getForObject(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/getObservable"),
                TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("more stuff", response.value);

        ResponseEntity<ServiceError> error = httpClient.postForEntity(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/"),
                new TestObject(RandomStringUtils.randomAlphabetic(100)), ServiceError.class);

        Assert.assertNotNull(response);
        Assert.assertEquals(HttpStatus.BAD_REQUEST, error.getStatusCode());
        Assert.assertEquals(ExceptionServiceErrorMapper.VALIDATION_ERROR_CODE, error.getBody().code);

        error = httpClient.getForEntity(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/expectedError"),
                ServiceError.class);

        Assert.assertNotNull(response);
        Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION_HTTP_CODE, error.getStatusCode());
        Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION.code, error.getBody().code);
        Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION.description, error.getBody().description);

        error = httpClient.getForEntity(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/unexpectedError"),
                ServiceError.class);

        Assert.assertNotNull(response);
        Assert.assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, error.getStatusCode());
        Assert.assertEquals(ExceptionServiceErrorMapper.UNKNOWN_ERROR_CODE, error.getBody().code);
    } finally {
        context.close();
    }
}

From source file:com.kixeye.chassis.transport.WebSocketTransportTest.java

@Test
public void testEmptyWebSocketFrameUsingText() throws Exception {
    Map<String, Object> properties = new HashMap<String, Object>();
    properties.put("websocket.enabled", "true");
    properties.put("websocket.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("websocket.hostname", "localhost");

    properties.put("http.enabled", "false");
    properties.put("http.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("http.hostname", "localhost");

    AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
    StandardEnvironment environment = new StandardEnvironment();
    environment.getPropertySources().addFirst(new MapPropertySource("default", properties));
    context.setEnvironment(environment);
    context.register(PropertySourcesPlaceholderConfigurer.class);
    context.register(TransportConfiguration.class);
    context.register(TestWebSocketService.class);

    WebSocketClient wsClient = new WebSocketClient();

    try {/*w  w w.j a va  2  s .  co  m*/
        //start server
        context.refresh();

        // start client
        wsClient.start();

        final MessageSerDe serDe = context.getBean(JsonJacksonMessageSerDe.class);

        final WebSocketMessageRegistry messageRegistry = context.getBean(WebSocketMessageRegistry.class);

        QueuingWebSocketListener listener = new QueuingWebSocketListener(serDe, messageRegistry, null);

        WebSocketSession session = (WebSocketSession) wsClient.connect(listener, new URI(
                "ws://localhost:" + properties.get("websocket.port") + "/" + serDe.getMessageFormatName()))
                .get(5000, TimeUnit.MILLISECONDS);

        session.getRemote().sendString("");

        ServiceError error = listener.getResponse(5, TimeUnit.SECONDS);

        Assert.assertNotNull(error);
        Assert.assertEquals("EMPTY_ENVELOPE", error.code);
        Assert.assertEquals("STOPPED", session.getState());
    } finally {
        try {
            wsClient.stop();
        } finally {
            context.close();
        }
    }
}

From source file:org.springframework.cloud.aws.context.config.xml.ContextCredentialsBeanDefinitionParserTest.java

@Test
public void parseBean_withProfileCredentialsProviderAndProfileFile_createProfileCredentialsProvider()
        throws IOException {
    GenericApplicationContext applicationContext = new GenericApplicationContext();

    Map<String, Object> secretAndAccessKeyMap = new HashMap<>();
    secretAndAccessKeyMap.put("profilePath",
            new ClassPathResource(getClass().getSimpleName() + "-profile", getClass()).getFile()
                    .getAbsolutePath());

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

    XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(applicationContext);
    reader.loadBeanDefinitions(new ClassPathResource(
            getClass().getSimpleName() + "-profileCredentialsProviderWithFile.xml", getClass()));

    applicationContext.refresh();/*from ww  w  .  j  ava2  s. c  o m*/

    AWSCredentialsProvider provider = applicationContext.getBean(
            AmazonWebserviceClientConfigurationUtils.CREDENTIALS_PROVIDER_BEAN_NAME,
            AWSCredentialsProvider.class);
    assertNotNull(provider);

    assertEquals("testAccessKey", provider.getCredentials().getAWSAccessKeyId());
    assertEquals("testSecretKey", provider.getCredentials().getAWSSecretKey());
}