Ejemplo n.º 1
0
  /**
   * Enforce mutual exclusivity and implicit activation of profiles as described in {@link
   * SaganProfiles}.
   */
  @Override
  protected void configureProfiles(ConfigurableEnvironment environment, String[] args) {
    super.configureProfiles(environment, args);

    boolean stagingActive = environment.acceptsProfiles(STAGING);
    boolean productionActive = environment.acceptsProfiles(PRODUCTION);

    if (stagingActive && productionActive) {
      throw new IllegalStateException(
          format(
              "Only one of the following profiles may be specified: [%s]",
              arrayToCommaDelimitedString(new String[] {STAGING, PRODUCTION})));
    }

    if (stagingActive || productionActive) {
      logger.info(
          format(
              "Activating '%s' profile because one of '%s' or '%s' profiles have been specified.",
              CLOUDFOUNDRY, STAGING, PRODUCTION));
      environment.addActiveProfile(CLOUDFOUNDRY);
    } else {
      logger.info(
          "The default 'standalone' profile is active because no other profiles have been specified.");
      environment.addActiveProfile(STANDALONE);
    }
  }
Ejemplo n.º 2
0
 private void applySpringProfiles(
     ConfigurableEnvironment environment, ServletContext servletContext) {
   if (environment.containsProperty("spring_profiles")) {
     String profiles = environment.getProperty("spring_profiles");
     servletContext.log("Setting active profiles: " + profiles);
     environment.setActiveProfiles(StringUtils.commaDelimitedListToStringArray(profiles));
   }
 }
 private void reorderSources(ConfigurableEnvironment environment) {
   ConfigurationPropertySources.finishAndRelocate(environment.getPropertySources());
   PropertySource<?> defaultProperties =
       environment.getPropertySources().remove(DEFAULT_PROPERTIES);
   if (defaultProperties != null) {
     environment.getPropertySources().addLast(defaultProperties);
   }
 }
 private void prependProfile(ConfigurableEnvironment environment, String profile) {
   Set<String> profiles = new LinkedHashSet<String>();
   environment.getActiveProfiles(); // ensure they are initialized
   // But this one should go first (last wins in a property key clash)
   profiles.add(profile);
   profiles.addAll(Arrays.asList(environment.getActiveProfiles()));
   environment.setActiveProfiles(profiles.toArray(new String[profiles.size()]));
 }
 private String getApplicationId(ConfigurableEnvironment environment) {
   String name = environment.resolvePlaceholders(this.name);
   String index = environment.resolvePlaceholders(INDEX_PATTERN);
   String profiles = StringUtils.arrayToCommaDelimitedString(environment.getActiveProfiles());
   if (StringUtils.hasText(profiles)) {
     name = name + ":" + profiles;
   }
   if (!"null".equals(index)) {
     name = name + ":" + index;
   }
   return name;
 }
 /**
  * Add config file property sources to the specified environment.
  *
  * @param environment the environment to add source to
  * @see #addPostProcessors(ConfigurableApplicationContext)
  */
 protected void addPropertySources(
     ConfigurableEnvironment environment, ResourceLoader resourceLoader) {
   RandomValuePropertySource.addToEnvironment(environment);
   try {
     PropertySource<?> defaultProperties =
         environment.getPropertySources().remove(DEFAULT_PROPERTIES);
     new Loader(environment, resourceLoader).load();
     if (defaultProperties != null) {
       environment.getPropertySources().addLast(defaultProperties);
     }
   } catch (IOException ex) {
     throw new IllegalStateException("Unable to load configuration files", ex);
   }
 }
Ejemplo n.º 7
0
  /**
   * @param args
   * @throws InterruptedException
   */
  public static void main(String[] args) throws InterruptedException {

    String conf = "spring.xml";
    AbstractApplicationContext context = new ClassPathXmlApplicationContext(conf);
    ConfigurableEnvironment configurableEnvironment = new StandardEnvironment();
    boolean testMode = false;

    if (args != null && args.length > 0) {
      if ("-test".equals(args[0])) {
        configurableEnvironment.setActiveProfiles("TEST");
        testMode = true;
      } else {
        configurableEnvironment.setActiveProfiles("PROD");
      }
    } else {
      configurableEnvironment.setActiveProfiles("PROD");
    }
    context.setEnvironment(configurableEnvironment);

    PropertyConfigurator.configure("resources/log4j.properties");

    logger.info("Starting launcher...");

    int iteration = 0;

    Launcher launcher = context.getBean("launcher", Launcher.class);

    while (true) {

      iteration++;

      logger.info("Iteration #" + iteration + " at " + new Date());

      logger.info(" Launching zezo automatic routing...");
      launcher.runZezoAutoRouting(testMode);

      /*
       * logger.info(" Launching waypoints..."); launcher.runWaypoints();
       *
       * logger.info(" Launching speed regulation...");
       * launcher.speedRegulation();
       */

      Date nextIteration = getNextIteration();
      long msToSleep = getSecondRemainingBefore(nextIteration);
      logger.info("Waiting for next iteration at " + nextIteration + "\n\n\n");
      Thread.sleep(msToSleep);
    }
  }
 /** @param containerAttributes */
 private void setConfiguredContainerAttributes(ContainerAttributes containerAttributes) {
   Map<String, String> attributes = new HashMap<String, String>();
   for (PropertySource<?> propertySource : environment.getPropertySources()) {
     if (propertySource instanceof EnumerablePropertySource) {
       EnumerablePropertySource<?> ps = (EnumerablePropertySource<?>) propertySource;
       for (String key : ps.getPropertyNames()) {
         if (key.startsWith(CONTAINER_ATTRIBUTES_PREFIX)) {
           String attributeKey = key.replaceAll(CONTAINER_ATTRIBUTES_PREFIX, "");
           attributes.put(attributeKey, environment.getProperty(key));
         }
       }
     }
   }
   containerAttributes.putAll(attributes);
 }
Ejemplo n.º 9
0
  protected static void mess() {
    //		System.setProperty("spring.profiles.active","foo");
    //		    	ConfigurableApplicationContext ctx =
    //		    			new
    // ClassPathXmlApplicationContext("classpath:/com/rooney/spring/spel/Spel-context.xml");

    // can we add appcontext.xml to a genericAppCtx and then add property sources, when call
    // refresh?
    ConfigurableApplicationContext ctx = new GenericApplicationContext();
    ConfigurableEnvironment environment = ctx.getEnvironment();

    MutablePropertySources sources = environment.getPropertySources();
    sources.addFirst(new MyPropertySource());

    System.out.println(ctx.getBean("stringBean"));
  }
 @Override
 public void postProcessEnvironment(
     ConfigurableEnvironment environment, SpringApplication application) {
   String json =
       environment.resolvePlaceholders("${spring.application.json:${SPRING_APPLICATION_JSON:}}");
   if (StringUtils.hasText(json)) {
     processJson(environment, json);
   }
 }
Ejemplo n.º 11
0
  protected static void configureInfoProperties(ConfigurableEnvironment env) {
    SystemInformation systemInformation = new SystemInformation();

    Map<String, Object> infoMap = new HashMap<>();
    infoMap.put("info.fileTimestamp", systemInformation.getDeploymentDateAsString());
    infoMap.put("info.hostname", systemInformation.getHostname());

    env.getPropertySources().addFirst(new MapPropertySource("INFO_MAP", infoMap));
  }
Ejemplo n.º 12
0
  @Bean
  public ContainerAttributes containerAttributes() {

    final ContainerAttributes containerAttributes = new ContainerAttributes();
    setConfiguredContainerAttributes(containerAttributes);

    final String containerIp =
        environment.getProperty(CONTAINER_ATTRIBUTES_PREFIX + ContainerAttributes.IP_ADDRESS_KEY);
    final String containerHostname =
        environment.getProperty(CONTAINER_ATTRIBUTES_PREFIX + ContainerAttributes.HOST_KEY);

    containerAttributes.setIp(
        StringUtils.hasText(containerIp) ? containerIp : RuntimeUtils.getIpAddress());
    containerAttributes.setHost(
        StringUtils.hasText(containerHostname) ? containerHostname : RuntimeUtils.getHost());

    containerAttributes.setPid(RuntimeUtils.getPid());
    return containerAttributes;
  }
 private void addJsonPropertySource(
     ConfigurableEnvironment environment, PropertySource<?> source) {
   MutablePropertySources sources = environment.getPropertySources();
   String name = findPropertySource(sources);
   if (sources.contains(name)) {
     sources.addBefore(name, source);
   } else {
     sources.addFirst(source);
   }
 }
Ejemplo n.º 14
0
  private void applyLog4jConfiguration(
      ConfigurableEnvironment environment, ServletContext servletContext) {

    String log4jConfigLocation = "classpath:log4j.properties";

    if (environment.containsProperty("logging.file")) {
      String location = environment.getProperty("logging.file");
      servletContext.log("Setting LOG_FILE: " + location);
      System.setProperty("LOG_FILE", location);
    } else if (environment.containsProperty("logging.path")) {
      String location = environment.getProperty("logging.path");
      servletContext.log("Setting LOG_PATH: " + location);
      System.setProperty("LOG_PATH", location);
    } else if (environment.containsProperty("logging.config")) {
      log4jConfigLocation = environment.getProperty("logging.config");
    }

    try {
      servletContext.log("Loading log4j config from location: " + log4jConfigLocation);
      Log4jConfigurer.initLogging(log4jConfigLocation);
    } catch (FileNotFoundException e) {
      servletContext.log("Error loading log4j config from location: " + log4jConfigLocation, e);
    }

    MDC.put("context", servletContext.getContextPath());
  }
 @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 {
       propertySources.addFirst(new PropertiesPropertySource("vcap", properties));
     }
   }
 }
 @SuppressWarnings("unchecked")
 private List<ApplicationListener<ApplicationEvent>> getListeners(ConfigurableEnvironment env) {
   String classNames = env.getProperty(PROPERTY_NAME);
   List<ApplicationListener<ApplicationEvent>> listeners =
       new ArrayList<ApplicationListener<ApplicationEvent>>();
   if (StringUtils.hasLength(classNames)) {
     for (String className : StringUtils.commaDelimitedListToSet(classNames)) {
       try {
         Class<?> clazz = ClassUtils.forName(className, ClassUtils.getDefaultClassLoader());
         Assert.isAssignable(
             ApplicationListener.class,
             clazz,
             "class [" + className + "] must implement ApplicationListener");
         listeners.add((ApplicationListener<ApplicationEvent>) BeanUtils.instantiateClass(clazz));
       } catch (Exception ex) {
         throw new ApplicationContextException(
             "Failed to load context listener class [" + className + "]", ex);
       }
     }
   }
   AnnotationAwareOrderComparator.sort(listeners);
   return listeners;
 }
 /**
  * Bind the environment to the {@link SpringApplication}.
  *
  * @param environment the environment to bind
  * @param application the application to bind to
  */
 protected void bindToSpringApplication(
     ConfigurableEnvironment environment, SpringApplication application) {
   RelaxedDataBinder binder = new RelaxedDataBinder(application, "spring.main");
   binder.setConversionService(this.conversionService);
   binder.bind(new PropertySourcesPropertyValues(environment.getPropertySources()));
 }
 @Test
 public void noBootstrapProperties() {
   assertFalse(environment.getPropertySources().contains("bootstrap"));
 }
 @Override
 public void postProcessEnvironment(
     ConfigurableEnvironment environment, SpringApplication application) {
   assertThat(environment.getPropertySources().size(), is(equalTo(4)));
 }
 @Override
 public void initialize(ConfigurableWebApplicationContext ctx) {
   ConfigurableEnvironment environment = ctx.getEnvironment();
   environment.setActiveProfiles("prod");
 }
 @Override
 public void initialize(ConfigurableApplicationContext applicationContext) {
   ConfigurableEnvironment environment = applicationContext.getEnvironment();
   environment.setActiveProfiles("alarms-" + environment.getProperty("httpd.alarms.db.type"));
 }