Java 类org.springframework.core.io.support.ResourcePropertySource 实例源码

项目:oma-riista-web    文件:AwsCloudRuntimeConfig.java   
public static Optional<ResourcePropertySource> createPropertySource() {
    try (final AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext()) {
        ctx.register(AwsCloudRuntimeConfig.class);
        ctx.register(RuntimeEnvironmentUtil.class);
        ctx.refresh();
        ctx.start();

        if (ctx.getBean(RuntimeEnvironmentUtil.class).isProductionEnvironment()) {
            final String s3config = ctx.getEnvironment().getProperty("aws.config.s3location");
            final Resource resource = ctx.getBean(SimpleStorageResourceLoader.class).getResource(s3config);
            return Optional.of(new ResourcePropertySource("aws", resource));
        }

        return Optional.empty();

    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
项目:iris    文件:ContargoApplicationInitializer.java   
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {

    try {
        String env = System.getenv(ENVIRONMENT);

        if (env == null) {
            env = System.getProperty(ENVIRONMENT, "dev");
        }

        ConfigurableEnvironment environment = applicationContext.getEnvironment();

        environment.getPropertySources()
            .addLast(new ResourcePropertySource("classpath:application-" + env + ".properties"));
        environment.getPropertySources().addLast(new ResourcePropertySource("classpath:application.properties"));
    } catch (IOException ex) {
        LOG.warn("Unable to load application properties!", ex);
    }
}
项目:proctor-pipet    文件:PropertiesInitializer.java   
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;
}
项目:iupload    文件:PropertiesInitializer.java   
protected boolean tryAddPropertySource(ConfigurableApplicationContext applicationContext, MutablePropertySources propSources, 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;
    }
    log.debug("Successfully added property source: " + filePath);
    return true;
}
项目:iql    文件:PropertiesInitializer.java   
protected boolean tryAddPropertySource(ConfigurableApplicationContext applicationContext, MutablePropertySources propSources, 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;
    }
    log.debug("Successfully added property source: " + filePath);
    return true;
}
项目:lams    文件:ConfigurationClassParser.java   
public List<PropertySource<?>> getPropertySources() {
    List<PropertySource<?>> propertySources = new LinkedList<PropertySource<?>>();
    for (Map.Entry<String, List<ResourcePropertySource>> entry : this.propertySources.entrySet()) {
        propertySources.add(0, collatePropertySources(entry.getKey(), entry.getValue()));
    }
    return propertySources;
}
项目:lams    文件:ConfigurationClassParser.java   
private PropertySource<?> collatePropertySources(String name, List<ResourcePropertySource> propertySources) {
    if (propertySources.size() == 1) {
        return propertySources.get(0).withName(name);
    }
    CompositePropertySource result = new CompositePropertySource(name);
    for (int i = propertySources.size() - 1; i >= 0; i--) {
        result.addPropertySource(propertySources.get(i));
    }
    return result;
}
项目:flow-platform    文件:AppInit.java   
public void onStartup(ServletContext servletContext) throws ServletException {
    LOGGER.trace("Initializing Flow Control Center for %s", servletContext.getServerInfo());

    // get class loader
    ClassLoader appClassLoader = appClassLoader();

    // Create ApplicationContext and set class loader
    AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
    applicationContext.setClassLoader(appClassLoader);

    applicationContext.register(WebConfig.class);
    Set<Class<?>> cloudClasses = CloudJarResourceLoader.configClasses(appClassLoader);
    if (!cloudClasses.isEmpty()) {
        applicationContext.register((cloudClasses.toArray(new Class<?>[cloudClasses.size()])));
    }

    applicationContext.setServletContext(servletContext);

    // set app property resource
    try {
        AppResourceLoader propertyLoader = new PropertyResourceLoader();
        applicationContext
            .getEnvironment()
            .getPropertySources()
            .addFirst(new ResourcePropertySource(propertyLoader.find()));
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    // Add the servlet mapping manually and make it initialize automatically
    DispatcherServlet dispatcherServlet = new DispatcherServlet(applicationContext);
    ServletRegistration.Dynamic servlet = servletContext.addServlet("mvc-dispatcher", dispatcherServlet);

    servlet.addMapping("/");
    servlet.setAsyncSupported(true);
    servlet.setLoadOnStartup(1);
}
项目:flow-platform    文件:TestBase.java   
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
    try {
        applicationContext
            .getEnvironment()
            .getPropertySources()
            .addFirst(new ResourcePropertySource(new PropertyResourceLoader().find()));
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
项目:oma-riista-web    文件:AbstractMMLServiceTest.java   
protected static MMLWebFeatureServiceRequestTemplate createRequestTemplate() throws IOException {
    ClassPathResource classPathResource = new ClassPathResource("configuration/application.properties");
    ResourcePropertySource propertySource = new ResourcePropertySource(classPathResource);
    String uri = propertySource.getProperty("wfs.mml.uri").toString();
    String username = propertySource.getProperty("wfs.mml.username").toString();
    String password = propertySource.getProperty("wfs.mml.password").toString();

    MMLProperties mmlProperties = new MMLProperties(uri, username, password);
    ClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();

    return new MMLWebFeatureServiceRequestTemplate(mmlProperties, requestFactory);
}
项目:spring4-understanding    文件:ConfigurationClassParser.java   
private void addPropertySource(ResourcePropertySource propertySource) {
    String name = propertySource.getName();
    MutablePropertySources propertySources = ((ConfigurableEnvironment) this.environment).getPropertySources();
    if (propertySources.contains(name) && this.propertySourceNames.contains(name)) {
        // We've already added a version, we need to extend it
        PropertySource<?> existing = propertySources.get(name);
        if (existing instanceof CompositePropertySource) {
            ((CompositePropertySource) existing).addFirstPropertySource(propertySource.withResourceName());
        }
        else {
            if (existing instanceof ResourcePropertySource) {
                existing = ((ResourcePropertySource) existing).withResourceName();
            }
            CompositePropertySource composite = new CompositePropertySource(name);
            composite.addPropertySource(propertySource.withResourceName());
            composite.addPropertySource(existing);
            propertySources.replace(name, composite);
        }
    }
    else {
        if (this.propertySourceNames.isEmpty()) {
            propertySources.addLast(propertySource);
        }
        else {
            String firstProcessed = this.propertySourceNames.get(this.propertySourceNames.size() - 1);
            propertySources.addBefore(firstProcessed, propertySource);
        }
    }
    this.propertySourceNames.add(name);
}
项目:my-spring-cache-redis    文件:ConfigurationClassParser.java   
public List<PropertySource<?>> getPropertySources() {
    List<PropertySource<?>> propertySources = new LinkedList<PropertySource<?>>();
    for (Map.Entry<String, List<ResourcePropertySource>> entry : this.propertySources.entrySet()) {
        propertySources.add(0, collatePropertySources(entry.getKey(), entry.getValue()));
    }
    return propertySources;
}
项目:my-spring-cache-redis    文件:ConfigurationClassParser.java   
private PropertySource<?> collatePropertySources(String name, List<ResourcePropertySource> propertySources) {
    if (propertySources.size() == 1) {
        return propertySources.get(0).withName(name);
    }
    CompositePropertySource result = new CompositePropertySource(name);
    for (int i = propertySources.size() - 1; i >= 0; i--) {
        result.addPropertySource(propertySources.get(i));
    }
    return result;
}
项目:c2mon    文件:C2monApplicationListener.java   
@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
  ConfigurableEnvironment environment = event.getEnvironment();
  String propertySource = environment.getProperty("c2mon.client.conf.url");

  if (propertySource != null) {
    try {
      environment.getPropertySources().addAfter("systemEnvironment", new ResourcePropertySource(propertySource));
    } catch (IOException e) {
      throw new RuntimeException("Could not read property source", e);
    }
  }
}
项目:c2mon    文件:CommonModule.java   
/**
 * Listens for the {@link ApplicationEnvironmentPreparedEvent} and injects
 * ${c2mon.server.properties} into the environment with the highest precedence
 * (if it exists). This is in order to allow users to point to an external
 * properties file via ${c2mon.server.properties}.
 */
@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
  ConfigurableEnvironment environment = event.getEnvironment();
  String propertySource = environment.getProperty("c2mon.server.properties");

  if (propertySource != null) {
    try {
      environment.getPropertySources().addAfter("systemEnvironment", new ResourcePropertySource(propertySource));
    } catch (IOException e) {
      throw new RuntimeException("Could not read property source", e);
    }
  }
}
项目:boilerplate    文件:InternalConfig.java   
/**
 * Without this bean declared, the @Value placeholder above will not be resolved properly.
 *
 * Using @PropertySource by itself will not work; nor will it work if this method is not declared static.
 *
 * See {@link org.springframework.context.annotation.PropertySource} JavaDoc for more info.
 */
@Bean
static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() throws IOException {
    PropertySourcesPlaceholderConfigurer result = new PropertySourcesPlaceholderConfigurer();
    MutablePropertySources sources = new MutablePropertySources();
    sources.addFirst(new ResourcePropertySource("classpath:app.properties"));
    result.setPropertySources(sources);
    result.setIgnoreUnresolvablePlaceholders(false);
    return result;
}
项目:boilerplate    文件:SpringMissingPropertyDemo.java   
/**
 * Without this method, e.g. if you try to use @PropertySource("classpath:app.properties") on the
 * WrongConfig class, you don't even get an error at all - try it! The behaviour is the same as the below
 * with setIgnoreUnresolvablePlaceholders(true).
 */
@Bean
static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() throws IOException {
    PropertySourcesPlaceholderConfigurer result = new PropertySourcesPlaceholderConfigurer();
    MutablePropertySources sources = new MutablePropertySources();
    sources.addFirst(new ResourcePropertySource("classpath:app.properties"));
    result.setPropertySources(sources);
    result.setIgnoreUnresolvablePlaceholders(false);
    return result;
}
项目:spring    文件:ConfigurationClassParser.java   
private void addPropertySource(PropertySource<?> propertySource) {
    String name = propertySource.getName();
    MutablePropertySources propertySources = ((ConfigurableEnvironment) this.environment).getPropertySources();
    if (propertySources.contains(name) && this.propertySourceNames.contains(name)) {
        // We've already added a version, we need to extend it
        PropertySource<?> existing = propertySources.get(name);
        PropertySource<?> newSource = (propertySource instanceof ResourcePropertySource ?
                ((ResourcePropertySource) propertySource).withResourceName() : propertySource);
        if (existing instanceof CompositePropertySource) {
            ((CompositePropertySource) existing).addFirstPropertySource(newSource);
        }
        else {
            if (existing instanceof ResourcePropertySource) {
                existing = ((ResourcePropertySource) existing).withResourceName();
            }
            CompositePropertySource composite = new CompositePropertySource(name);
            composite.addPropertySource(newSource);
            composite.addPropertySource(existing);
            propertySources.replace(name, composite);
        }
    }
    else {
        if (this.propertySourceNames.isEmpty()) {
            propertySources.addLast(propertySource);
        }
        else {
            String firstProcessed = this.propertySourceNames.get(this.propertySourceNames.size() - 1);
            propertySources.addBefore(firstProcessed, propertySource);
        }
    }
    this.propertySourceNames.add(name);
}
项目:spring-boot-multi-module-property-files    文件:PropertyFilePatternRegisteringListener.java   
private void addFileToEnvironment(ConfigurableEnvironment environment, String file) throws IOException {
  ClassPathResource classPathResource = new ClassPathResource(file);
  if (classPathResource.exists()) {
    environment.getPropertySources()
               .addLast(new ResourcePropertySource(classPathResource));
  }
}
项目:spring-boot-multi-module-property-files    文件:PropertyFilePatternRegisteringListener.java   
private void addFileToEnvironment(ConfigurableEnvironment environment, String file) throws IOException {
  ClassPathResource classPathResource = new ClassPathResource(file);
  if (classPathResource.exists()) {
    environment.getPropertySources()
               .addLast(new ResourcePropertySource(classPathResource));
  }
}
项目:director-aws-plugin    文件:PropertyResolvers.java   
private static PropertySource buildPropertySource(String name, String loc,
    boolean allowMissing)
    throws IOException {
  try {
    return new ResourcePropertySource(name, loc,
                                      PropertyResolvers.class.getClassLoader());
  } catch (IOException e) {
    if (allowMissing) {
      return null;
    }
    throw new IOException("Unable to load " + name +
        " properties from " + loc, e);
  }
}
项目:mybatis-spring-1.2.2    文件:ConfigurationClassParser.java   
/**
 * Process the given <code>@PropertySource</code> annotation metadata.
 * @param propertySource metadata for the <code>@PropertySource</code> annotation found
 * @throws IOException if loading a property source failed
 */
private void processPropertySource(AnnotationAttributes propertySource) throws IOException {
    String name = propertySource.getString("name");
    String[] locations = propertySource.getStringArray("value");
    int locationCount = locations.length;
    if (locationCount == 0) {
        throw new IllegalArgumentException("At least one @PropertySource(value) location is required");
    }
    for (int i = 0; i < locationCount; i++) {
        locations[i] = this.environment.resolveRequiredPlaceholders(locations[i]);
    }
    ClassLoader classLoader = this.resourceLoader.getClassLoader();
    if (!StringUtils.hasText(name)) {
        for (String location : locations) {
            this.propertySources.push(new ResourcePropertySource(location, classLoader));
        }
    }
    else {
        if (locationCount == 1) {
            this.propertySources.push(new ResourcePropertySource(name, locations[0], classLoader));
        }
        else {
            CompositePropertySource ps = new CompositePropertySource(name);
            for (int i = locations.length - 1; i >= 0; i--) {
                ps.addPropertySource(new ResourcePropertySource(locations[i], classLoader));
            }
            this.propertySources.push(ps);
        }
    }
}
项目:indoqa-boot    文件:AbstractIndoqaBootApplication.java   
private static ResourcePropertySource getProperties(String propertiesLocation) {
    try {
        return new ResourcePropertySource(propertiesLocation);
    } catch (IOException e) {
        throw new ApplicationInitializationException("Error while reading properties from " + propertiesLocation, e);
    }
}
项目:indoqa-boot    文件:AbstractIndoqaBootApplication.java   
private void initializeExternalProperties() {
    if (isExternalPropertiesFileProvided()) {
        String propertiesLocation = System.getProperty("properties");
        ResourcePropertySource propertySource = getProperties(propertiesLocation);
        this.context.getEnvironment().getPropertySources().addFirst(propertySource);
        LOGGER.info("Using external properties from {}", propertiesLocation);
    }
    else {
        LOGGER.info("No external properties set. Use the system property 'properties' "
            + "to provide application properties as a Java properties file.");
    }
}
项目:webanno    文件:WebAnnoApplicationContextInitializer.java   
@Override
public void initialize(ConfigurableApplicationContext aApplicationContext)
{
    ConfigurableEnvironment aEnvironment = aApplicationContext.getEnvironment();

    File settings = SettingsUtil.getSettingsFile();

    // If settings were found, add them to the environment
    if (settings != null) {
        log.info("Settings: " + settings);
        try {
            aEnvironment.getPropertySources().addFirst(
                    new ResourcePropertySource(new FileSystemResource(settings)));
        }
        catch (IOException e) {
            throw new IllegalStateException(e);
        }
    }

    // Activate bean profile depending on authentication mode
    if (AUTH_MODE_PREAUTH.equals(aEnvironment.getProperty(SettingsUtil.CFG_AUTH_MODE))) {
        aEnvironment.setActiveProfiles(PROFILE_PREAUTH);
        log.info("Authentication: pre-auth");
    }
    else {
        aEnvironment.setActiveProfiles(PROFILE_DATABASE);
        log.info("Authentication: database");
    }
}
项目:exchange    文件:BisqEnvironment.java   
PropertySource<?> getAppDirProperties() throws Exception {
    Resource resource = getAppDirPropertiesResource();

    if (!resource.exists())
        return new PropertySource.StubPropertySource(BISQ_APP_DIR_PROPERTY_SOURCE_NAME);

    return new ResourcePropertySource(BISQ_APP_DIR_PROPERTY_SOURCE_NAME, resource);
}
项目:lavagna    文件:LavagnaEnvironment.java   
public LavagnaEnvironment(ConfigurableEnvironment environment) {
    this.environment = environment;

    if (environment.containsProperty(LAVAGNA_CONFIG_LOCATION) && StringUtils.isNotBlank(environment.getProperty(LAVAGNA_CONFIG_LOCATION))) {

        String configLocation = environment.getProperty(LAVAGNA_CONFIG_LOCATION);

        LOG.info("Detected config file {}, loading it", configLocation);
        try {
            environment.getPropertySources().addFirst(new ResourcePropertySource(new UrlResource(configLocation)));
        } catch (IOException ioe) {
            throw new IllegalStateException("error while loading external configuration file at " + configLocation, ioe);
        }
    }

    setSystemPropertyIfNull(environment, "datasource.dialect", "HSQLDB");
    setSystemPropertyIfNull(environment, "datasource.url", "jdbc:hsqldb:mem:lavagna");
    setSystemPropertyIfNull(environment, "datasource.username", "sa");
    setSystemPropertyIfNull(environment, "datasource.password", "");
    setSystemPropertyIfNull(environment, "spring.profiles.active", "dev");

    logUse("datasource.dialect");
    logUse("datasource.url");
    logUse("datasource.username");
    logUse("spring.profiles.active");

}
项目:class-guard    文件:ConfigurationClassParser.java   
/**
 * Process the given <code>@PropertySource</code> annotation metadata.
 * @param propertySource metadata for the <code>@PropertySource</code> annotation found
 * @throws IOException if loading a property source failed
 */
private void processPropertySource(AnnotationAttributes propertySource) throws IOException {
    String name = propertySource.getString("name");
    String[] locations = propertySource.getStringArray("value");
    int locationCount = locations.length;
    if (locationCount == 0) {
        throw new IllegalArgumentException("At least one @PropertySource(value) location is required");
    }
    for (int i = 0; i < locationCount; i++) {
        locations[i] = this.environment.resolveRequiredPlaceholders(locations[i]);
    }
    ClassLoader classLoader = this.resourceLoader.getClassLoader();
    if (!StringUtils.hasText(name)) {
        for (String location : locations) {
            this.propertySources.push(new ResourcePropertySource(location, classLoader));
        }
    }
    else {
        if (locationCount == 1) {
            this.propertySources.push(new ResourcePropertySource(name, locations[0], classLoader));
        }
        else {
            CompositePropertySource ps = new CompositePropertySource(name);
            for (int i = locations.length - 1; i >= 0; i--) {
                ps.addPropertySource(new ResourcePropertySource(locations[i], classLoader));
            }
            this.propertySources.push(ps);
        }
    }
}
项目:bulbs-core    文件:TestConfig.java   
@Override
public void initialize(ConfigurableApplicationContext ctx) {
    log.info("INIT TestConfig");
    //~ Load (test overriding) property resource(s) to be registered in environment with highest precedence!
    ConfigurableEnvironment env = ctx.getEnvironment();

    Resource runtimeProps = ctx.getResource(TEST_PROPERTIES_PATH);
    try {
        env.getPropertySources().addFirst(new ResourcePropertySource(runtimeProps));
    } catch (IOException ioex) {
        throw new Error(ioex);
    }
}
项目:ws-proxy    文件:WsProxyWebApplicationInitializer.java   
private AnnotationConfigWebApplicationContext createContext(final Class<?>... annotatedClasses) {
    AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
    try {
        context.getEnvironment().getPropertySources()
                .addFirst(new ResourcePropertySource("classpath:active_environment.properties"));
    } catch (IOException ioException) {
        throw new RuntimeException(ioException);
    }
    context.register(annotatedClasses);
    return context;
}
项目:icearchiva    文件:SpringAppContextInitializer.java   
@Override
public void initialize(ConfigurableWebApplicationContext applicationContext) {
    MutablePropertySources propertySources = applicationContext.getEnvironment().getPropertySources();
    try {
        propertySources.addFirst(new ResourcePropertySource("classpath:/spring-profiles.properties"));
    } catch (Exception e) {}
}
项目:salespoint    文件:ChangelogCreator.java   
private static RestTemplate setUpRestTemplate() throws IOException {

        FileSystemResource resource = new FileSystemResource("env.properties");
        ResourcePropertySource propertySource = new ResourcePropertySource(resource);
        String username = propertySource.getProperty("github.username").toString();
        String password = propertySource.getProperty("github.password").toString();

        BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));

        AuthCache authCache = new BasicAuthCache();
        authCache.put(new HttpHost("api.github.com", 443, "https"), new BasicScheme());

        final HttpClientContext context = HttpClientContext.create();
        context.setCredentialsProvider(credentialsProvider);
        context.setAuthCache(authCache);

        ClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(HttpClientBuilder.create().build()) {

            @Override
            protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) {
                return context;
            }
        };

        RestTemplate template = new RestTemplate();
        template.setRequestFactory(factory);

        return template;
    }
项目:spring4-understanding    文件:TestPropertySourceUtils.java   
/**
 * Add the {@link Properties} files from the given resource {@code locations}
 * to the {@link Environment} of the supplied {@code context}.
 * <p>Property placeholders in resource locations (i.e., <code>${...}</code>)
 * will be {@linkplain Environment#resolveRequiredPlaceholders(String) resolved}
 * against the {@code Environment}.
 * <p>Each properties file will be converted to a {@link ResourcePropertySource}
 * that will be added to the {@link PropertySources} of the environment with
 * highest precedence.
 * @param context the application context whose environment should be updated;
 * never {@code null}
 * @param locations the resource locations of {@code Properties} files to add
 * to the environment; potentially empty but never {@code null}
 * @since 4.1.5
 * @see ResourcePropertySource
 * @see TestPropertySource#locations
 * @throws IllegalStateException if an error occurs while processing a properties file
 */
public static void addPropertiesFilesToEnvironment(ConfigurableApplicationContext context,
        String[] locations) {
    Assert.notNull(context, "context must not be null");
    Assert.notNull(locations, "locations must not be null");
    try {
        ConfigurableEnvironment environment = context.getEnvironment();
        for (String location : locations) {
            String resolvedLocation = environment.resolveRequiredPlaceholders(location);
            Resource resource = context.getResource(resolvedLocation);
            environment.getPropertySources().addFirst(new ResourcePropertySource(resource));
        }
    }
    catch (IOException e) {
        throw new IllegalStateException("Failed to add PropertySource to Environment", e);
    }
}
项目:owsi-core-parent    文件:AbstractExtendedApplicationContextInitializer.java   
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
    try {
        // définition d'un environnement par défaut (permet de configurer l'application avant le chargement
        // des beans) ; sert entre autres pour la définiton des profils spring à charger.
        ResourcePropertySource resourcePropertySource = new ResourcePropertySource(getMainConfigurationLocation());

        applicationContext.getEnvironment().getPropertySources().addFirst(resourcePropertySource);
        String customLocation = getCustomConfigurationLocation();
        if (applicationContext.getResource(customLocation).exists()) {
            applicationContext.getEnvironment().getPropertySources().addFirst(new ResourcePropertySource(customLocation));
        }

        // configuration de log4j ; permet de spécifier plusieurs fichiers de propriétés qui seront combinés entre
        // eux pour faire le fichier global de configuration.
        if (applicationContext.getEnvironment().getProperty(SPRING_LOG4J_CONFIGURATION) != null) {
            String locationsString = applicationContext.getEnvironment().getProperty(SPRING_LOG4J_CONFIGURATION);
            List<String> locations = StringUtils.splitAsList(locationsString, ",");
            MutablePropertySources sources = new MutablePropertySources();
            boolean hasSource = false;
            List<String> propertyNames = new ArrayList<String>();
            for (String location : locations) {
                if (applicationContext.getResource(location).exists()) {
                    LOGGER.info(String.format("Log4j : %1$s added", location));
                    hasSource = true;
                    ResourcePropertySource source = new ResourcePropertySource(applicationContext.getResource(location));
                    sources.addFirst(source);
                    propertyNames.addAll(Arrays.asList(source.getPropertyNames()));
                } else {
                    LOGGER.warn(String.format("Log4j : %1$s not found", location));
                }
            }

            if (hasSource) {
                PropertySourcesPropertyResolver resolver = new PropertySourcesPropertyResolver(sources);
                resolver.setPlaceholderPrefix("#{");
                resolver.setPlaceholderSuffix("}");
                Properties properties = new Properties();
                for (String propertyName : propertyNames) {
                    if (resolver.containsProperty(propertyName)) {
                        LOGGER.debug(String.format("Log4j : property resolved %1$s -> %2$s", propertyName, resolver.getProperty(propertyName)));
                        properties.put(propertyName, resolver.getProperty(propertyName));
                    } else {
                        LOGGER.warn(String.format("Log4j : property %1$s cannot be resolved", propertyName));
                    }
                }
                properties.setProperty("log4j.reset", "true");
                PropertyConfigurator.configure(properties);
            } else {
                LOGGER.warn("Log4j : no additional files configured in %1$s", locationsString);
            }
        }
    } catch (IOException e) {
        throw new IllegalStateException("Error loading configuration files", e);
    }
}
项目:eHMP    文件:BootstrapTests.java   
@Test
    public void testInitializeWithHmpHomeSystemPropertyAndDefaults() throws Exception {
        Properties versionInfo = new Properties();
        versionInfo.put(HmpProperties.VERSION, "fubar-23.42");
        versionInfo.put(HmpProperties.BUILD_DATE, "Jul 20,1944");

        Properties hmpDefaults = new Properties();
        hmpDefaults.put(HmpProperties.SERVER_PORT_HTTP, MOCK_HTTP_PORT);
        hmpDefaults.put(HmpProperties.SERVER_PORT_HTTPS, MOCK_HTTPS_PORT);

        setUpMockHmpHomeSystemProperty();
        when(mockApplicationContext.getResource("classpath:/version.properties")).thenReturn(createMockPropertiesResource(versionInfo));
        when(mockApplicationContext.getResource("classpath:/hmp-defaults.properties")).thenReturn(createMockPropertiesResource(hmpDefaults));
        Resource mockHmpPropertiesResource = mock(Resource.class);
        when(mockHomeDirectory.createRelative(HMP_PROPERTIES_FILE_NAME)).thenReturn(mockHmpPropertiesResource);
        when(mockHmpPropertiesResource.exists()).thenReturn(false); // no hmp.properties resource exists, therefore use defaults

        when(mockEnviroment.getProperty(VERSION)).thenReturn("fubar-23.42");
        when(mockEnviroment.getProperty(BUILD_DATE)).thenReturn("Jul 20,1944");
        when(mockEnviroment.getProperty(SERVER_HOST)).thenReturn(MOCK_HOST);
        when(mockEnviroment.getProperty(SERVER_PORT_HTTP)).thenReturn(MOCK_HTTP_PORT);
        when(mockEnviroment.getProperty(SERVER_PORT_HTTPS)).thenReturn(MOCK_HTTPS_PORT);
        when(mockEnviroment.getProperty(SERVER_ID)).thenReturn(MOCK_SERVER_ID);
        when(mockEnviroment.getProperty(EHCACHE_DATA_DIR)).thenReturn("java.io.tmpdir");

        Bootstrap bootstrap = new Bootstrap();
        bootstrap.initialize(mockApplicationContext);

        InOrder inOrder = inOrder(mockPropertySources);

        ArgumentCaptor<ResourcePropertySource> versionPropertySourceArg = ArgumentCaptor.forClass(ResourcePropertySource.class);
        inOrder.verify(mockPropertySources, times(1)).addFirst(versionPropertySourceArg.capture());
        assertThat(versionPropertySourceArg.getValue().getName(), is(Bootstrap.HMP_VERSION_PROPERTIES_PROPERTY_SOURCE_NAME));

        ArgumentCaptor<PropertySource> hmpDefaultsPropertySourceArg = ArgumentCaptor.forClass(PropertySource.class);
        inOrder.verify(mockPropertySources, times(1)).addLast(hmpDefaultsPropertySourceArg.capture());
        assertThat(hmpDefaultsPropertySourceArg.getValue().getName(), is(Bootstrap.HMP_DEFAULT_PROPERTIES_PROPERTY_SOURCE_NAME));

        ArgumentCaptor<MapPropertySource> runtimeDefaultsPropertySourceArg = ArgumentCaptor.forClass(MapPropertySource.class);
        inOrder.verify(mockPropertySources, times(1)).addFirst(runtimeDefaultsPropertySourceArg.capture());
        assertThat(runtimeDefaultsPropertySourceArg.getValue().getName(), is(Bootstrap.HMP_PROPERTIES_PROPERTY_SOURCE_NAME));
        // check the initial defaults
        assertThat(runtimeDefaultsPropertySourceArg.getValue().getProperty(SERVER_ID).toString(), notNullValue());
        assertThat(runtimeDefaultsPropertySourceArg.getValue().getProperty(SERVER_HOST).toString(), is(InetAddress.getLocalHost().getHostName()));

        ArgumentCaptor<MapPropertySource> calculatedPropertySourceArg = ArgumentCaptor.forClass(MapPropertySource.class);
        inOrder.verify(mockPropertySources, times(1)).addLast(calculatedPropertySourceArg.capture());
        assertThat(calculatedPropertySourceArg.getValue().getName(), is(Bootstrap.HMP_CALCULATED_PROPERTIES_PROPERTY_SOURCE_NAME));
        // check the calculated values
        assertThat(calculatedPropertySourceArg.getValue().getProperty(SERVER_URL).toString(), is("https://" + MOCK_HOST + ":" + MOCK_HTTPS_PORT + "/"));
        assertThat(calculatedPropertySourceArg.getValue().getProperty(ACTIVEMQ_BROKER_URL).toString(), is("vm://hmp-" + MOCK_SERVER_ID));
        assertThat(calculatedPropertySourceArg.getValue().getProperty(SOLR_URL).toString(), is("http://" + MOCK_HOST + ":" + MOCK_HTTP_PORT + "/solr/"));

        // This is not cross-platform and it's taking too long to untangle the properties to make them cross-platform for the sake of these tests.
//
//        assertThat(calculatedPropertySourceArg.getValue().getProperty(ACTIVEMQ_DATA_DIR).toString(), is(MOCK_HMP_HOME_PATH + File.separator + "activemq-data"));
//        assertThat(calculatedPropertySourceArg.getValue().getProperty(EHCACHE_DATA_DIR).toString(), is(MOCK_HMP_HOME_PATH + "/ehcache"));
//        assertThat(calculatedPropertySourceArg.getValue().getProperty(LOGS_DIR).toString(), is(MOCK_HMP_HOME_PATH + "/logs"));
//
        /*
        calculatedProps.put(ACTIVEMQ_DATA_DIR, "${homeDirCanonicalPath}/activemq-data");
        calculatedProps.put(EHCACHE_DATA_DIR, "${homeDirCanonicalPath}/ehcache");
         */
    }
项目:kaa    文件:AbstractServerApplication.java   
/**
 * Initialize {@link ApplicationContext} and populates
 * {@link org.springframework.core.env.Environment} with values from properties files
 *
 * @param args arguments that overwrite default configuration and properties files
 */
public void startAndWait(String[] args) {
  LOG.info("{} application starting...", getName());
  Environment.logState();

  String[] appContextXmls = defaultContextFiles;
  String[] appPropertiesFiles = defaultConfigurationFiles;
  if (args.length > 0) {
    List<String> contexts = new ArrayList<>();
    List<String> properties = new ArrayList<>();
    for (String arg : args) {
      if (arg.endsWith(XML) || arg.endsWith(XML.toUpperCase())) {
        contexts.add(arg);
      } else if (arg.endsWith(PROPERTIES) || arg.endsWith(PROPERTIES.toUpperCase())) {
        properties.add(arg);
      }
    }
    if (!contexts.isEmpty()) {
      appContextXmls = contexts.toArray(new String[contexts.size()]);
    }
    if (!properties.isEmpty()) {
      appPropertiesFiles = properties.toArray(new String[properties.size()]);
    }
  }

  ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(appContextXmls, false);
  try {
    MutablePropertySources sources = ctx.getEnvironment().getPropertySources();
    for (String propertyFile : appPropertiesFiles) {
      try {
        sources.addLast(new ResourcePropertySource(propertyFile, AbstractServerApplication.class
            .getClassLoader()));
      } catch (IOException ioException) {
        LOG.error(
                "Can't load properties file {} from classpath, exception catched {}",
                propertyFile,
                ioException
        );
        return;
      }
    }
    ctx.refresh();
    init(ctx);
  } catch (Exception initializationException) {
    LOG.info("Error during initialization of context", initializationException);
    throw initializationException;
  } finally {
    ctx.close();
  }

  LOG.info("{} application stopped.", getName());
}
项目:gazpachoquest    文件:EnviromentDiscovery.java   
@Override
public void initialize(ConfigurableApplicationContext ctx) {
    ConfigurableEnvironment environment = ctx.getEnvironment();
    String activeProfiles[] = environment.getActiveProfiles();

    if (activeProfiles.length == 0) {
        environment.setActiveProfiles("test,db_hsql");
    }

    logger.info("Application running using profiles: {}", Arrays.toString(environment.getActiveProfiles()));

    String instanceInfoString = environment.getProperty(GAZPACHO_APP_KEY);

    String dbEngine = null;
    for (String profile : activeProfiles) {
        if (profile.startsWith("db_")) {
            dbEngine = profile;
            break;
        }
    }
    try {
        environment.getPropertySources().addLast(
                new ResourcePropertySource(String.format("classpath:/database/%s.properties", dbEngine)));
    } catch (IOException e) {
        throw new IllegalStateException(dbEngine + ".properties not found in classpath", e);
    }

    PropertySourcesPlaceholderConfigurer propertyHolder = new PropertySourcesPlaceholderConfigurer();

    Map<String, String> environmentProperties = parseInstanceInfo(instanceInfoString);
    if (!environmentProperties.isEmpty()) {
        logger.info("Overriding default properties with {}", instanceInfoString);
        Properties properties = new Properties();
        for (String key : environmentProperties.keySet()) {
            String value = environmentProperties.get(key);
            properties.put(key, value);
        }
        environment.getPropertySources().addLast(new PropertiesPropertySource("properties", properties));

        propertyHolder.setEnvironment(environment);
        // ctx.addBeanFactoryPostProcessor(propertyHolder);
        // ctx.refresh();
    }
}
项目:eHMP    文件:Bootstrap.java   
/**
 * Property defaults that are "baked" in to the HMP, but can still be overridden.
 *
 * @param resourceLoader
 * @return
 */
protected PropertySource createHmpDefaultsPropertySource(ResourceLoader resourceLoader) throws IOException {
    return new ResourcePropertySource(HMP_DEFAULT_PROPERTIES_PROPERTY_SOURCE_NAME, resourceLoader.getResource("classpath:/hmp-defaults.properties"));
}