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

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

Introduction

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

Prototype

protected PropertiesPropertySource(String name, Map<String, Object> source) 

Source Link

Usage

From source file:org.jumpmind.metl.ui.init.AppInitializer.java

@Override
public void onStartup(ServletContext servletContext) throws ServletException {
    Properties properties = loadProperties();
    AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
    applicationContext.scan("org.jumpmind.metl");
    MutablePropertySources sources = applicationContext.getEnvironment().getPropertySources();
    sources.addLast(new PropertiesPropertySource("passed in properties", properties));
    servletContext.addListener(new ContextLoaderListener(applicationContext));
    servletContext.addListener(this);
    servletContext.addListener(new RequestContextListener());

    AnnotationConfigWebApplicationContext dispatchContext = new AnnotationConfigWebApplicationContext();
    dispatchContext.setParent(applicationContext);
    ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher",
            new DispatcherServlet(dispatchContext));
    dispatcher.setLoadOnStartup(1);//from ww w .  j a v  a  2 s .  c om
    dispatcher.addMapping("/api/*");
    applicationContextRef.set(dispatchContext);

    ServletRegistration.Dynamic apidocs = servletContext.addServlet("apidocs", DefaultServlet.class);
    apidocs.addMapping("/api.html", "/doc/*");

    ServletRegistration.Dynamic vaadin = servletContext.addServlet("vaadin", AppServlet.class);
    vaadin.setAsyncSupported(true);
    vaadin.setInitParameter("org.atmosphere.cpr.asyncSupport", JSR356AsyncSupport.class.getName());
    vaadin.setInitParameter("beanName", "appUI");
    vaadin.addMapping("/*");
}

From source file:org.opentestsystem.shared.test.standalone.LoadTestPackageRunner.java

private void main_(String[] args) {
    // Bridge the JUL logging into SLF4J
    SLF4JBridgeHandler.removeHandlersForRootLogger(); // (since SLF4J 1.6.5)
    SLF4JBridgeHandler.install();//from   w w  w  . ja  v a2s .  co  m
    MDC.put("interestingThreadId", "main");

    // Parse arguments
    Options options = new Options();
    options.addOption("h", OPTION_NAME_HELP, false, "Print this message");
    options.addOption("p", OPTION_NAME_CONTEXT_CONFIG, true,
            "URL of Spring context-configuration file that defines the test to run");
    options.addOption("c", OPTION_NAME_CONTEXT_PROPERTIES, true,
            "URL of a file defining properties for the test");
    options.addOption("d", OPTION_NAME_SPRING_PROFILES, true,
            "Names of active Spring profiles, separated by spaces");
    CommandLineParser cliParser = new GnuParser();
    CommandLine cli = null;
    try {
        cli = cliParser.parse(options, args);
    } catch (ParseException e) {
        _logger.error("Unable to parse command line parameters", e);
        System.exit(1);
    }

    if (cli.hasOption(OPTION_NAME_HELP)) {
        new HelpFormatter().printHelp("java -jar shared-test.jar", options);
        System.exit(0);
    }

    String contextConfigUrl = cli.getOptionValue(OPTION_NAME_CONTEXT_CONFIG, OPTION_DEFAULT_CONTEXT_CONFIG);
    String contextPropertiesUrl = cli.getOptionValue(OPTION_NAME_CONTEXT_PROPERTIES,
            OPTION_DEFAULT_CONTEXT_PROPERTIES);
    String springProfilesString = cli.getOptionValue(OPTION_NAME_SPRING_PROFILES,
            OPTION_DEFAULT_SPRING_PROFILES);

    // Configure the Spring context
    GenericXmlApplicationContext context = new GenericXmlApplicationContext();
    if (!StringUtils.isEmpty(springProfilesString)) {
        String[] springProfiles = springProfilesString.split(" ");
        context.getEnvironment().setActiveProfiles(springProfiles);
    }
    if (!StringUtils.isEmpty(contextPropertiesUrl)) {
        Properties p = new Properties();
        try {
            p.loadFromXML(new URL(contextPropertiesUrl).openStream());
        } catch (InvalidPropertiesFormatException e) {
            MDC.put("close", "true");
            _logger.error("Error parsing properties file {}", contextPropertiesUrl, e);
            System.exit(1);
        } catch (MalformedURLException e) {
            MDC.put("close", "true");
            _logger.error("Illegal URL for properties file {}", contextPropertiesUrl, e);
            System.exit(1);
        } catch (IOException e) {
            MDC.put("close", "true");
            _logger.error("IO error reading properties file {}", contextPropertiesUrl, e);
            System.exit(1);
        }
        context.getEnvironment().getPropertySources().addFirst(new PropertiesPropertySource("cmdline", p));
    }
    context.load(contextConfigUrl);
    context.refresh();
    setApplicationContext(context);

    // Get the lifecycle resources
    _lifecycleResources = new LifecycleResourceCombiner();
    _lifecycleResources.setApplicationContext(context);

    // Start lifecycle resources
    try {
        _lifecycleResources.startupBeforeDependencies();
        _lifecycleResources.startupAfterDependencies();
    } catch (Exception e) {
        MDC.put("close", "true");
        _logger.error("Error starting lifecycle resources", e);
        System.exit(1);
    }

    // Get the first-person users
    _users = new HashMap<>();
    for (@SuppressWarnings("rawtypes")
    Entry<String, FirstPersonInteractiveUser> entry_i : context.getBeansOfType(FirstPersonInteractiveUser.class)
            .entrySet()) {
        _users.put(entry_i.getKey(), entry_i.getValue());
    }

    // Start first-person scripts
    for (FirstPersonInteractiveUser<?, ?> user_i : _users.values()) {
        user_i.startScript();
    }

    // Wait for conclusion
    for (FirstPersonInteractiveUser<?, ?> user_i : _users.values()) {
        try {
            user_i.join();
        } catch (InterruptedException e) {
            _logger.error("Interrupted running test");
        }
    }

    // Expand any "chorus" users to get the actual users
    int i = 0;
    List<FirstPersonInteractiveUser<?, ?>> allUsers = new ArrayList<>(_users.values());
    while (i < allUsers.size()) {
        FirstPersonInteractiveUser<?, ?> user_i = allUsers.get(i);
        if (user_i instanceof Chorus) {
            allUsers.remove(i);
            for (FirstPersonInteractiveUser<?, ?> user_j : ((Chorus<?, ?>) user_i)) {
                allUsers.add(user_j);
            }
        } else {
            i++;
        }
    }

    // Log summary interaction statistics
    TimingRecordSummarizer summarizer = new TimingRecordSummarizerImpl();
    for (FirstPersonInteractiveUser<?, ?> user_i : allUsers) {
        for (InteractionContext<?> context_j : user_i.getInteractionContexts()) {
            for (InteractionTimingRecord record_k : context_j.getTimingRecordHistory()) {
                summarizer.addObservation(record_k);
            }
        }
    }
    _logger.info("Latency summary:\r\n\r\n" + summarizer.getSummaryAsString());

    // Shut down lifecycle resources
    try {
        _lifecycleResources.shutdownBeforeDependencies();
        _lifecycleResources.shutdownAfterDependencies();
    } catch (Exception e) {
        MDC.put("close", "true");
        _logger.error("Error stopping lifecycle resources", e);
        System.exit(1);
    }
    MDC.put("close", "true");
    System.exit(0);
}

From source file:org.springframework.batch.integration.x.RemoteFileToHadoopTests.java

@SuppressWarnings({ "unchecked", "rawtypes" })
@Before//from ww  w .  j ava2 s .  co m
public void setup() throws Exception {
    byte[] bytes = "foobarbaz".getBytes();

    // using this trick here by getting hadoop minicluster from main test
    // context and then using it to override 'hadoopConfiguration' bean
    // which is imported from ftphdfs.xml.
    ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext();
    ctx.setConfigLocations("org/springframework/batch/integration/x/RemoteFileToHadoopTests-context.xml",
            "org/springframework/batch/integration/x/miniclusterconfig.xml");
    Properties properties = new Properties();
    properties.setProperty("restartable", "false");
    properties.setProperty("xd.config.home", "file:../../config");
    properties.setProperty("partitionResultsTimeout", "3600000");
    PropertiesPropertySource propertiesPropertySource = new PropertiesPropertySource("props", properties);
    ctx.getEnvironment().getPropertySources().addLast(propertiesPropertySource);
    ctx.setParent(context);
    ctx.refresh();

    this.sessionFactory = ctx.getBean(SessionFactory.class);

    Session session = mock(Session.class);
    when(this.sessionFactory.getSession()).thenReturn(session);
    when(session.readRaw("/foo/bar.txt")).thenReturn(new ByteArrayInputStream(bytes));
    when(session.readRaw("/foo/baz.txt")).thenReturn(new ByteArrayInputStream(bytes));
    when(session.finalizeRaw()).thenReturn(true);
    Object[] fileList = new FTPFile[2];
    FTPFile file = new FTPFile();
    file.setName("bar.txt");
    fileList[0] = file;
    file = new FTPFile();
    file.setName("baz.txt");
    fileList[1] = file;
    when(session.list("/foo/")).thenReturn(fileList);

    this.launcher = ctx.getBean(JobLauncher.class);
    this.job = ctx.getBean(Job.class);
    this.requestsOut = ctx.getBean("stepExecutionRequests.output", MessageChannel.class);
    this.requestsIn = ctx.getBean("stepExecutionRequests.input", MessageChannel.class);
    this.repliesOut = ctx.getBean("stepExecutionReplies.output", MessageChannel.class);
    this.repliesIn = ctx.getBean("stepExecutionReplies.input", MessageChannel.class);

    this.bus = new LocalMessageBus();
    ((LocalMessageBus) this.bus).setApplicationContext(ctx);
    this.bus.bindRequestor("foo", this.requestsOut, this.repliesIn, null);
    this.bus.bindReplier("foo", this.requestsIn, this.repliesOut, null);
}

From source file:org.springframework.boot.cloud.CloudFoundryVcapEnvironmentPostProcessor.java

@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
    if (CloudPlatform.CLOUD_FOUNDRY.isActive(environment)) {
        Properties properties = new Properties();
        addWithPrefix(properties, getPropertiesFromApplication(environment), "vcap.application.");
        addWithPrefix(properties, getPropertiesFromServices(environment), "vcap.services.");
        MutablePropertySources propertySources = environment.getPropertySources();
        if (propertySources.contains(CommandLinePropertySource.COMMAND_LINE_PROPERTY_SOURCE_NAME)) {
            propertySources.addAfter(CommandLinePropertySource.COMMAND_LINE_PROPERTY_SOURCE_NAME,
                    new PropertiesPropertySource("vcap", properties));
        } else {//w w  w . j a  v  a 2 s  .co m
            propertySources.addFirst(new PropertiesPropertySource("vcap", properties));
        }
    }
}

From source file:org.springframework.boot.cloudfoundry.VcapApplicationListener.java

@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
    ConfigurableEnvironment environment = event.getEnvironment();
    if (!environment.containsProperty(VCAP_APPLICATION) && !environment.containsProperty(VCAP_SERVICES)) {
        return;/*from w w  w  . ja v  a 2 s.  c  o  m*/
    }
    Properties properties = new Properties();
    addWithPrefix(properties, getPropertiesFromApplication(environment), "vcap.application.");
    addWithPrefix(properties, getPropertiesFromServices(environment), "vcap.services.");
    MutablePropertySources propertySources = environment.getPropertySources();
    if (propertySources.contains(CommandLinePropertySource.COMMAND_LINE_PROPERTY_SOURCE_NAME)) {
        propertySources.addAfter(CommandLinePropertySource.COMMAND_LINE_PROPERTY_SOURCE_NAME,
                new PropertiesPropertySource("vcap", properties));
    } else {
        propertySources.addFirst(new PropertiesPropertySource("vcap", properties));
    }
}

From source file:org.springframework.boot.cloudfoundry.VcapEnvironmentPostProcessor.java

@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
    if (!environment.containsProperty(VCAP_APPLICATION) && !environment.containsProperty(VCAP_SERVICES)) {
        return;//from   w  w w .  j  a  v a 2s  .  c o  m
    }
    Properties properties = new Properties();
    addWithPrefix(properties, getPropertiesFromApplication(environment), "vcap.application.");
    addWithPrefix(properties, getPropertiesFromServices(environment), "vcap.services.");
    MutablePropertySources propertySources = environment.getPropertySources();
    if (propertySources.contains(CommandLinePropertySource.COMMAND_LINE_PROPERTY_SOURCE_NAME)) {
        propertySources.addAfter(CommandLinePropertySource.COMMAND_LINE_PROPERTY_SOURCE_NAME,
                new PropertiesPropertySource("vcap", properties));
    } else {
        propertySources.addFirst(new PropertiesPropertySource("vcap", properties));
    }
}

From source file:org.springframework.boot.config.PropertiesPropertySourceLoader.java

@Override
public PropertySource<?> load(Resource resource) {
    try {/*  www .  jav a  2s.  c  om*/
        Properties properties = loadProperties(resource);
        // N.B. this is off by default unless user has supplied logback config in
        // standard location
        if (logger.isDebugEnabled()) {
            logger.debug("Properties loaded from " + resource + ": " + properties);
        }
        return new PropertiesPropertySource(resource.getDescription(), properties);
    } catch (IOException ex) {
        throw new IllegalStateException("Could not load properties from " + resource, ex);
    }
}

From source file:org.springframework.boot.context.initializer.VcapApplicationContextInitializer.java

@Override
public void initialize(ConfigurableApplicationContext applicationContext) {

    ConfigurableEnvironment environment = applicationContext.getEnvironment();
    if (!environment.containsProperty(VCAP_APPLICATION) && !environment.containsProperty(VCAP_SERVICES)) {
        return;//from  ww w  .j  a  va  2  s.  c  om
    }

    Properties properties = new Properties();
    addWithPrefix(properties, getPropertiesFromApplication(environment), "vcap.application.");
    addWithPrefix(properties, getPropertiesFromServices(environment), "vcap.services.");
    MutablePropertySources propertySources = environment.getPropertySources();
    if (propertySources.contains(CommandLinePropertySource.COMMAND_LINE_PROPERTY_SOURCE_NAME)) {
        propertySources.addAfter(CommandLinePropertySource.COMMAND_LINE_PROPERTY_SOURCE_NAME,
                new PropertiesPropertySource("vcap", properties));

    } else {
        propertySources.addFirst(new PropertiesPropertySource("vcap", properties));
    }

}

From source file:org.springframework.boot.context.listener.VcapApplicationListener.java

@Override
public void onApplicationEvent(SpringApplicationEnvironmentAvailableEvent event) {

    ConfigurableEnvironment environment = event.getEnvironment();
    if (!environment.containsProperty(VCAP_APPLICATION) && !environment.containsProperty(VCAP_SERVICES)) {
        return;/*  ww w .  j a v a2 s. c  o m*/
    }

    Properties properties = new Properties();
    addWithPrefix(properties, getPropertiesFromApplication(environment), "vcap.application.");
    addWithPrefix(properties, getPropertiesFromServices(environment), "vcap.services.");
    MutablePropertySources propertySources = environment.getPropertySources();
    if (propertySources.contains(CommandLinePropertySource.COMMAND_LINE_PROPERTY_SOURCE_NAME)) {
        propertySources.addAfter(CommandLinePropertySource.COMMAND_LINE_PROPERTY_SOURCE_NAME,
                new PropertiesPropertySource("vcap", properties));

    } else {
        propertySources.addFirst(new PropertiesPropertySource("vcap", properties));
    }

}

From source file:org.springframework.cloud.gcp.autoconfigure.core.cloudfoundry.GcpCloudFoundryEnvironmentPostProcessor.java

@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
    if (!StringUtils.isEmpty(environment.getProperty(VCAP_SERVICES_ENVVAR))) {
        Map<String, Object> vcapMap = this.parser.parseMap(environment.getProperty(VCAP_SERVICES_ENVVAR));

        Properties gcpCfServiceProperties = new Properties();

        Set<GcpCfService> servicesToMap = new HashSet<>(Arrays.asList(GcpCfService.values()));
        if (vcapMap.containsKey(GcpCfService.MYSQL.getCfServiceName())
                && vcapMap.containsKey(GcpCfService.POSTGRES.getCfServiceName())) {
            LOGGER.warn("Both MySQL and PostgreSQL bound to the app. " + "Not configuring Cloud SQL.");
            servicesToMap.remove(GcpCfService.MYSQL);
            servicesToMap.remove(GcpCfService.POSTGRES);
        }/*  w w w.j a  v a 2 s . com*/

        servicesToMap.forEach((service) -> gcpCfServiceProperties.putAll(retrieveCfProperties(vcapMap,
                service.getGcpServiceName(), service.getCfServiceName(), service.getCfPropNameToGcp())));

        // For Cloud SQL, there are some exceptions to the rule.
        // The instance connection name must be built from three fields.
        if (gcpCfServiceProperties.containsKey("spring.cloud.gcp.sql.instance-name")) {
            String instanceConnectionName = gcpCfServiceProperties
                    .getProperty("spring.cloud.gcp.sql.project-id") + ":"
                    + gcpCfServiceProperties.getProperty("spring.cloud.gcp.sql.region") + ":"
                    + gcpCfServiceProperties.getProperty("spring.cloud.gcp.sql.instance-name");
            gcpCfServiceProperties.put("spring.cloud.gcp.sql.instance-connection-name", instanceConnectionName);
        }
        // The username and password should be in the generic DataSourceProperties.
        if (gcpCfServiceProperties.containsKey("spring.cloud.gcp.sql.username")) {
            gcpCfServiceProperties.put("spring.datasource.username",
                    gcpCfServiceProperties.getProperty("spring.cloud.gcp.sql.username"));
        }
        if (gcpCfServiceProperties.containsKey("spring.cloud.gcp.sql.password")) {
            gcpCfServiceProperties.put("spring.datasource.password",
                    gcpCfServiceProperties.getProperty("spring.cloud.gcp.sql.password"));
        }

        environment.getPropertySources()
                .addFirst(new PropertiesPropertySource("gcpCf", gcpCfServiceProperties));
    }
}