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

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

Introduction

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

Prototype

void setActiveProfiles(String... profiles);

Source Link

Document

Specify the set of profiles active for this Environment .

Usage

From source file:org.cloudfoundry.identity.uaa.config.YamlServletProfileInitializer.java

private void applySpringProfiles(ConfigurableEnvironment environment, ServletContext servletContext) {
    if (environment.containsProperty("spring_profiles")) {
        String profiles = (String) environment.getProperty("spring_profiles");
        servletContext.log("Setting active profiles: " + profiles);
        environment.setActiveProfiles(StringUtils.commaDelimitedListToStringArray(profiles));
    }//from w ww  .  j  av  a 2s . c  o m
}

From source file:com.rr.generic.ui.security.ContextProfileInitializer.java

public void initialize(ConfigurableWebApplicationContext ctx) {
    ConfigurableEnvironment environment = ctx.getEnvironment();

    String hostname = null;//from www.  j  ava2s.c  o  m
    String profiles = "local";

    try {
        hostname = InetAddress.getLocalHost().getHostAddress();
    } catch (UnknownHostException ex) {
        Logger.getLogger(ContextProfileInitializer.class.getName()).log(Level.SEVERE, null, ex);
    }

    if ("172.24.16.43".equals(hostname)) {
        profiles = "staging";
    } else if ("172.24.32.41".equals(hostname)) {
        profiles = "prod";
    }

    environment.setActiveProfiles(profiles);
}

From source file:com.ut.healthelink.security.ContextProfileInitializer.java

public void initialize(ConfigurableWebApplicationContext ctx) {
    ConfigurableEnvironment environment = ctx.getEnvironment();

    String hostname = null;//w  ww .j  a v  a  2  s. co m
    String profiles = "local";

    try {
        hostname = InetAddress.getLocalHost().getHostAddress();
    } catch (UnknownHostException ex) {
        Logger.getLogger(ContextProfileInitializer.class.getName()).log(Level.SEVERE, null, ex);
    }

    if ("10.202.52.54".equals(hostname)) {
        profiles = "healthelink-test";
    } else if ("10.202.52.152".equals(hostname)) {
        profiles = "healthelink-prod";
    }

    environment.setActiveProfiles(profiles);
}

From source file:com.quartzdesk.executor.web.spring.SpringProfilesActivator.java

@Override
public void initialize(XmlWebApplicationContext applicationContext) {
    ConfigurableEnvironment env = applicationContext.getEnvironment();

    WorkDir workDir;//  w w  w.  j av a2  s  . co  m
    try {
        workDir = new WorkDir(applicationContext.getServletContext());
    } catch (IOException e) {
        throw new ApplicationContextException("Error obtaining QuartzDesk Executor work directory.", e);
    }

    String databaseProfile = getDatabaseProfile(workDir);

    String[] activeProfiles = new String[] { databaseProfile };

    log.info("Activating Spring profiles: {}", Arrays.toString(activeProfiles));

    env.setActiveProfiles(activeProfiles);
}

From source file:de.tudarmstadt.ukp.clarin.webanno.webapp.security.preauth.WebAnnoApplicationContextInitializer.java

@Override
public void initialize(ConfigurableApplicationContext aApplicationContext) {
    WebAnnoLoggingFilter.setLoggingUsername("SYSTEM");

    log.info("  _      __    __   ___                ");
    log.info(" | | /| / /__ / /  / _ | ___  ___  ___ ");
    log.info(" | |/ |/ / -_) _ \\/ __ |/ _ \\/ _ \\/ _ \\");
    log.info(" |__/|__/\\__/_.__/_/ |_/_//_/_//_/\\___/");
    log.info(SettingsUtil.getVersionString());

    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 {//ww w .ja va 2s  .c  om
            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(PROP_AUTH_MODE))) {
        aEnvironment.setActiveProfiles(PROFILE_PREAUTH);
        log.info("Authentication: pre-auth");
    } else {
        aEnvironment.setActiveProfiles(PROFILE_DATABASE);
        log.info("Authentication: database");
    }
}

From source file:net.community.chest.gitcloud.facade.AbstractContextInitializer.java

@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
    ConfigurableEnvironment environment = applicationContext.getEnvironment();
    MutablePropertySources propSources = environment.getPropertySources();
    ExtendedPlaceholderResolver sourcesResolver = ExtendedPlaceholderResolverUtils
            .toPlaceholderResolver(propSources);
    File appBase = resolveApplicationBase(propSources, sourcesResolver);
    File configFile = getApplicationConfigFile(appBase, sourcesResolver);
    Collection<String> activeProfiles = resolveActiveProfiles(sourcesResolver);
    if (ExtendedCollectionUtils.size(activeProfiles) > 0) {
        environment.setActiveProfiles(activeProfiles.toArray(new String[activeProfiles.size()]));
    }//from w  ww.jav a  2 s  . c  o  m

    try {
        ensureFoldersExistence(appBase, configFile, sourcesResolver);
    } catch (IOException e) {
        logger.error("ensureFoldersExistence(" + ExtendedFileUtils.toString(appBase) + ")" + " "
                + e.getClass().getSimpleName() + ": " + e.getMessage());
    }

    if (logger.isDebugEnabled()) {
        showArtifactsVersions();
    }
}

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

/**
 * Constructor for creating an application context. Disallows bean overrides by default.
 * // ww  w .j  ava 2  s .co  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: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
 */// ww w  .j  a v  a 2s.  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()]));
}

From source file:org.springframework.integration.samples.travel.Main.java

/**
 * @param args Not used./* w w w.  j a  v  a  2 s . c om*/
 */
public static void main(String... args) throws Exception {

    final GenericXmlApplicationContext context = new GenericXmlApplicationContext();

    final ConfigurableEnvironment env = context.getEnvironment();
    boolean mapQuestApiKeyDefined = env.containsProperty("mapquest.apikey");

    if (mapQuestApiKeyDefined) {
        env.setActiveProfiles("mapquest");
    }

    context.load("classpath:META-INF/spring/*.xml");
    context.refresh();

    final TravelGateway travelGateway = context.getBean("travelGateway", TravelGateway.class);

    final Scanner scanner = new Scanner(System.in);

    System.out.println("\n========================================================="
            + "\n                                                         "
            + "\n    Welcome to the Spring Integration Travel App!        "
            + "\n                                                         "
            + "\n    For more information please visit:                   "
            + "\n    http://www.springintegration.org/                    "
            + "\n                                                         "
            + "\n=========================================================");

    System.out.println(
            "Please select the city, for which you would like to get traffic and weather information:");

    for (City city : City.values()) {
        System.out.println(String.format("\t%s. %s", city.getId(), city.getName()));
    }
    System.out.println("\tq. Quit the application");
    System.out.print("Enter your choice: ");

    while (true) {
        final String input = scanner.nextLine();

        if ("q".equals(input.trim())) {
            System.out.println("Exiting application...bye.");
            break;
        } else {

            final Integer cityId = Integer.valueOf(input);
            final City city = City.getCityForId(cityId);

            final String weatherReply = travelGateway.getWeatherByCity(city);

            System.out.println("\n=========================================================" + "\n    Weather:"
                    + "\n=========================================================");
            System.out.println(weatherReply);

            if (mapQuestApiKeyDefined) {
                final String trafficReply = travelGateway.getTrafficByCity(city);

                System.out.println("\n========================================================="
                        + "\n    Traffic:" + "\n=========================================================");
                System.out.println(trafficReply);
            } else {
                LOGGER.warn("Skipping Traffic Information call. Did you setup your MapQuest API Key? "
                        + "e.g. by calling:\n\n    $ mvn exec:java -Dmapquest.apikey=\"your_mapquest_api_key_url_decoded\"");
            }

            System.out.println("\n=========================================================" + "\n    Done."
                    + "\n=========================================================");
            System.out.print("Enter your choice: ");
        }
    }

    scanner.close();
    context.close();
}