Example usage for org.springframework.core.env ConfigurableEnvironment getActiveProfiles

List of usage examples for org.springframework.core.env ConfigurableEnvironment getActiveProfiles

Introduction

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

Prototype

String[] getActiveProfiles();

Source Link

Document

Return the set of profiles explicitly made active for this environment.

Usage

From source file:alfio.config.SpringBootLauncher.java

/**
 * Entry point for spring boot/*w ww  . j  a v a 2s .c om*/
 * @param args original arguments
 */
public static void main(String[] args) {
    Thread.setDefaultUncaughtExceptionHandler(new DefaultExceptionHandler());
    String profiles = System.getProperty("spring.profiles.active", "");

    SpringApplication application = new SpringApplication(SpringBootInitializer.class,
            RepositoryConfiguration.class, DataSourceConfiguration.class, WebSecurityConfig.class,
            MvcConfiguration.class);
    List<String> additionalProfiles = new ArrayList<>();
    additionalProfiles.add(Initializer.PROFILE_SPRING_BOOT);
    if ("true".equals(System.getenv("ALFIO_LOG_STDOUT_ONLY"))) {
        // -> will load application-stdout.properties on top to override the logger configuration
        additionalProfiles.add("stdout");
    }
    if ("true".equals(System.getenv("ALFIO_DEMO_ENABLED"))) {
        additionalProfiles.add(Initializer.PROFILE_DEMO);
    }
    if ("true".equals(System.getenv("ALFIO_JDBC_SESSION_ENABLED"))) {
        additionalProfiles.add(Initializer.PROFILE_JDBC_SESSION);
    }
    application.setAdditionalProfiles(additionalProfiles.toArray(new String[additionalProfiles.size()]));
    ConfigurableApplicationContext applicationContext = application.run(args);
    ConfigurableEnvironment environment = applicationContext.getEnvironment();
    log.info("profiles: requested {}, active {}", profiles,
            String.join(", ", (CharSequence[]) environment.getActiveProfiles()));
    if ("true".equals(System.getProperty("startDBManager"))) {
        launchHsqlGUI();
    }
}

From source file:com.setronica.ucs.server.MessageServer.java

private static ClassPathXmlApplicationContext initApplication(String profile,
        DefaultListableBeanFactory parentBeanFactory) {
    ClassPathXmlApplicationContext applicationContext;

    if (parentBeanFactory != null) {
        //wrap BeanFactory inside ApplicationContext
        GenericApplicationContext parentContext = new GenericApplicationContext(parentBeanFactory);
        parentContext.refresh();/*w w  w  .  ja v  a  2 s.  c o  m*/
        applicationContext = new ClassPathXmlApplicationContext(parentContext);
    } else {
        applicationContext = new ClassPathXmlApplicationContext();
    }
    ConfigurableEnvironment environment = applicationContext.getEnvironment();
    environment.setDefaultProfiles(profile);
    applicationContext.setConfigLocation("spring-application.xml");

    // log active profile

    String[] profiles = environment.getActiveProfiles();
    if (profiles.length == 0) {
        profiles = environment.getDefaultProfiles();
    }
    for (String activeProfile : profiles) {
        if (environment.acceptsProfiles(activeProfile)) {
            logger.info("Profile " + activeProfile + " is active");
        }
    }

    applicationContext.refresh();
    return applicationContext;
}

From source file:com.indeed.imhotep.web.config.PropertiesInitializer.java

private static void activateSpringProfiles(ConfigurableEnvironment springEnv) {
    if (IQLEnv.isSpringProfileSet(springEnv)) {
        return; // we seem to already have some profile set. let it be
    }// w w w . j ava2 s .  c om

    // try to infer the appropriate Spring profile
    // this JVM system property should be set in OPs managed JVMs
    String indeedEnv = System.getProperty(indeedEnvironmentJVMProperty);
    if (Strings.isNullOrEmpty(indeedEnv)) {
        indeedEnv = "developer"; // assume this is not an OPs managed JVM and thus a developer station
    }
    final List<String> profiles = Lists.newArrayList(springEnv.getActiveProfiles());
    profiles.add(indeedEnv);
    springEnv.setActiveProfiles(profiles.toArray(new String[profiles.size()]));
}

From source file:jp.xet.uncommons.web.env.EnvironmentProfileApplicationContextInitializer.java

@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
    ConfigurableEnvironment environment = applicationContext.getEnvironment();

    String[] activeProfiles = environment.getActiveProfiles();
    if (ObjectUtils.isEmpty(activeProfiles)) {
        String propEnvironment = environment.getProperty("environment");
        if (Strings.isNullOrEmpty(propEnvironment)) {
            environment.setActiveProfiles("development");
            logger.warn("Spring active profiles are not specified.  Set default value [{}]", DEFAULT_PROFILE);
        } else {/*from   w  w w . j  a v a  2  s.c  o  m*/
            environment.setActiveProfiles(propEnvironment);
            logger.info("Set Spring active profiles to [{}]", propEnvironment);
        }
    } else {
        logger.info("Spring active profiles [{}]", activeProfiles);
    }
}

From source file:guru.qas.martini.jmeter.config.MartiniSpringConfiguration.java

@Override
public void testStarted() {
    synchronized (contextRef) {
        ConfigurableApplicationContext context = initializeContext();
        ConfigurableApplicationContext previous = contextRef.getAndSet(context);
        if (null != previous) {
            previous.close();//from   w w  w.  j  av  a  2s. co  m
        }

        String hostname = JMeterUtils.getLocalHostName();
        String ip = JMeterUtils.getLocalHostIP();
        String name = super.getName();
        String id = context.getId();
        long startupDate = context.getStartupDate();
        String username = System.getProperty("user.name");

        ConfigurableEnvironment environment = context.getEnvironment();
        String[] activeProfiles = environment.getActiveProfiles();
        ArrayList<String> profiles = Lists.newArrayList(activeProfiles);

        Map<String, String> environmentVariables = this.getEnvironmentProperties().getArgumentsAsMap();

        SuiteIdentifier identifier = DefaultSuiteIdentifier.builder().setId(id).setStartupTimestamp(startupDate)
                .setName(name).setHostname(hostname).setHostAddress(ip).setUsername(username)
                .setProfiles(profiles).setEnvironmentVariables(environmentVariables).build();

        ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
        beanFactory.registerSingleton(BEAN_SUITE_IDENTIFIER, identifier);

        EventManager eventManager = context.getBean(EventManager.class);
        eventManager.publishBeforeSuite(this, identifier);
    }
}

From source file:org.carewebframework.ui.spring.FrameworkAppContext.java

/**
 * Constructor for creating an application context. Disallows bean overrides by default.
 * /*from ww  w .  j  av  a  2s. c o  m*/
 * @param desktop The desktop associated with this application context. Will be null for the
 *            root application context.
 * @param testConfig If true, use test profiles.
 * @param locations Optional list of configuration file locations. If not specified, defaults to
 *            the default configuration locations ({@link #getDefaultConfigLocations}).
 */
public FrameworkAppContext(Desktop desktop, boolean testConfig, String... locations) {
    super();
    setAllowBeanDefinitionOverriding(false);
    this.desktop = desktop;
    ConfigurableEnvironment env = getEnvironment();
    Set<String> aps = new LinkedHashSet<String>();
    Collections.addAll(aps, env.getActiveProfiles());

    if (desktop != null) {
        desktop.setAttribute(APP_CONTEXT_ATTRIB, this);
        final Session session = desktop.getSession();
        final ServletContext sc = session.getWebApp().getServletContext();
        final WebApplicationContext rootContext = WebApplicationContextUtils
                .getRequiredWebApplicationContext(sc);
        setDisplayName("Child XmlWebApplicationContext " + desktop);
        setParent(rootContext);
        setServletContext(sc);
        this.ctxListener = new ContextClosedListener();
        getParent().getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class)
                .addApplicationListener(this.ctxListener);
        // Set up profiles (remove root profiles merged from parent)
        aps.removeAll(Arrays.asList(Constants.PROFILES_ROOT));
        Collections.addAll(aps, testConfig ? Constants.PROFILES_DESKTOP_TEST : Constants.PROFILES_DESKTOP_PROD);
    } else {
        AppContextFinder.rootContext = this;
        Collections.addAll(aps, testConfig ? Constants.PROFILES_ROOT_TEST : Constants.PROFILES_ROOT_PROD);
        env.getPropertySources().addLast(new LabelPropertySource(this));
        env.getPropertySources().addLast(new DomainPropertySource(this));
    }

    env.setActiveProfiles(aps.toArray(new String[aps.size()]));
    setConfigLocations(locations == null || locations.length == 0 ? null : locations);
}

From source file:it.scoppelletti.programmerpower.web.spring.config.WebApplicationContextInitializer.java

/**
 * Inizializzazione.//from   ww w . j a va  2  s  . c om
 * 
 * @param applCtx Contesto dell&rsquo;applicazione.
 */
public void initialize(AbstractRefreshableWebApplicationContext applCtx) {
    ConfigurableEnvironment env;
    PropertySource<?> propSource;
    MutablePropertySources propSources;

    env = applCtx.getEnvironment();

    // Acquisisco gli eventuali profili configurati prima di aggiungere
    // quelli di Programmer Power
    env.getActiveProfiles();

    env.addActiveProfile(WebApplicationContextInitializer.PROFILE);
    env.addActiveProfile(DataUtils.PROFILE);

    propSources = env.getPropertySources();

    propSource = BeanConfigUtils.loadPropertySource();
    if (propSource != null) {
        propSources.addFirst(propSource);
    }

    propSources.addLast(new WebPropertySource(WebPropertySource.class.getName(), applCtx));
}

From source file:it.scoppelletti.programmerpower.console.spring.ConsoleApplicationRunner.java

/**
 * Inizializza il contesto dell&rsquo;applicazione.
 * /*from  w w  w .ja v a  2  s .c  om*/
 * @param  ui Interfaccia utente.
 * @return    Oggetto.
 */
private GenericApplicationContext initApplicationContext(UserInterfaceProvider ui) {
    SingletonBeanRegistry beanRegistry;
    GenericApplicationContext ctx = null;
    GenericApplicationContext applCtx;
    XmlBeanDefinitionReader reader;
    ConfigurableEnvironment env;
    PropertySource<?> propSource;
    MutablePropertySources propSources;

    try {
        ctx = new GenericApplicationContext();
        reader = new XmlBeanDefinitionReader(ctx);
        reader.loadBeanDefinitions(ConsoleApplicationRunner.CONSOLE_CONTEXT);
        reader.loadBeanDefinitions(initApplicationContextResourceName());

        beanRegistry = ctx.getBeanFactory();
        beanRegistry.registerSingleton(ConsoleApplicationRunner.BEAN_NAME, this);
        beanRegistry.registerSingleton(UserInterfaceProvider.BEAN_NAME, ui);

        env = ctx.getEnvironment();

        // Acquisisco gli eventuali profili configurati prima di aggiungere
        // quello di Programmer Power
        env.getActiveProfiles();

        env.addActiveProfile(ConsoleApplicationRunner.PROFILE);

        propSources = env.getPropertySources();

        propSources.addFirst(new ConsolePropertySource(ConsolePropertySource.class.getName(), this));

        propSource = BeanConfigUtils.loadPropertySource();
        if (propSource != null) {
            propSources.addFirst(propSource);
        }

        ctx.refresh();
        applCtx = ctx;
        ctx = null;
    } finally {
        if (ctx != null) {
            ctx.close();
            ctx = null;
        }
    }

    return applCtx;
}

From source file:org.springframework.boot.SpringApplication.java

private ConfigurableEnvironment convertToStandardEnvironment(ConfigurableEnvironment environment) {
    StandardEnvironment result = new StandardEnvironment();
    removeAllPropertySources(result.getPropertySources());
    result.setActiveProfiles(environment.getActiveProfiles());
    for (PropertySource<?> propertySource : environment.getPropertySources()) {
        if (!SERVLET_ENVIRONMENT_SOURCE_NAMES.contains(propertySource.getName())) {
            result.getPropertySources().addLast(propertySource);
        }/*from  w  w w  . j  ava2s  .  co  m*/
    }
    return result;
}

From source file:org.springframework.boot.SpringApplication.java

/**
 * Configure which profiles are active (or active by default) for this application
 * environment. Additional profiles may be activated during configuration file
 * processing via the {@code spring.profiles.active} property.
 * @param environment this application's environment
 * @param args arguments passed to the {@code run} method
 * @see #configureEnvironment(ConfigurableEnvironment, String[])
 * @see org.springframework.boot.context.config.ConfigFileEnvironmentPostProcessor
 *//*from w w w . ja v  a 2  s  .  c o m*/
protected void configureProfiles(ConfigurableEnvironment environment, String[] args) {
    environment.getActiveProfiles(); // ensure they are initialized
    // But these ones should go first (last wins in a property key clash)
    Set<String> profiles = new LinkedHashSet<String>(this.additionalProfiles);
    profiles.addAll(Arrays.asList(environment.getActiveProfiles()));
    environment.setActiveProfiles(profiles.toArray(new String[profiles.size()]));
}