Example usage for org.springframework.context ApplicationContext getEnvironment

List of usage examples for org.springframework.context ApplicationContext getEnvironment

Introduction

In this page you can find the example usage for org.springframework.context ApplicationContext getEnvironment.

Prototype

Environment getEnvironment();

Source Link

Document

Return the Environment associated with this component.

Usage

From source file:com.logsniffer.app.CoreAppConfig.java

@Bean(name = { BEAN_LOGSNIFFER_PROPS })
@Autowired//from www  . j a  v  a  2s  .c  o m
public PropertiesFactoryBean logSnifferProperties(final ApplicationContext ctx) throws IOException {
    if (ctx.getEnvironment().acceptsProfiles("!" + ContextProvider.PROFILE_NONE_QA)) {
        final File qaFile = File.createTempFile("logsniffer", "qa");
        qaFile.delete();
        final String qaHomeDir = qaFile.getPath();
        logger.info("QA mode active, setting random home directory: {}", qaHomeDir);
        System.setProperty("logsniffer.home", qaHomeDir);
    }
    final PathMatchingResourcePatternResolver pathMatcher = new PathMatchingResourcePatternResolver();
    Resource[] classPathProperties = pathMatcher.getResources("classpath*:/config/**/logsniffer-*.properties");
    final Resource[] metainfProperties = pathMatcher
            .getResources("classpath*:/META-INF/**/logsniffer-*.properties");
    final PropertiesFactoryBean p = new PropertiesFactoryBean();
    for (final Resource r : metainfProperties) {
        classPathProperties = (Resource[]) ArrayUtils.add(classPathProperties, r);
    }
    classPathProperties = (Resource[]) ArrayUtils.add(classPathProperties,
            new FileSystemResource(System.getProperty("logsniffer.home") + "/" + LOGSNIFFER_PROPERTIES_FILE));
    p.setLocations(classPathProperties);
    p.setProperties(System.getProperties());
    p.setLocalOverride(true);
    p.setIgnoreResourceNotFound(true);
    return p;
}

From source file:org.excalibur.service.deployment.server.ApplicationServer.java

/**
 * Starts the this server and its services. 
 **///w w w  . java 2  s .  c  om
public void start() throws Exception {
    if (this.started.compareAndSet(false, true)) {
        ServletContextHandler context = new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
        context.addEventListener(new ContextLoaderListener());
        context.setInitParameter("contextConfigLocation", "classpath*:META-INF/context.xml");
        context.setContextPath(contextPath);

        ServletHolder sh = new ServletHolder(new org.glassfish.jersey.servlet.ServletContainer());
        sh.setInitParameter("javax.ws.rs.Application", ApplicationConfig.class.getName());
        sh.setInitOrder(1);
        context.addServlet(sh, "/*");

        server.setHandler(context);
        server.start();

        ApplicationContext applicationContext = (ApplicationContext) context.getServletContext()
                .getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);

        Environment environment = applicationContext.getEnvironment();
        ApplicationConfig application = applicationContext.getBean(ApplicationConfig.class);

        for (Class<?> klass : application.getAvailableResources()) {
            registerThisInstanceServices(klass, environment, application);
        }

        this.serviceDiscovery.start();
        server.join();
    }
}

From source file:com.github.wnameless.spring.routing.RoutingPathResolver.java

/**
   * Creates a {@link RoutingPathResolver}.
   * //w w  w.j a  v  a2  s .co  m
   * @param appCtx
   *          the Spring {@link ApplicationContext}
   * @param basePackages
   *          packages to be searched
   */
  public RoutingPathResolver(ApplicationContext appCtx, String... basePackages) {
      env = appCtx.getEnvironment();
      Map<String, Object> beans = appCtx.getBeansWithAnnotation(Controller.class);
      beans.putAll(appCtx.getBeansWithAnnotation(RestController.class));
      retainBeansByPackageNames(beans, basePackages);

      for (Object bean : beans.values()) {
          List<Method> mappingMethods = getMethodsListWithAnnotation(bean.getClass(), RequestMapping.class);
          RequestMapping classRM = bean.getClass().getAnnotation(RequestMapping.class);
          for (Method method : mappingMethods) {
              RequestMapping methodRM = method.getAnnotation(RequestMapping.class);
              for (Entry<String, RequestMethod> rawPathAndMethod : computeRawPaths(classRM, methodRM)) {
                  String rawPath = rawPathAndMethod.getKey();
                  String path = computePath(rawPath);
                  String regexPath = computeRegexPath(path);
                  routingPaths.add(new RoutingPath(rawPathAndMethod.getValue(), rawPath, path,
                          Pattern.compile(regexPath), bean.getClass().getAnnotations(), method.getAnnotations()));
              }
          }
      }
  }

From source file:com.artivisi.belajar.restful.ui.controller.HomepageController.java

@RequestMapping("/homepage/appinfo")
@ResponseBody//from w ww.  j  ava  2  s  . com
public Map<String, String> appInfo(HttpServletRequest request) {

    ApplicationContext ctx = WebApplicationContextUtils
            .getWebApplicationContext(request.getSession().getServletContext());

    Map<String, String> hasil = new HashMap<String, String>();

    hasil.put("profileDefault",
            StringUtils.arrayToCommaDelimitedString(ctx.getEnvironment().getDefaultProfiles()));
    hasil.put("profileActive",
            StringUtils.arrayToCommaDelimitedString(ctx.getEnvironment().getActiveProfiles()));
    hasil.put("namaAplikasi", messageSource.getMessage("app.name", null, "undefined", null));
    hasil.put("versiAplikasi", messageSource.getMessage("app.version", null, "x.x.x", null));

    return hasil;
}

From source file:org.vaadin.spring.i18n.CompositeMessageSource.java

/**
 * Creates a new {@code CompositeMessageSource}.
 *
 * @param applicationContext the application context to use when looking up
 *        {@link org.vaadin.spring.i18n.MessageProvider}s, must not be {@code null}.
 *//*from   w  ww.j  a  va2  s . c  o m*/
public CompositeMessageSource(ApplicationContext applicationContext) {
    LOGGER.info("Looking up MessageProviders");
    messageProviders = applicationContext.getBeansOfType(MessageProvider.class).values();
    if (LOGGER.isDebugEnabled()) {
        for (MessageProvider messageProvider : messageProviders) {
            LOGGER.debug("Found MessageProvider [{}]", messageProvider);
        }
    }
    LOGGER.info("Found {} MessageProvider(s)", messageProviders.size());
    setMessageFormatCacheEnabled(applicationContext.getEnvironment()
            .getProperty(ENV_PROP_MESSAGE_FORMAT_CACHE_ENABLED, Boolean.class, true));
}

From source file:org.grails.plugins.AbstractGrailsPluginManager.java

/**
 * Base implementation that simply goes through the list of plugins and calls doWithRuntimeConfiguration on each
 * @param springConfig The RuntimeSpringConfiguration instance
 *///w ww .jav  a2 s.c o  m
public void doRuntimeConfiguration(RuntimeSpringConfiguration springConfig) {
    ApplicationContext context = springConfig.getUnrefreshedApplicationContext();
    AutowireCapableBeanFactory autowireCapableBeanFactory = context.getAutowireCapableBeanFactory();
    if (autowireCapableBeanFactory instanceof ConfigurableListableBeanFactory) {
        ConfigurableListableBeanFactory beanFactory = (ConfigurableListableBeanFactory) autowireCapableBeanFactory;
        ConversionService existingConversionService = beanFactory.getConversionService();
        ConverterRegistry converterRegistry;
        if (existingConversionService == null) {
            GenericConversionService conversionService = new GenericConversionService();
            converterRegistry = conversionService;
            beanFactory.setConversionService(conversionService);
        } else {
            converterRegistry = (ConverterRegistry) existingConversionService;
        }

        converterRegistry.addConverter(
                new Converter<GrailsApplication, org.codehaus.groovy.grails.commons.GrailsApplication>() {
                    @Override
                    public org.codehaus.groovy.grails.commons.GrailsApplication convert(
                            GrailsApplication source) {
                        return new LegacyGrailsApplication(source);
                    }
                });
        converterRegistry.addConverter(new Converter<NavigableMap.NullSafeNavigator, Object>() {
            @Override
            public Object convert(NavigableMap.NullSafeNavigator source) {
                return null;
            }
        });
    }
    checkInitialised();
    for (GrailsPlugin plugin : pluginList) {
        if (plugin.supportsCurrentScopeAndEnvironment()
                && plugin.isEnabled(context.getEnvironment().getActiveProfiles())) {
            plugin.doWithRuntimeConfiguration(springConfig);
        }
    }
}

From source file:org.grails.plugins.AbstractGrailsPluginManager.java

public void doDynamicMethods() {
    checkInitialised();//w  w w .  java  2s. c  o  m
    Class<?>[] allClasses = application.getAllClasses();
    if (allClasses != null) {
        for (Class<?> c : allClasses) {
            ExpandoMetaClass emc = new ExpandoMetaClass(c, true, true);
            emc.initialize();
        }
        ApplicationContext ctx = applicationContext;
        for (GrailsPlugin plugin : pluginList) {
            if (!plugin.isEnabled(ctx.getEnvironment().getActiveProfiles()))
                continue;
            plugin.doWithDynamicMethods(ctx);
        }
    }
}

From source file:org.jumpmind.metl.core.util.LogUtils.java

public static void initLogging(String configDir, ApplicationContext ctx) {

    /* Optionally remove existing handlers attached to j.u.l root logger */
    SLF4JBridgeHandler.removeHandlersForRootLogger();

    /*/*w w  w .  java2  s  .  c o m*/
     * Add SLF4JBridgeHandler to j.u.l's root logger, should be done once
     * during the initialization phase of your application
     */
    SLF4JBridgeHandler.install();

    consoleEnabled = Boolean
            .parseBoolean(ctx.getEnvironment().getProperty(EnvConstants.LOG_TO_CONSOLE_ENABLED, "true"));
    if (!consoleEnabled) {
        org.apache.log4j.Logger.getRootLogger().removeAppender("CONSOLE");
    }

    fileEnabled = Boolean
            .parseBoolean(ctx.getEnvironment().getProperty(EnvConstants.LOG_TO_FILE_ENABLED, "true"));
    if (fileEnabled) {
        logFilePath = ctx.getEnvironment().getProperty(EnvConstants.LOG_FILE, (String) null);
        if (isBlank(logFilePath)) {
            logDir = new File(configDir, "logs");
            logDir.mkdirs();
            logFilePath = logDir.getAbsolutePath() + "/metl.log";
        } else {
            logDir = new File(logFilePath).getParentFile();
        }
        try {
            RollingFileAppender logFileAppender = new RollingFileAppender();
            logFileAppender.setFile(logFilePath);
            logFileAppender.setMaxBackupIndex(10);
            logFileAppender.setMaxFileSize("40MB");
            logFileAppender.setAppend(true);
            logFileAppender.setLayout(new PatternLayout("%d %-5p [%c{1}] [%t] %m%n"));
            org.apache.log4j.Logger.getRootLogger().addAppender(logFileAppender);
            logFileAppender.activateOptions();
        } catch (Exception ex) {
            System.err.println("Failed to configure the following log file: " + logFilePath);
            ex.printStackTrace();
        }
    }
}

From source file:org.springframework.cloud.bootstrap.encrypt.EnvironmentDecryptApplicationInitializer.java

@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
    ConfigurableEnvironment environment = applicationContext.getEnvironment();
    MapPropertySource decrypted = new MapPropertySource(DECRYPTED_PROPERTY_SOURCE_NAME,
            decrypt(environment.getPropertySources()));
    if (!decrypted.getSource().isEmpty()) {
        // We have some decrypted properties
        insert(environment.getPropertySources(), decrypted);
        ApplicationContext parent = applicationContext.getParent();
        if (parent != null && (parent.getEnvironment() instanceof ConfigurableEnvironment)) {
            ConfigurableEnvironment mutable = (ConfigurableEnvironment) parent.getEnvironment();
            // The parent is actually the bootstrap context, and it is fully
            // initialized, so we can fire an EnvironmentChangeEvent there to rebind
            // @ConfigurationProperties, in case they were encrypted.
            insert(mutable.getPropertySources(), decrypted);
            parent.publishEvent(new EnvironmentChangeEvent(decrypted.getSource().keySet()));
        }//www.j  ava  2s .  co m
    }
}

From source file:org.springframework.context.support.AbstractApplicationContext.java

/**
 * Set the parent of this application context.
 * <p>The parent {@linkplain ApplicationContext#getEnvironment() environment} is
 * {@linkplain ConfigurableEnvironment#merge(ConfigurableEnvironment) merged} with
 * this (child) application context environment if the parent is non-{@code null} and
 * its environment is an instance of {@link ConfigurableEnvironment}.
 * @see ConfigurableEnvironment#merge(ConfigurableEnvironment)
 *///from   w  w  w  .j  av  a2s  .co  m
@Override
public void setParent(@Nullable ApplicationContext parent) {
    this.parent = parent;
    if (parent != null) {
        Environment parentEnvironment = parent.getEnvironment();
        if (parentEnvironment instanceof ConfigurableEnvironment) {
            getEnvironment().merge((ConfigurableEnvironment) parentEnvironment);
        }
    }
}