/** * 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; }
@Override protected WebApplicationContext createWebApplicationContext(ApplicationContext parent) { if (this.logger.isDebugEnabled()) { this.logger.debug("Servlet with name '" + getServletName() + "' will try to create custom WebApplicationContext context of class '" + CubaXmlWebApplicationContext.class.getName() + "'" + ", using parent context [" + parent + "]"); } ConfigurableWebApplicationContext wac = new CubaXmlWebApplicationContext() { @Override protected ResourcePatternResolver getResourcePatternResolver() { if (dependencyJars == null || dependencyJars.isEmpty()) { throw new RuntimeException("No JARs defined for the 'web' block. " + "Please check that web.dependencies file exists in WEB-INF directory."); } return new SingleAppResourcePatternResolver(this, dependencyJars); } }; wac.setEnvironment(getEnvironment()); wac.setParent(parent); wac.setConfigLocation(getContextConfigLocation()); configureAndRefreshWebApplicationContext(wac); return wac; }
/** * Apply any relevant post processing the {@link ApplicationContext}. Subclasses can * apply additional processing as required. * @param context the application context */ protected void postProcessApplicationContext(ConfigurableApplicationContext context) { if (this.webEnvironment) { if (context instanceof ConfigurableWebApplicationContext) { ConfigurableWebApplicationContext configurableContext = (ConfigurableWebApplicationContext) context; if (this.beanNameGenerator != null) { configurableContext.getBeanFactory().registerSingleton( AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR, this.beanNameGenerator); } } } if (this.resourceLoader != null) { if (context instanceof GenericApplicationContext) { ((GenericApplicationContext) context) .setResourceLoader(this.resourceLoader); } if (context instanceof DefaultResourceLoader) { ((DefaultResourceLoader) context) .setClassLoader(this.resourceLoader.getClassLoader()); } } }
/** * Allows loading/override of custom bean definitions from sakai.home * * <p>The pattern is the 'servlet_name-context.xml'</p> * * @param servletContext current servlet context * @return the new WebApplicationContext * @throws org.springframework.beans.BeansException * if the context couldn't be initialized */ @Override public WebApplicationContext initWebApplicationContext(ServletContext servletContext) throws BeansException { ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) super.initWebApplicationContext(servletContext); // optionally look in sakai home for additional bean deifinitions to load if (cwac != null) { final String servletName = servletContext.getServletContextName(); String location = getHomeBeanDefinitionIfExists(servletName); if (StringUtils.isNotBlank(location)) { log.debug("Servlet " + servletName + " is attempting to load bean definition [" + location + "]"); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader((BeanDefinitionRegistry) cwac.getBeanFactory()); try { int loaded = reader.loadBeanDefinitions(new FileSystemResource(location)); log.info("Servlet " + servletName + " loaded " + loaded + " beans from [" + location + "]"); AnnotationConfigUtils.registerAnnotationConfigProcessors(reader.getRegistry()); cwac.getBeanFactory().preInstantiateSingletons(); } catch (BeanDefinitionStoreException bdse) { log.warn("Failure loading beans from [" + location + "]", bdse); } catch (BeanCreationException bce) { log.warn("Failure instantiating beans from [" + location + "]", bce); } } } return cwac; }
@Override protected void customizeContext(ServletContext servletContext, ConfigurableWebApplicationContext applicationContext) { super.customizeContext(servletContext, applicationContext); String policy = servletContext.getInitParameter("superfly-policy"); if (policy == null) { policy = Policy.NONE.getIdentifier(); } String disableHotp = servletContext.getInitParameter("disable-hotp"); if ("true".equals(disableHotp)) { policy = Policy.NONE.getIdentifier(); } String[] oldLocations = applicationContext.getConfigLocations(); String[] newLocations = new String[oldLocations.length]; for (int i = 0; i < oldLocations.length; i++) { newLocations[i] = oldLocations[i].replaceAll("\\!policy\\!", policy); } applicationContext.setConfigLocations(newLocations); }
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; }
@Override public void initialize(ConfigurableWebApplicationContext ctx) { try { this.setLocations(ctx.getResources("/WEB-INF/application-customer-dev.properties")); Properties props = this.mergeProperties(); if (props.containsKey(TERRACOTTA_URL_KEY)) { System.setProperty(TERRACOTTA_URL_KEY, props.getProperty(TERRACOTTA_URL_KEY)); } ctx.getEnvironment().getPropertySources().addLast(new PropertiesPropertySource("default_properties", props)); this.setLocations(ctx.getResources("classpath:application-customer.properties")); props = this.mergeProperties(); if (props.containsKey(TERRACOTTA_URL_KEY)) { System.setProperty(TERRACOTTA_URL_KEY, props.getProperty(TERRACOTTA_URL_KEY)); } ctx.getEnvironment().getPropertySources() .addFirst(new PropertiesPropertySource("environment_properties", props)); } catch (IOException e) { logger.info("Unable to load properties file.", e); } }
@Override public void initialize(ConfigurableWebApplicationContext ctx) { try { this.setLocations(ctx.getResources("/WEB-INF/application-batch-dev.properties")); Properties props = this.mergeProperties(); if (props.containsKey(TERRACOTTA_URL_KEY)) { System.setProperty(TERRACOTTA_URL_KEY, props.getProperty(TERRACOTTA_URL_KEY)); } ctx.getEnvironment().getPropertySources().addLast(new PropertiesPropertySource("default_properties", props)); this.setLocations(ctx.getResources("classpath:application-batch.properties")); props = this.mergeProperties(); if (props.containsKey(TERRACOTTA_URL_KEY)) { System.setProperty(TERRACOTTA_URL_KEY, props.getProperty(TERRACOTTA_URL_KEY)); } ctx.getEnvironment().getPropertySources() .addFirst(new PropertiesPropertySource("environment_properties", props)); } catch (IOException e) { logger.info("Unable to load properties file.", e); } }
@SuppressWarnings({"unchecked", "rawtypes"}) @Test public void test_no_register_after_close() { ApplicationRegistrator registrator = mock(ApplicationRegistrator.class); TaskScheduler scheduler = mock(TaskScheduler.class); RegistrationApplicationListener listener = new RegistrationApplicationListener(registrator, scheduler); ScheduledFuture task = mock(ScheduledFuture.class); when(scheduler.scheduleAtFixedRate(isA(Runnable.class), eq(Duration.ofSeconds(10)))).thenReturn(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); }
protected void customizeContext(ServletContext servletContext, ConfigurableWebApplicationContext applicationContext) { String[] configLocations = applicationContext.getConfigLocations(); String[] jresConfigLocations = null; if (configLocations == null || configLocations.length < 1) { configLocations = StringUtils.tokenizeToStringArray( servletContext.getInitParameter(CONFIG_LOCATION_PARAM), ",; \t\n"); } if (configLocations != null) { jresConfigLocations = new String[configLocations.length + 2]; jresConfigLocations[0] = "classpath:conf/spring/jres-web-beans.xml"; jresConfigLocations[1] = "classpath:conf/spring/jres-common-beans.xml"; int index = 2; for (String config : configLocations) { jresConfigLocations[index] = config; index++; } } applicationContext.setConfigLocations(jresConfigLocations); super.customizeContext(servletContext, applicationContext); }
/** * Close Spring's web application context for the given servlet context. If * the default {@link #loadParentContext(ServletContext)} implementation, * which uses ContextSingletonBeanFactoryLocator, has loaded any shared * parent context, release one reference to that shared parent context. * <p>If overriding {@link #loadParentContext(ServletContext)}, you may have * to override this method as well. * @param servletContext the ServletContext that the WebApplicationContext runs in */ public void closeWebApplicationContext(ServletContext servletContext) { servletContext.log("Closing Spring root WebApplicationContext"); try { if (this.context instanceof ConfigurableWebApplicationContext) { ((ConfigurableWebApplicationContext) this.context).close(); } } finally { currentContextPerThread.remove(Thread.currentThread().getContextClassLoader()); servletContext.removeAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); if (this.parentContextRef != null) { this.parentContextRef.release(); } } }
private void addDataSourceProfile(ConfigurableWebApplicationContext ctx) { DataSourceConfigType dataSourceConfigType; String rawType = ctx.getEnvironment().getProperty(DATASOURCE_CONFIG_TYPE); if(StringUtils.isNotBlank(rawType)) { dataSourceConfigType = DataSourceConfigType.valueOf(StringUtils.upperCase(rawType)); } else { dataSourceConfigType = DataSourceConfigType.LEGACY; } String dataSourceTypeProfile = StringUtils.lowerCase(dataSourceConfigType.name()); List<String> existingProfiles = Lists.newArrayList(ctx.getEnvironment().getActiveProfiles()); existingProfiles.add(dataSourceTypeProfile); ctx.getEnvironment().setActiveProfiles(existingProfiles.toArray(new String[0])); }
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; }
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(); }
@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()); }
@Override protected void configureAndRefreshWebApplicationContext( ConfigurableWebApplicationContext wac, ServletContext sc) { wac.addBeanFactoryPostProcessor(new ApplicationBeanFactoryPostProcessor( ApplicationServletContextListener.this.applicationConfig)); super.configureAndRefreshWebApplicationContext(wac, sc); }
@Override protected void configureAndRefreshWebApplicationContext( ConfigurableWebApplicationContext wac) { wac.addBeanFactoryPostProcessor(new ApplicationBeanFactoryPostProcessor( ApplicationServlet.this.applicationConfig)); super.configureAndRefreshWebApplicationContext(wac); }
/** * Creates a default SpringLambdaContainerHandler initialized with the `AwsProxyRequest` and `AwsProxyResponse` objects * @param applicationContext A custom ConfigurableWebApplicationContext to be used * @return An initialized instance of the `SpringLambdaContainerHandler` * @throws ContainerInitializationException */ public static SpringLambdaContainerHandler<AwsProxyRequest, AwsProxyResponse> getAwsProxyHandler(ConfigurableWebApplicationContext applicationContext) throws ContainerInitializationException { return new SpringLambdaContainerHandler<>( new AwsProxyHttpServletRequestReader(), new AwsProxyHttpServletResponseWriter(), new AwsProxySecurityContextWriter(), new AwsProxyExceptionHandler(), applicationContext ); }
/** * Creates a new container handler with the given reader and writer objects * * @param requestReader An implementation of `RequestReader` * @param responseWriter An implementation of `ResponseWriter` * @param securityContextWriter An implementation of `SecurityContextWriter` * @param exceptionHandler An implementation of `ExceptionHandler` * @throws ContainerInitializationException */ public SpringLambdaContainerHandler(RequestReader<RequestType, AwsProxyHttpServletRequest> requestReader, ResponseWriter<AwsHttpServletResponse, ResponseType> responseWriter, SecurityContextWriter<RequestType> securityContextWriter, ExceptionHandler<ResponseType> exceptionHandler, ConfigurableWebApplicationContext applicationContext) throws ContainerInitializationException { super(requestReader, responseWriter, securityContextWriter, exceptionHandler); initializer = new LambdaSpringApplicationInitializer(applicationContext); }
@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); }
@Override public void initialize(ConfigurableWebApplicationContext applicationContext) { applicationContext.setServletContext(this.servletContext); if (this.addApplicationContextAttribute) { this.servletContext.setAttribute( WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, applicationContext); } }
@Test public void errorPageAvailableWithParentContext() throws Exception { setup((ConfigurableWebApplicationContext) new SpringApplicationBuilder( ParentConfiguration.class).child(ChildConfiguration.class) .run("--server.port=0")); MvcResult response = this.mockMvc .perform(get("/error").accept(MediaType.TEXT_HTML)) .andExpect(status().is5xxServerError()).andReturn(); String content = response.getResponse().getContentAsString(); assertThat(content).contains("status=999"); }
@Test public void errorPageAvailableWithMvcIncluded() throws Exception { setup((ConfigurableWebApplicationContext) new SpringApplication( WebMvcIncludedConfiguration.class).run("--server.port=0")); MvcResult response = this.mockMvc .perform(get("/error").accept(MediaType.TEXT_HTML)) .andExpect(status().is5xxServerError()).andReturn(); String content = response.getResponse().getContentAsString(); assertThat(content).contains("status=999"); }
@Test public void errorPageNotAvailableWithWhitelabelDisabled() throws Exception { setup((ConfigurableWebApplicationContext) new SpringApplication( WebMvcIncludedConfiguration.class).run("--server.port=0", "--server.error.whitelabel.enabled=false")); this.thrown.expect(ServletException.class); this.mockMvc.perform(get("/error").accept(MediaType.TEXT_HTML)); }
@Test public void errorControllerWithAop() throws Exception { setup((ConfigurableWebApplicationContext) new SpringApplication( WithAopConfiguration.class).run("--server.port=0")); MvcResult response = this.mockMvc .perform(get("/error").accept(MediaType.TEXT_HTML)) .andExpect(status().is5xxServerError()).andReturn(); String content = response.getResponse().getContentAsString(); assertThat(content).contains("status=999"); }
@Test public void homePageNotFound() throws Exception { this.wac = (ConfigurableWebApplicationContext) new SpringApplicationBuilder( TestConfiguration.class).run(); this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); this.mockMvc.perform(get("/")).andExpect(status().isNotFound()).andReturn(); }
@Test public void homePageCustomLocation() throws Exception { this.wac = (ConfigurableWebApplicationContext) new SpringApplicationBuilder( TestConfiguration.class) .properties("spring.resources.staticLocations:classpath:/custom/") .run(); this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); this.mockMvc.perform(get("/")).andExpect(status().isOk()).andReturn(); }
@Test public void homePageCustomLocationNoTrailingSlash() throws Exception { this.wac = (ConfigurableWebApplicationContext) new SpringApplicationBuilder( TestConfiguration.class) .properties("spring.resources.staticLocations:classpath:/custom") .run(); this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); this.mockMvc.perform(get("/")).andExpect(status().isOk()).andReturn(); }
@Override public void reloadBackend() { List<String> configLocs = Lists.newArrayList("classpath:spring/web/commonContext.xml"); if ("on".equals(properties.getProperty("easyrec.rest"))) { configLocs.add(configLocations.get("easyrec.rest")); } // if no config found use default if (configLocs.size() == 1) { configLocs.add(configLocations.get("easyrec.rest")); } if ("on".equals(properties.getProperty("easyrec.dev"))) { configLocs.add(configLocations.get("easyrec.dev")); } ApplicationContext webctx = applicationContext; ApplicationContext parent = webctx.getParent(); if (parent instanceof ConfigurableWebApplicationContext) { ((ConfigurableWebApplicationContext) parent).setConfigLocations( configLocs.toArray(new String[configLocs.size()])); ((ConfigurableWebApplicationContext) parent).refresh(); } setDataSource(parent.getBean("easyrecDataSource", com.zaxxer.hikari.HikariDataSource.class)); }
@Override public void reloadFrontend() { ApplicationContext webctx = applicationContext; if (webctx instanceof ConfigurableWebApplicationContext) { ((ConfigurableWebApplicationContext) webctx) .setConfigLocation("classpath:spring/web/easyrecContext.xml"); ((ConfigurableWebApplicationContext) webctx).refresh(); } }