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:bootstrap.EnvironmentBootstrapConfiguration.java

@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
    if (!environment.getPropertySources().contains(CONFIG_SERVER_BOOTSTRAP)) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("spring.cloud.config.uri",
                "${CONFIG_SERVER_URI:${vcap.services.${PREFIX:}configserver.credentials.uri:http://localhost:8888}}");
        if (ClassUtils.isPresent("org.springframework.cloud.sleuth.zipkin.ZipkinProperties", null)) {
            map.put("spring.zipkin.host",
                    "${ZIPKIN_HOST:${vcap.services.${PREFIX:}zipkin.credentials.host:localhost}}");
            map.put("logging.pattern.console",
                    "%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(%5p) %clr(${PID:- }){magenta} %clr(---){faint} %clr([trace=%X{X-Trace-Id:-},span=%X{X-Span-Id:-}]){yellow} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n%wex");
            String zipkinHost = environment
                    .resolvePlaceholders("${ZIPKIN_HOST:${vcap.services.${PREFIX:}zipkin.credentials.host:}}");
            if (!"".equals(zipkinHost)) {
                map.put("fleet.zipkin.enabled", "true");
            }//from w ww.j  av a 2  s  . c o m
        }
        String space = environment.resolvePlaceholders("${vcap.application.space_name:dev}");
        log.info("Spacename: " + space);
        if (space.startsWith("dev")) {
            environment.addActiveProfile("dev");
        }
        map.put("encrypt.failOnError", "false");
        map.put("endpoints.shutdown.enabled", "true");
        map.put("endpoints.restart.enabled", "true");
        environment.getPropertySources().addLast(new MapPropertySource(CONFIG_SERVER_BOOTSTRAP, map));
    }
}

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

@Override
public ApplicationContext resolveSiteWhereContext(IVersion version) throws SiteWhereException {
    LOGGER.info("Loading Spring configuration ...");
    File sitewhereConf = getSiteWhereConfigFolder();
    File serverConfigFile = new File(sitewhereConf, SERVER_CONFIG_FILE_NAME);
    if (!serverConfigFile.exists()) {
        throw new SiteWhereException(
                "SiteWhere server configuration not found: " + serverConfigFile.getAbsolutePath());
    }//w w w  . j a  v a  2  s . c  o  m
    GenericApplicationContext context = new GenericApplicationContext();

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

    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(serverConfigFile));

    context.refresh();
    return context;
}

From source file:com.richard.memorystore.tcp.TcpServer.java

public static GenericXmlApplicationContext setupContext() {
    final GenericXmlApplicationContext context = new GenericXmlApplicationContext();

    System.out.print("Detect open server socket...");
    int availableServerSocket = SocketUtils.findAvailableServerSocket(5678);

    final Map<String, Object> sockets = new HashMap<String, Object>();
    sockets.put("availableServerSocket", availableServerSocket);

    final MapPropertySource propertySource = new MapPropertySource("sockets", sockets);

    context.getEnvironment().getPropertySources().addLast(propertySource);

    System.out.println("using port " + context.getEnvironment().getProperty("availableServerSocket"));

    context.load("classpath:tcpClientServerDemo-context.xml");
    context.registerShutdownHook();/* w w w  . j a v  a  2  s. c o  m*/
    context.refresh();

    return context;
}

From source file:com.ecsteam.cloudlaunch.environment.VcapEnvironmentListener.java

@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
    Map<String, Object> properties = new RelaxedPropertyResolver(event.getEnvironment())
            .getSubProperties("vcap.services.");

    if (properties == null || properties.isEmpty()) {
        return;/*  www  .j  a v a 2  s.c  o  m*/
    }

    Map<String, Object> source = new HashMap<String, Object>();

    source.put("ecs.cc.user", "${vcap.services.${ecs.cc.serviceId:cc}.credentials.user}");
    source.put("ecs.cc.password", "${vcap.services.${ecs.cc.serviceId:cc}.credentials.password}");
    source.put("ecs.cc.url", "${vcap.services.${ecs.cc.serviceId:cc}.credentials.url}");
    source.put("ecs.cc.trustSelfSigned",
            "${vcap.services.${ecs.cc.serviceId:cc}.credentials.trustSelfSigned:false}");

    source.put("ecs.jenkins.baseUrl", "${vcap.services.${ecs.jenkins.serviceId:jenkins}.credentials.baseUrl}");
    source.put("ecs.jenkins.jobName", "${vcap.services.${ecs.jenkins.serviceId:jenkins}.credentials.jobName}");
    source.put("ecs.jenkins.user", "${vcap.services.${ecs.jenkins.serviceId:jenkins}.credentials.user}");
    source.put("ecs.jenkins.password",
            "${vcap.services.${ecs.jenkins.serviceId:jenkins}.credentials.password}");

    source.put("ecs.github.clientId", "${vcap.services.${ecs.github.serviceId:github}.credentials.clientId}");
    source.put("ecs.github.clientSecret",
            "${vcap.services.${ecs.github.serviceId:github}.credentials.clientSecret}");
    source.put("ecs.github.repoName", "${vcap.services.${ecs.github.serviceId:github}.credentials.repoName}");
    source.put("ecs.github.repoOwner", "${vcap.services.${ecs.github.serviceId:github}.credentials.repoOwner}");
    source.put("ecs.github.accessToken",
            "${vcap.services.${ecs.github.serviceId:github}.credentials.accessToken}");

    event.getEnvironment().getPropertySources()
            .addLast(new MapPropertySource("ecsCloudLaunchProperties", source));
}

From source file:io.pivotal.spring.cloud.service.hystrix.HystrixStreamServiceConnector.java

@Override
protected PropertySource<?> toPropertySource(HystrixAmqpServiceInfo serviceInfo) {
    Map<String, Object> properties = new LinkedHashMap<>();

    properties.put(SPRING_CLOUD_STREAM_BINDINGS_HYSTRIXSTREAMOUTPUT + "destination",
            SPRING_CLOUD_HYSTRIX_STREAM);
    properties.put(SPRING_CLOUD_STREAM_BINDINGS_HYSTRIXSTREAMOUTPUT + "binder", "hystrix");
    properties.put(SPRING_CLOUD_STREAM_BINDERS_HYSTRIX + "type", "rabbit");
    properties.put(SPRING_CLOUD_STREAM_BINDERS_HYSTRIX + "inheritEnvironment", false);
    properties.put(SPRING_CLOUD_STREAM_BINDERS_HYSTRIX + "defaultCandidate", false);
    properties.put(/*from w  ww.ja va 2s .  co  m*/
            SPRING_CLOUD_STREAM_BINDERS_HYSTRIX + "environment.spring.cloud.stream.overrideCloudConnectors",
            true);
    properties.put(SPRING_CLOUD_STREAM_BINDERS_HYSTRIX_ENVIRONMENT_SPRING_RABBITMQ + "addresses",
            serviceInfo.getAddresses());
    properties.put(SPRING_CLOUD_STREAM_BINDERS_HYSTRIX_ENVIRONMENT_SPRING_RABBITMQ + "username",
            serviceInfo.getUserName());
    properties.put(SPRING_CLOUD_STREAM_BINDERS_HYSTRIX_ENVIRONMENT_SPRING_RABBITMQ + "password",
            serviceInfo.getPassword());
    properties.put(SPRING_CLOUD_STREAM_BINDERS_HYSTRIX_ENVIRONMENT_SPRING_RABBITMQ + "virtualHost",
            serviceInfo.getVirtualHost());
    properties.put(SPRING_CLOUD_STREAM_BINDERS_HYSTRIX_ENVIRONMENT_SPRING_RABBITMQ + "ssl.enabled",
            serviceInfo.getSslEnabled());
    properties.put(SPRING_CLOUD_STREAM_BINDERS_HYSTRIX + "default.prefix", "");

    return new MapPropertySource(PROPERTY_SOURCE_NAME, properties);
}

From source file:com.haythem.integration.Main.java

public static GenericXmlApplicationContext setupContext() {
    final GenericXmlApplicationContext context = new GenericXmlApplicationContext();

    System.out.print("Detect open server socket...");
    int availableServerSocket = SocketUtils.findAvailableServerSocket(5678);

    final Map<String, Object> sockets = new HashMap<String, Object>();
    sockets.put("availableServerSocket", availableServerSocket);

    final MapPropertySource propertySource = new MapPropertySource("sockets", sockets);

    context.getEnvironment().getPropertySources().addLast(propertySource);

    System.out.println("using port " + context.getEnvironment().getProperty("availableServerSocket"));

    context.load("classpath:META-INF/spring/integration/tcpClientServerDemo-context.xml");
    context.registerShutdownHook();//  www.  j  a va 2  s .c  o  m
    context.refresh();

    return context;
}

From source file:org.wso2.msf4j.spring.property.YamlFileApplicationContextInitializer.java

@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
    Resource resource = applicationContext.getResource("classpath:" + YAML_CONFIG_FILE_NAME);
    if (!resource.exists()) {
        resource = applicationContext.getResource("file:" + YAML_CONFIG_FILE_NAME);
    }//from  w w w.  j  a va  2 s  .  co m

    if (resource.exists()) {
        List<Properties> applicationYmlProperties = new ArrayList<>();
        String[] activeProfileNames = null;
        try (InputStream input = resource.getInputStream()) {
            Yaml yml = new Yaml(new SafeConstructor());
            Iterable<Object> objects = yml.loadAll(input);
            for (Object obj : objects) {
                Map<String, Object> flattenedMap = getFlattenedMap(asMap(obj));
                Properties properties = new Properties();
                properties.putAll(flattenedMap);
                Object activeProfile = properties.get("spring.profiles.active");
                if (activeProfile != null) {
                    activeProfileNames = activeProfile.toString().split(",");
                }
                applicationYmlProperties.add(properties);
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException("Couldn't find " + YAML_CONFIG_FILE_NAME, e);
        } catch (IOException e) {
            throw new RuntimeException("Error while reading " + YAML_CONFIG_FILE_NAME, e);
        }

        if (activeProfileNames == null) {
            activeProfileNames = applicationContext.getEnvironment().getActiveProfiles();
        }

        for (Properties properties : applicationYmlProperties) {
            String profile = properties.getProperty("spring.profiles");
            PropertySource<?> propertySource;
            if (profile == null) {
                propertySource = new MapPropertySource(YAML_CONFIG_FILE_NAME, new HashMap(properties));
                applicationContext.getEnvironment().getPropertySources().addLast(propertySource);
            } else if (activeProfileNames != null && ("default".equals(profile)
                    || (activeProfileNames.length == 1 && activeProfileNames[0].equals(profile)))) {
                propertySource = new MapPropertySource(YAML_CONFIG_FILE_NAME + "[" + profile + "]",
                        new HashMap(properties));
                applicationContext.getEnvironment().getPropertySources().addAfter("systemEnvironment",
                        propertySource);
            }
            activeProfileNames = applicationContext.getEnvironment().getActiveProfiles();
        }
    }
    applicationContext.getEnvironment().getActiveProfiles();
}

From source file:com.bose.aem.spring.config.ConfigServicePropertySourceLocator.java

@Override
public org.springframework.core.env.PropertySource<?> locate(
        org.springframework.core.env.Environment environment) {
    ConfigClientProperties client = this.defaults.override(environment);
    CompositePropertySource composite = new CompositePropertySource("configService");
    RestTemplate restTemplate = this.restTemplate == null ? getSecureRestTemplate(client) : this.restTemplate;
    Exception error = null;/*from w w  w.ja va  2 s .co  m*/
    String errorBody = null;
    //logger.info("Fetching config from server at: " + client.getRawUri());
    try {
        String[] labels = new String[] { "" };
        if (StringUtils.hasText(client.getLabel())) {
            labels = StringUtils.commaDelimitedListToStringArray(client.getLabel());
        }
        // Try all the labels until one works
        for (String label : labels) {
            Environment result = getRemoteEnvironment(restTemplate, client.getRawUri(), client.getName(),
                    client.getProfile(), label.trim());
            if (result != null) {
                //                    logger.info(String.format("Located environment: name=%s, profiles=%s, label=%s, version=%s",
                //                            result.getName(),
                //                            result.getProfiles() == null ? "" : Arrays.asList(result.getProfiles()),
                //                            result.getLabel(), result.getVersion()));

                for (PropertySource source : result.getPropertySources()) {
                    @SuppressWarnings("unchecked")
                    Map<String, Object> map = (Map<String, Object>) source.getSource();
                    composite.addPropertySource(new MapPropertySource(source.getName(), map));
                }
                return composite;
            }
        }
    } catch (HttpServerErrorException e) {
        error = e;
        if (MediaType.APPLICATION_JSON.includes(e.getResponseHeaders().getContentType())) {
            errorBody = e.getResponseBodyAsString();
        }
    } catch (Exception e) {
        error = e;
    }
    if (client != null && client.isFailFast()) {
        throw new IllegalStateException(
                "Could not locate PropertySource and the fail fast property is set, failing", error);
    }
    //        logger.warn("Could not locate PropertySource: "
    //                + (errorBody == null ? error == null ? "label not found" : error.getMessage() : errorBody));
    return null;

}

From source file:com.avanza.astrix.integration.tests.GsRemotingTest.java

@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>() {
                {/* ww w  .j  a  v  a  2 s . c  o  m*/
                    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);
}

From source file:edu.jhuapl.openessence.config.AppInitializer.java

/**
 * Add builtin properties, i.e. properties added to environment that do not come from .properties files.
 */// www. j  a v a2  s  .c o m
private MapPropertySource getBuiltinPropertySource(ConfigurableWebApplicationContext ctx) {
    Map<String, Object> builtinProps = new HashMap<String, Object>();
    builtinProps.put("contextPath", ctx.getServletContext().getContextPath());

    return new MapPropertySource(BUILTIN_PROP_SOURCE, builtinProps);
}