org.springframework.web.context.ConfigurableWebApplicationContext Java Examples

The following examples show how to use org.springframework.web.context.ConfigurableWebApplicationContext. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FrameworkServlet.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Instantiate the WebApplicationContext for this servlet, either a default
 * {@link org.springframework.web.context.support.XmlWebApplicationContext}
 * or a {@link #setContextClass custom context class}, if set.
 * <p>This implementation expects custom contexts to implement the
 * {@link org.springframework.web.context.ConfigurableWebApplicationContext}
 * interface. Can be overridden in subclasses.
 * <p>Do not forget to register this servlet instance as application listener on the
 * created context (for triggering its {@link #onRefresh callback}, and to call
 * {@link org.springframework.context.ConfigurableApplicationContext#refresh()}
 * before returning the context instance.
 * @param parent the parent ApplicationContext to use, or {@code null} if none
 * @return the WebApplicationContext for this servlet
 * @see org.springframework.web.context.support.XmlWebApplicationContext
 */
protected WebApplicationContext createWebApplicationContext(ApplicationContext parent) {
	Class<?> contextClass = getContextClass();
	if (this.logger.isDebugEnabled()) {
		this.logger.debug("Servlet with name '" + getServletName() +
				"' will try to create custom WebApplicationContext context of class '" +
				contextClass.getName() + "'" + ", using parent context [" + parent + "]");
	}
	if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {
		throw new ApplicationContextException(
				"Fatal initialization error in servlet with name '" + getServletName() +
				"': custom WebApplicationContext class [" + contextClass.getName() +
				"] is not of type ConfigurableWebApplicationContext");
	}
	ConfigurableWebApplicationContext wac =
			(ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);

	wac.setEnvironment(getEnvironment());
	wac.setParent(parent);
	wac.setConfigLocation(getContextConfigLocation());

	configureAndRefreshWebApplicationContext(wac);

	return wac;
}
 
Example #2
Source File: SpringBootLambdaContainerHandler.java    From aws-serverless-java-container with Apache License 2.0 6 votes vote down vote up
@Override
public void initialize()
        throws ContainerInitializationException {
    Timer.start("SPRINGBOOT_COLD_START");

    SpringApplication app = new SpringApplication(
            springBootInitializer,
            ServerlessServletEmbeddedServerFactory.class,
            SpringBootServletConfigurationSupport.class
    );
    if (springProfiles != null && springProfiles.length > 0) {
        ConfigurableEnvironment springEnv = new StandardEnvironment();
        springEnv.setActiveProfiles(springProfiles);
        app.setEnvironment(springEnv);
    }
    ConfigurableApplicationContext applicationContext = app.run();

    ((ConfigurableWebApplicationContext)applicationContext).setServletContext(getServletContext());
    AwsServletRegistration reg = (AwsServletRegistration)getServletContext().getServletRegistration(DISPATCHER_SERVLET_REGISTRATION_NAME);
    if (reg != null) {
        reg.setLoadOnStartup(1);
    }
    super.initialize();
    initialized = true;
    Timer.stop("SPRINGBOOT_COLD_START");
}
 
Example #3
Source File: FrameworkServlet.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Instantiate the WebApplicationContext for this servlet, either a default
 * {@link org.springframework.web.context.support.XmlWebApplicationContext}
 * or a {@link #setContextClass custom context class}, if set.
 * <p>This implementation expects custom contexts to implement the
 * {@link org.springframework.web.context.ConfigurableWebApplicationContext}
 * interface. Can be overridden in subclasses.
 * <p>Do not forget to register this servlet instance as application listener on the
 * created context (for triggering its {@link #onRefresh callback}, and to call
 * {@link org.springframework.context.ConfigurableApplicationContext#refresh()}
 * before returning the context instance.
 * @param parent the parent ApplicationContext to use, or {@code null} if none
 * @return the WebApplicationContext for this servlet
 * @see org.springframework.web.context.support.XmlWebApplicationContext
 */
protected WebApplicationContext createWebApplicationContext(ApplicationContext parent) {
	Class<?> contextClass = getContextClass();
	if (this.logger.isDebugEnabled()) {
		this.logger.debug("Servlet with name '" + getServletName() +
				"' will try to create custom WebApplicationContext context of class '" +
				contextClass.getName() + "'" + ", using parent context [" + parent + "]");
	}
	if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {
		throw new ApplicationContextException(
				"Fatal initialization error in servlet with name '" + getServletName() +
				"': custom WebApplicationContext class [" + contextClass.getName() +
				"] is not of type ConfigurableWebApplicationContext");
	}
	ConfigurableWebApplicationContext wac =
			(ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);

	wac.setEnvironment(getEnvironment());
	wac.setParent(parent);
	wac.setConfigLocation(getContextConfigLocation());

	configureAndRefreshWebApplicationContext(wac);

	return wac;
}
 
Example #4
Source File: SakaiContextLoader.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
/**
 * Allows loading/override of custom bean definitions from sakai.home
 *
 * <p>The pattern is the 'servlet_name-context.xml'</p>
 *
 * @param sc current servlet context
 * @param wac the new WebApplicationContext
 */
@Override
protected void customizeContext(ServletContext sc, ConfigurableWebApplicationContext wac) {
	super.customizeContext(sc, wac);
	if (wac != null) {
		final String servletName = sc.getServletContextName();
		String location = getHomeBeanDefinitionIfExists(servletName);
		if (StringUtils.isNotBlank(location)) {
			String[] configLocations = wac.getConfigLocations();
			String[] newLocations = Arrays.copyOf(configLocations, configLocations.length + 1);
			newLocations[configLocations.length] = "file:" + location;
			wac.setConfigLocations(newLocations);
			log.info("Servlet {} added an additional bean config location [{}]", servletName, location);
		}
	}
}
 
Example #5
Source File: FrameworkServlet.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Instantiate the WebApplicationContext for this servlet, either a default
 * {@link org.springframework.web.context.support.XmlWebApplicationContext}
 * or a {@link #setContextClass custom context class}, if set.
 * <p>This implementation expects custom contexts to implement the
 * {@link org.springframework.web.context.ConfigurableWebApplicationContext}
 * interface. Can be overridden in subclasses.
 * <p>Do not forget to register this servlet instance as application listener on the
 * created context (for triggering its {@link #onRefresh callback}, and to call
 * {@link org.springframework.context.ConfigurableApplicationContext#refresh()}
 * before returning the context instance.
 * @param parent the parent ApplicationContext to use, or {@code null} if none
 * @return the WebApplicationContext for this servlet
 * @see org.springframework.web.context.support.XmlWebApplicationContext
 */
protected WebApplicationContext createWebApplicationContext(@Nullable ApplicationContext parent) {
	Class<?> contextClass = getContextClass();
	if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {
		throw new ApplicationContextException(
				"Fatal initialization error in servlet with name '" + getServletName() +
				"': custom WebApplicationContext class [" + contextClass.getName() +
				"] is not of type ConfigurableWebApplicationContext");
	}
	ConfigurableWebApplicationContext wac =
			(ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);

	wac.setEnvironment(getEnvironment());
	wac.setParent(parent);
	String configLocation = getContextConfigLocation();
	if (configLocation != null) {
		wac.setConfigLocation(configLocation);
	}
	configureAndRefreshWebApplicationContext(wac);

	return wac;
}
 
Example #6
Source File: MetricDispatcherServlet.java    From realtime-analytics with GNU General Public License v2.0 6 votes vote down vote up
protected WebApplicationContext createWebApplicationContext(ApplicationContext parent) {
    Class<?> contextClass = getContextClass();
    if (this.logger.isDebugEnabled()) {
        this.logger.debug("Servlet with name '" + getServletName() +
                "' will try to create custom WebApplicationContext context of class '" +
                contextClass.getName() + "'" + ", using parent context [" + parent + "]");
    }
    if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {
        throw new ApplicationContextException(
                "Fatal initialization error in servlet with name '" + getServletName() +
                "': custom WebApplicationContext class [" + contextClass.getName() +
                "] is not of type ConfigurableWebApplicationContext");
    }
    ConfigurableWebApplicationContext wac =
            (ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);
    
    wac.setParent(parent);
    if (wac.getParent() == null) {
        ApplicationContext rootContext = (ApplicationContext) getServletContext().getAttribute("JetStreamRoot");
        wac.setParent(rootContext);
    }
    wac.setConfigLocation(getContextConfigLocation());
    configureAndRefreshWebApplicationContext(wac);
    return wac;
}
 
Example #7
Source File: RegistrationApplicationListenerTest.java    From spring-boot-admin with Apache License 2.0 6 votes vote down vote up
@Test
public void should_cancel_register_task_on_context_close() {
	ApplicationRegistrator registrator = mock(ApplicationRegistrator.class);
	ThreadPoolTaskScheduler scheduler = mock(ThreadPoolTaskScheduler.class);
	RegistrationApplicationListener listener = new RegistrationApplicationListener(registrator, scheduler);

	ScheduledFuture<?> task = mock(ScheduledFuture.class);
	when(scheduler.scheduleAtFixedRate(isA(Runnable.class), eq(Duration.ofSeconds(10)))).then((invocation) -> task);

	listener.onApplicationReady(new ApplicationReadyEvent(mock(SpringApplication.class), null,
			mock(ConfigurableWebApplicationContext.class)));
	verify(scheduler).scheduleAtFixedRate(isA(Runnable.class), eq(Duration.ofSeconds(10)));

	listener.onClosedContext(new ContextClosedEvent(mock(WebApplicationContext.class)));
	verify(task).cancel(true);
}
 
Example #8
Source File: SakaiContextLoader.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
/**
 * Allows loading/override of custom bean definitions from sakai.home
 *
 * <p>The pattern is the 'servlet_name-context.xml'</p>
 *
 * @param sc current servlet context
 * @param wac the new WebApplicationContext
 */
@Override
protected void customizeContext(ServletContext sc, ConfigurableWebApplicationContext wac) {
	super.customizeContext(sc, wac);
	if (wac != null) {
		final String servletName = sc.getServletContextName();
		String location = getHomeBeanDefinitionIfExists(servletName);
		if (StringUtils.isNotBlank(location)) {
			String[] configLocations = wac.getConfigLocations();
			String[] newLocations = Arrays.copyOf(configLocations, configLocations.length + 1);
			newLocations[configLocations.length] = "file:" + location;
			wac.setConfigLocations(newLocations);
			log.info("Servlet {} added an additional bean config location [{}]", servletName, location);
		}
	}
}
 
Example #9
Source File: AbstractJettyComponent.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected WebApplicationContext createWebApplicationContext(ServletContext sc, ApplicationContext parent)
{
	GenericWebApplicationContext wac = (GenericWebApplicationContext) BeanUtils.instantiateClass(GenericWebApplicationContext.class);

	// Assign the best possible id value.
	wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX + contextPath);

	wac.setParent(parent);
	wac.setServletContext(sc);
	wac.refresh();

	return wac;
}
 
Example #10
Source File: SpringLambdaContainerHandler.java    From aws-serverless-java-container with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new container handler with the given reader and writer objects
 *
 * @param requestTypeClass The class for the incoming Lambda event
 * @param requestReader An implementation of `RequestReader`
 * @param responseWriter An implementation of `ResponseWriter`
 * @param securityContextWriter An implementation of `SecurityContextWriter`
 * @param exceptionHandler An implementation of `ExceptionHandler`
 */
public SpringLambdaContainerHandler(Class<RequestType> requestTypeClass,
                                    Class<ResponseType> responseTypeClass,
                                    RequestReader<RequestType, HttpServletRequest> requestReader,
                                    ResponseWriter<AwsHttpServletResponse, ResponseType> responseWriter,
                                    SecurityContextWriter<RequestType> securityContextWriter,
                                    ExceptionHandler<ResponseType> exceptionHandler,
                                    ConfigurableWebApplicationContext applicationContext,
                                    InitializationWrapper init) {
    super(requestTypeClass, responseTypeClass, requestReader, responseWriter, securityContextWriter, exceptionHandler);
    Timer.start("SPRING_CONTAINER_HANDLER_CONSTRUCTOR");
    appContext = applicationContext;
    setInitializationWrapper(init);
    Timer.stop("SPRING_CONTAINER_HANDLER_CONSTRUCTOR");
}
 
Example #11
Source File: ChassisEurekaTestConfiguration.java    From chassis with Apache License 2.0 5 votes vote down vote up
@Order(0)
@Bean(initMethod="start", destroyMethod="stop")
public Server httpServer(
        @Value("${http.hostname}") String hostname,
        @Value("${http.port}") int port,
        ConfigurableWebApplicationContext webApplicationContext) {

    // set up servlets
    ServletHandler servlets = new ServletHandler();
    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.NO_SESSIONS | ServletContextHandler.NO_SECURITY);
    context.setErrorHandler(null);
    context.setWelcomeFiles(new String[] { "/" });

    // set up spring with the servlet context
    setServletContext(context.getServletContext());

    // configure the spring mvc dispatcher
    DispatcherServlet dispatcher = new DispatcherServlet(webApplicationContext);

    // map application servlets
    context.addServlet(new ServletHolder(dispatcher), "/");

    servlets.setHandler(context);

    // create the server
    InetSocketAddress address = StringUtils.isBlank(hostname) ? new InetSocketAddress(port) : new InetSocketAddress(hostname, port);
    Server server = new Server();
    ServerConnector connector = new ServerConnector(server);
    connector.setHost(address.getHostName());
    connector.setPort(address.getPort());
    server.setConnectors(new Connector[]{ connector });
    server.setHandler(servlets);

    return server;
}
 
Example #12
Source File: HttpTransportConfiguration.java    From chassis with Apache License 2.0 5 votes vote down vote up
private Collection<ObjectMapper> getObjectMappers(ConfigurableWebApplicationContext webApplicationContext) {
    Map<String, JacksonMessageSerDe> serdes = webApplicationContext.getBeansOfType(JacksonMessageSerDe.class);
    if(serdes.isEmpty()){
        return Collections.emptyList();
    }
    return Collections2.transform(serdes.values(), new Function<JacksonMessageSerDe, ObjectMapper>() {
        @Nullable
        @Override
        public ObjectMapper apply(@Nullable JacksonMessageSerDe serDe) {
            return serDe.getObjectMapper();
        }
    });
}
 
Example #13
Source File: ProfileInitializer.java    From AppStash with Apache License 2.0 5 votes vote down vote up
@Override
public void initialize(ConfigurableWebApplicationContext configurableWebApplicationContext) {
    ConfigurableEnvironment environment = configurableWebApplicationContext.getEnvironment();
    if (environment.getSystemEnvironment().containsKey("MONGODB_PORT_27017_TCP_ADDR") &&
            environment.getSystemEnvironment().containsKey("MONGODB_PORT_27017_TCP_PORT")) {
        environment.setActiveProfiles("docker");
    }
    if (!hasActiveProfile(environment)) {
        environment.setActiveProfiles("production");
    }
    LOGGER.info("Active profiles are {}", StringUtils.join(environment.getActiveProfiles(), ","));
}
 
Example #14
Source File: FrameworkServlet.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac) {
	if (ObjectUtils.identityToString(wac).equals(wac.getId())) {
		// The application context id is still set to its original default value
		// -> assign a more useful id based on available information
		if (this.contextId != null) {
			wac.setId(this.contextId);
		}
		else {
			// Generate default id...
			wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +
					ObjectUtils.getDisplayString(getServletContext().getContextPath()) + "/" + getServletName());
		}
	}

	wac.setServletContext(getServletContext());
	wac.setServletConfig(getServletConfig());
	wac.setNamespace(getNamespace());
	wac.addApplicationListener(new SourceFilteringListener(wac, new ContextRefreshListener()));

	// The wac environment's #initPropertySources will be called in any case when the context
	// is refreshed; do it eagerly here to ensure servlet property sources are in place for
	// use in any post-processing or initialization that occurs below prior to #refresh
	ConfigurableEnvironment env = wac.getEnvironment();
	if (env instanceof ConfigurableWebEnvironment) {
		((ConfigurableWebEnvironment) env).initPropertySources(getServletContext(), getServletConfig());
	}

	postProcessWebApplicationContext(wac);
	applyInitializers(wac);
	wac.refresh();
}
 
Example #15
Source File: SingleAppDispatcherServlet.java    From cuba with Apache License 2.0 5 votes vote down vote up
@Override
@Nonnull
protected WebApplicationContext createWebApplicationContext(@Nullable ApplicationContext parent) {
    if (this.logger.isDebugEnabled()) {
        this.logger.debug(
                String.format("Servlet with name '%s' will try to create custom WebApplicationContext context of class '%s', using parent context [%s]",
                        getServletName(), CubaXmlWebApplicationContext.class.getName(), parent));
    }
    ConfigurableWebApplicationContext wac = new CubaXmlWebApplicationContext() {
        @Override
        protected ResourcePatternResolver getResourcePatternResolver() {
            return new SingleAppResourcePatternResolver(this, libFolder);
        }
    };

    String contextConfigLocation = getContextConfigLocation();
    if (contextConfigLocation == null) {
        throw new RuntimeException("Unable to determine context config location");
    }

    wac.setEnvironment(getEnvironment());
    wac.setParent(parent);
    wac.setConfigLocation(contextConfigLocation);

    configureAndRefreshWebApplicationContext(wac);

    return wac;
}
 
Example #16
Source File: MessageTagTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("deprecation")
public void nullMessageSource() throws JspException {
	PageContext pc = createPageContext();
	ConfigurableWebApplicationContext ctx = (ConfigurableWebApplicationContext)
			RequestContextUtils.getWebApplicationContext(pc.getRequest(), pc.getServletContext());
	ctx.close();

	MessageTag tag = new MessageTag();
	tag.setPageContext(pc);
	tag.setCode("test");
	tag.setVar("testvar2");
	tag.doStartTag();
	assertEquals("Correct doEndTag return value", Tag.EVAL_PAGE, tag.doEndTag());
}
 
Example #17
Source File: ProfileInitializer.java    From the-app with Apache License 2.0 5 votes vote down vote up
@Override
public void initialize(ConfigurableWebApplicationContext configurableWebApplicationContext) {
    ConfigurableEnvironment environment = configurableWebApplicationContext.getEnvironment();
    if (environment.getSystemEnvironment().containsKey("MONGODB_PORT_27017_TCP_ADDR") &&
            environment.getSystemEnvironment().containsKey("MONGODB_PORT_27017_TCP_PORT")) {
        environment.setActiveProfiles("docker");
    }
    if (!hasActiveProfile(environment)) {
        environment.setActiveProfiles("production");
    }
    LOGGER.info("Active profiles are {}", StringUtils.join(environment.getActiveProfiles(), ","));
}
 
Example #18
Source File: MyContextLoaderListener.java    From resteasy-examples with Apache License 2.0 5 votes vote down vote up
@Override
protected void customizeContext(ServletContext servletContext, ConfigurableWebApplicationContext configurableWebApplicationContext) {
    super.customizeContext(servletContext, configurableWebApplicationContext);

    ResteasyDeployment deployment = (ResteasyDeployment) servletContext.getAttribute(ResteasyDeployment.class.getName());
    if (deployment == null) {
        throw new RuntimeException(Messages.MESSAGES.deploymentIsNull());
    }

    SpringBeanProcessor processor = new SpringBeanProcessor(deployment);
    configurableWebApplicationContext.addBeanFactoryPostProcessor(processor);
    configurableWebApplicationContext.addApplicationListener(processor);
}
 
Example #19
Source File: CloudStackContextLoaderListener.java    From cosmic with Apache License 2.0 5 votes vote down vote up
@Override
protected void customizeContext(final ServletContext servletContext, final ConfigurableWebApplicationContext applicationContext) {
    super.customizeContext(servletContext, applicationContext);

    final String[] newLocations = cloudStackContext.getConfigLocationsForWeb(configuredParentName, applicationContext.getConfigLocations());

    applicationContext.setConfigLocations(newLocations);
}
 
Example #20
Source File: SpringLambdaContainerHandler.java    From aws-serverless-java-container with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a default SpringLambdaContainerHandler initialized with the `AwsProxyRequest` and `AwsProxyResponse` objects and sets the given profiles as active
 * @param applicationContext A custom ConfigurableWebApplicationContext to be used
 * @param profiles The spring profiles to activate
 * @return An initialized instance of the `SpringLambdaContainerHandler`
 * @throws ContainerInitializationException When the Spring framework fails to start.
 */
public static SpringLambdaContainerHandler<AwsProxyRequest, AwsProxyResponse> getAwsProxyHandler(ConfigurableWebApplicationContext applicationContext, String... profiles)
        throws ContainerInitializationException {
    return new SpringProxyHandlerBuilder<AwsProxyRequest>()
            .defaultProxy()
            .initializationWrapper(new InitializationWrapper())
            .springApplicationContext(applicationContext)
            .profiles(profiles)
            .buildAndInitialize();
}
 
Example #21
Source File: FrameworkServlet.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac) {
	if (ObjectUtils.identityToString(wac).equals(wac.getId())) {
		// The application context id is still set to its original default value
		// -> assign a more useful id based on available information
		if (this.contextId != null) {
			wac.setId(this.contextId);
		}
		else {
			// Generate default id...
			wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +
					ObjectUtils.getDisplayString(getServletContext().getContextPath()) + '/' + getServletName());
		}
	}

	wac.setServletContext(getServletContext());
	wac.setServletConfig(getServletConfig());
	wac.setNamespace(getNamespace());
	wac.addApplicationListener(new SourceFilteringListener(wac, new ContextRefreshListener()));

	// The wac environment's #initPropertySources will be called in any case when the context
	// is refreshed; do it eagerly here to ensure servlet property sources are in place for
	// use in any post-processing or initialization that occurs below prior to #refresh
	ConfigurableEnvironment env = wac.getEnvironment();
	if (env instanceof ConfigurableWebEnvironment) {
		((ConfigurableWebEnvironment) env).initPropertySources(getServletContext(), getServletConfig());
	}

	postProcessWebApplicationContext(wac);
	applyInitializers(wac);
	wac.refresh();
}
 
Example #22
Source File: CustomPropertySourceConfigurer.java    From airsonic-advanced with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void initialize(ConfigurableWebApplicationContext ctx) {
    // vars are searched in order: spring > jvm > env > app.prop > airsonic.prop > default consts
    // spring: java -jar pkg.jar --var=foo
    // jvm: java -jar -Dvar=foo pkg.jar
    // env: SET var=foo; java -jar pkg.jar

    Map<String, String> migratedProps = SettingsService.getMigratedPropertyKeys();

    // Migrate each property source key to its latest name
    // PropertySource precedence matters. Higher migrates first, lower will skip migration if key has already migrated
    // At lookup time, migrated properties have lower precedence (so more specific properties can override migrated properties)
    // Example for same start: env (higher precedence) and file (lower) need to migrate A -> B and both have A
    //  - env migrates A -> B, file skips chain (migration keys already present)
    //  - Lookup(A) will find env[A] (higher precedence)
    //  - Lookup(B) will find migrated[env[A]] since B does not exist in env and file, and migrated has env[A] (skipped file)
    // Example 1 for in-the-middle chain migration: env has C and file has A in migration A -> B -> C -> D
    //  - env migrates C -> D, file migrates A -> B (skips rest of the chain)
    //  - Lookup(A) finds file[A]
    //  - Lookup(B) finds migrated[file[A]]
    //  - Lookup(C) finds env[C]
    //  - Lookup(D) finds migrated[env[C]]
    // Example 2 for in-the-middle chain migration: env has A and file has C in migration A -> B -> C -> D
    //  - env migrates A -> B -> C -> D, file skips chain (migration keys already present)
    //  - Lookup(A) finds env[A]
    //  - Lookup(B) finds migrated[env[A]]
    //  - Lookup(C) finds file[C] (higher precedence than migrated[env[C]])
    //  - Lookup(D) finds migrated[env[A]]
    ctx.getEnvironment().getPropertySources().forEach(ps -> SettingsService.migratePropertySourceKeys(migratedProps, ps, MIGRATED));
    ctx.getEnvironment().getPropertySources().addLast(new MapPropertySource("migrated-properties", MIGRATED));

    // Migrate external property file
    SettingsService.migratePropFileKeys(migratedProps, ConfigurationPropertiesService.getInstance());
    ctx.getEnvironment().getPropertySources().addLast(new ConfigurationPropertySource("airsonic-properties", ConfigurationPropertiesService.getInstance().getConfiguration()));

    // Set default constants - only set if vars are blank so their PS need to be set first (or blank vars will get picked up first on look up)
    SettingsService.setDefaultConstants(ctx.getEnvironment(), DEFAULT_CONSTANTS);
    ctx.getEnvironment().getPropertySources().addFirst(new MapPropertySource("default-constants", DEFAULT_CONSTANTS));
}
 
Example #23
Source File: FrameworkServlet.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Instantiate the WebApplicationContext for this servlet, either a default
 * {@link org.springframework.web.context.support.XmlWebApplicationContext}
 * or a {@link #setContextClass custom context class}, if set.
 * <p>This implementation expects custom contexts to implement the
 * {@link org.springframework.web.context.ConfigurableWebApplicationContext}
 * interface. Can be overridden in subclasses.
 * <p>Do not forget to register this servlet instance as application listener on the
 * created context (for triggering its {@link #onRefresh callback}, and to call
 * {@link org.springframework.context.ConfigurableApplicationContext#refresh()}
 * before returning the context instance.
 * @param parent the parent ApplicationContext to use, or {@code null} if none
 * @return the WebApplicationContext for this servlet
 * @see org.springframework.web.context.support.XmlWebApplicationContext
 */
protected WebApplicationContext createWebApplicationContext(@Nullable ApplicationContext parent) {
	// 允许我们自定义容器的类型,通过 contextClass 属性进行配置
	// 但是类型必须要继承 ConfigurableWebApplicationContext,不然将会报错
	Class<?> contextClass = getContextClass();
	if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {
		throw new ApplicationContextException(
				"Fatal initialization error in servlet with name '" + getServletName() +
				"': custom WebApplicationContext class [" + contextClass.getName() +
				"] is not of type ConfigurableWebApplicationContext");
	}
	// 通过反射来创建 contextClass
	ConfigurableWebApplicationContext wac =
			(ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);

	wac.setEnvironment(getEnvironment());
	wac.setParent(parent);
	// 获取 contextConfigLocation 属性,配置在 servlet 初始化函数中
	String configLocation = getContextConfigLocation();
	if (configLocation != null) {
		wac.setConfigLocation(configLocation);
	}
	// 初始化 Spring 环境包括加载配置环境
	configureAndRefreshWebApplicationContext(wac);

	return wac;
}
 
Example #24
Source File: FrameworkServlet.java    From spring-analysis-note with MIT License 5 votes vote down vote up
protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac) {
	if (ObjectUtils.identityToString(wac).equals(wac.getId())) {
		// The application context id is still set to its original default value
		// -> assign a more useful id based on available information
		if (this.contextId != null) {
			wac.setId(this.contextId);
		}
		else {
			// Generate default id... 生成默认ID
			wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +
					ObjectUtils.getDisplayString(getServletContext().getContextPath()) + '/' + getServletName());
		}
	}

	wac.setServletContext(getServletContext());
	wac.setServletConfig(getServletConfig());
	wac.setNamespace(getNamespace());
	wac.addApplicationListener(new SourceFilteringListener(wac, new ContextRefreshListener()));

	// The wac environment's #initPropertySources will be called in any case when the context
	// is refreshed; do it eagerly here to ensure servlet property sources are in place for
	// use in any post-processing or initialization that occurs below prior to #refresh
	ConfigurableEnvironment env = wac.getEnvironment();
	if (env instanceof ConfigurableWebEnvironment) {
		((ConfigurableWebEnvironment) env).initPropertySources(getServletContext(), getServletConfig());
	}

	postProcessWebApplicationContext(wac);
	// 遍历 ApplicationContextInitializer,执行 initialize 方法
	applyInitializers(wac);
	// 关键的刷新,加载配置文件及整合 parent 到 wac
	wac.refresh();
}
 
Example #25
Source File: PropertiesInitializer.java    From proctor with Apache License 2.0 5 votes vote down vote up
protected List<String> getTomcatContextPropertyLocations(ConfigurableApplicationContext applicationContext) {
    if (!(applicationContext instanceof ConfigurableWebApplicationContext)) {
        return Collections.emptyList();
    }
    ConfigurableWebApplicationContext webApplicationContext = (ConfigurableWebApplicationContext) applicationContext;
    List<String> locations = Lists.newArrayList();
    final String tomcatContextPropertiesFile = webApplicationContext.getServletContext().getInitParameter(contextPropertiesParameterName);
    locations.add("file:" + tomcatContextPropertiesFile);
    return locations;
}
 
Example #26
Source File: MessageTagTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void nullMessageSource() throws JspException {
	PageContext pc = createPageContext();
	ConfigurableWebApplicationContext ctx = (ConfigurableWebApplicationContext)
			RequestContextUtils.findWebApplicationContext((HttpServletRequest) pc.getRequest(), pc.getServletContext());
	ctx.close();

	MessageTag tag = new MessageTag();
	tag.setPageContext(pc);
	tag.setCode("test");
	tag.setVar("testvar2");
	tag.doStartTag();
	assertEquals("Correct doEndTag return value", Tag.EVAL_PAGE, tag.doEndTag());
}
 
Example #27
Source File: CloudStackContextLoaderListener.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
@Override
protected void customizeContext(ServletContext servletContext, ConfigurableWebApplicationContext applicationContext) {
    super.customizeContext(servletContext, applicationContext);

    String[] newLocations = cloudStackContext.getConfigLocationsForWeb(configuredParentName, applicationContext.getConfigLocations());

    applicationContext.setConfigLocations(newLocations);
}
 
Example #28
Source File: FrameworkServlet.java    From java-technology-stack with MIT License 5 votes vote down vote up
protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac) {
	if (ObjectUtils.identityToString(wac).equals(wac.getId())) {
		// The application context id is still set to its original default value
		// -> assign a more useful id based on available information
		if (this.contextId != null) {
			wac.setId(this.contextId);
		}
		else {
			// Generate default id...
			wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +
					ObjectUtils.getDisplayString(getServletContext().getContextPath()) + '/' + getServletName());
		}
	}

	wac.setServletContext(getServletContext());
	wac.setServletConfig(getServletConfig());
	wac.setNamespace(getNamespace());
	wac.addApplicationListener(new SourceFilteringListener(wac, new ContextRefreshListener()));

	// The wac environment's #initPropertySources will be called in any case when the context
	// is refreshed; do it eagerly here to ensure servlet property sources are in place for
	// use in any post-processing or initialization that occurs below prior to #refresh
	ConfigurableEnvironment env = wac.getEnvironment();
	if (env instanceof ConfigurableWebEnvironment) {
		((ConfigurableWebEnvironment) env).initPropertySources(getServletContext(), getServletConfig());
	}

	postProcessWebApplicationContext(wac);
	applyInitializers(wac);
	wac.refresh();
}
 
Example #29
Source File: Initializer.java    From alf.io with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected WebApplicationContext createRootApplicationContext() {
    ConfigurableWebApplicationContext ctx = ((ConfigurableWebApplicationContext) super.createRootApplicationContext());
    Objects.requireNonNull(ctx, "Something really bad is happening...");
    this.environment = ctx.getEnvironment();
    return ctx;
}
 
Example #30
Source File: MessageTagTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void nullMessageSource() throws JspException {
	PageContext pc = createPageContext();
	ConfigurableWebApplicationContext ctx = (ConfigurableWebApplicationContext)
			RequestContextUtils.findWebApplicationContext((HttpServletRequest) pc.getRequest(), pc.getServletContext());
	ctx.close();

	MessageTag tag = new MessageTag();
	tag.setPageContext(pc);
	tag.setCode("test");
	tag.setVar("testvar2");
	tag.doStartTag();
	assertEquals("Correct doEndTag return value", Tag.EVAL_PAGE, tag.doEndTag());
}