@Override public EmbeddedServletContainer getEmbeddedServletContainer(ServletContextInitializer... initializers) { ClassLoader parentClassLoader = resourceLoader != null ? resourceLoader.getClassLoader() : ClassUtils.getDefaultClassLoader(); Package nettyPackage = Bootstrap.class.getPackage(); String title = nettyPackage.getImplementationTitle(); String version = nettyPackage.getImplementationVersion(); logger.info("Running with " + title + " " + version); NettyEmbeddedContext context = new NettyEmbeddedContext(getContextPath(), new URLClassLoader(new URL[]{}, parentClassLoader), SERVER_INFO); if (isRegisterDefaultServlet()) { logger.warn("This container does not support a default servlet"); } /*if (isRegisterJspServlet()) { logger.warn("This container does not support a JSP servlet"); }*/ for (ServletContextInitializer initializer : initializers) { try { initializer.onStartup(context); } catch (ServletException e) { throw new RuntimeException(e); } } int port = getPort() > 0 ? getPort() : new Random().nextInt(65535 - 1024) + 1024; InetSocketAddress address = new InetSocketAddress(port); logger.info("Server initialized with port: " + port); return new NettyEmbeddedServletContainer(address, context); }
@Override public EmbeddedServletContainer getEmbeddedServletContainer( ServletContextInitializer... initializers) { Tomcat tomcat = new Tomcat(); File baseDir = (this.baseDirectory != null ? this.baseDirectory : createTempDir("tomcat")); tomcat.setBaseDir(baseDir.getAbsolutePath()); Connector connector = new Connector(this.protocol); tomcat.getService().addConnector(connector); customizeConnector(connector); tomcat.setConnector(connector); tomcat.getHost().setAutoDeploy(false); configureEngine(tomcat.getEngine()); for (Connector additionalConnector : this.additionalTomcatConnectors) { tomcat.getService().addConnector(additionalConnector); } prepareContext(tomcat.getHost(), initializers); return getTomcatEmbeddedServletContainer(tomcat); }
/** * Configure the Tomcat {@link Context}. * @param context the Tomcat context * @param initializers initializers to apply */ protected void configureContext(Context context, ServletContextInitializer[] initializers) { TomcatStarter starter = new TomcatStarter(initializers); if (context instanceof TomcatEmbeddedContext) { // Should be true ((TomcatEmbeddedContext) context).setStarter(starter); } context.addServletContainerInitializer(starter, NO_CLASSES); for (LifecycleListener lifecycleListener : this.contextLifecycleListeners) { context.addLifecycleListener(lifecycleListener); } for (Valve valve : this.contextValves) { context.getPipeline().addValve(valve); } for (ErrorPage errorPage : getErrorPages()) { new TomcatErrorPage(errorPage).addToContext(context); } for (MimeMappings.Mapping mapping : getMimeMappings()) { context.addMimeMapping(mapping.getExtension(), mapping.getMimeType()); } configureSession(context); for (TomcatContextCustomizer customizer : this.tomcatContextCustomizers) { customizer.customize(context); } }
@Override public void onStartup(Set<Class<?>> classes, ServletContext servletContext) throws ServletException { try { for (ServletContextInitializer initializer : this.initializers) { initializer.onStartup(servletContext); } } catch (Exception ex) { this.startUpException = ex; // Prevent Tomcat from logging and re-throwing when we know we can // deal with it in the main thread, but log for information here. if (logger.isErrorEnabled()) { logger.error("Error starting Tomcat context. Exception: " + ex.getClass().getName() + ". Message: " + ex.getMessage()); } } }
@Override public EmbeddedServletContainer getEmbeddedServletContainer( ServletContextInitializer... initializers) { JettyEmbeddedWebAppContext context = new JettyEmbeddedWebAppContext(); int port = (getPort() >= 0 ? getPort() : 0); InetSocketAddress address = new InetSocketAddress(getAddress(), port); Server server = createServer(address); configureWebAppContext(context, initializers); server.setHandler(addHandlerWrappers(context)); this.logger.info("Server initialized with port: " + port); if (getSsl() != null && getSsl().isEnabled()) { SslContextFactory sslContextFactory = new SslContextFactory(); configureSsl(sslContextFactory, getSsl()); AbstractConnector connector = getSslServerConnectorFactory() .getConnector(server, sslContextFactory, port); server.setConnectors(new Connector[] { connector }); } for (JettyServerCustomizer customizer : getServerCustomizers()) { customizer.customize(server); } if (this.useForwardHeaders) { new ForwardHeadersCustomizer().customize(server); } return getJettyEmbeddedServletContainer(server); }
/** * Configure the given Jetty {@link WebAppContext} for use. * @param context the context to configure * @param initializers the set of initializers to apply */ protected final void configureWebAppContext(WebAppContext context, ServletContextInitializer... initializers) { Assert.notNull(context, "Context must not be null"); context.setTempDirectory(getTempDirectory()); if (this.resourceLoader != null) { context.setClassLoader(this.resourceLoader.getClassLoader()); } String contextPath = getContextPath(); context.setContextPath(StringUtils.hasLength(contextPath) ? contextPath : "/"); context.setDisplayName(getDisplayName()); configureDocumentRoot(context); if (isRegisterDefaultServlet()) { addDefaultServlet(context); } if (shouldRegisterJspServlet()) { addJspServlet(context); context.addBean(new JasperInitializer(context), true); } ServletContextInitializer[] initializersToUse = mergeInitializers(initializers); Configuration[] configurations = getWebAppContextConfigurations(context, initializersToUse); context.setConfigurations(configurations); configureSession(context); postProcessWebAppContext(context); }
@Test public void startBlocksUntilReadyToServe() throws Exception { AbstractEmbeddedServletContainerFactory factory = getFactory(); final Date[] date = new Date[1]; this.container = factory .getEmbeddedServletContainer(new ServletContextInitializer() { @Override public void onStartup(ServletContext servletContext) throws ServletException { try { Thread.sleep(500); date[0] = new Date(); } catch (InterruptedException ex) { throw new ServletException(ex); } } }); this.container.start(); assertThat(date[0]).isNotNull(); }
@Test public void loadOnStartAfterContextIsInitialized() throws Exception { AbstractEmbeddedServletContainerFactory factory = getFactory(); final InitCountingServlet servlet = new InitCountingServlet(); this.container = factory .getEmbeddedServletContainer(new ServletContextInitializer() { @Override public void onStartup(ServletContext servletContext) throws ServletException { servletContext.addServlet("test", servlet).setLoadOnStartup(1); } }); assertThat(servlet.getInitCount()).isEqualTo(0); this.container.start(); assertThat(servlet.getInitCount()).isEqualTo(1); }
@Test public void multipleConfigurations() throws Exception { AbstractEmbeddedServletContainerFactory factory = getFactory(); ServletContextInitializer[] initializers = new ServletContextInitializer[6]; for (int i = 0; i < initializers.length; i++) { initializers[i] = mock(ServletContextInitializer.class); } factory.setInitializers(Arrays.asList(initializers[2], initializers[3])); factory.addInitializers(initializers[4], initializers[5]); this.container = factory.getEmbeddedServletContainer(initializers[0], initializers[1]); this.container.start(); InOrder ordered = inOrder((Object[]) initializers); for (ServletContextInitializer initializer : initializers) { ordered.verify(initializer).onStartup((ServletContext) anyObject()); } }
@Test public void rootServletContextResource() throws Exception { AbstractEmbeddedServletContainerFactory factory = getFactory(); final AtomicReference<URL> rootResource = new AtomicReference<URL>(); this.container = factory .getEmbeddedServletContainer(new ServletContextInitializer() { @Override public void onStartup(ServletContext servletContext) throws ServletException { try { rootResource.set(servletContext.getResource("/")); } catch (MalformedURLException ex) { throw new ServletException(ex); } } }); this.container.start(); assertThat(rootResource.get()).isNotNull(); }
protected final ServletContextInitializer sessionServletRegistration() { ServletRegistrationBean bean = new ServletRegistrationBean(new ExampleServlet() { @Override public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { HttpSession session = ((HttpServletRequest) request).getSession(true); long value = System.currentTimeMillis(); Object existing = session.getAttribute("boot"); session.setAttribute("boot", value); PrintWriter writer = response.getWriter(); writer.append(String.valueOf(existing) + ":" + value); } }, "/session"); bean.setName("session"); return bean; }
@Test public void servletContextInitializerBeans() throws Exception { addEmbeddedServletContainerFactoryBean(); ServletContextInitializer initializer1 = mock(ServletContextInitializer.class, withSettings().extraInterfaces(Ordered.class)); given(((Ordered) initializer1).getOrder()).willReturn(1); ServletContextInitializer initializer2 = mock(ServletContextInitializer.class, withSettings().extraInterfaces(Ordered.class)); given(((Ordered) initializer2).getOrder()).willReturn(2); this.context.registerBeanDefinition("initializerBean2", beanDefinition(initializer2)); this.context.registerBeanDefinition("initializerBean1", beanDefinition(initializer1)); this.context.refresh(); ServletContext servletContext = getEmbeddedServletContainerFactory() .getServletContext(); InOrder ordered = inOrder(initializer1, initializer2); ordered.verify(initializer1).onStartup(servletContext); ordered.verify(initializer2).onStartup(servletContext); }
@Test public void servletContextInitializerBeansDoesNotSkipServletsAndFilters() throws Exception { addEmbeddedServletContainerFactoryBean(); ServletContextInitializer initializer = mock(ServletContextInitializer.class); Servlet servlet = mock(Servlet.class); Filter filter = mock(Filter.class); this.context.registerBeanDefinition("initializerBean", beanDefinition(initializer)); this.context.registerBeanDefinition("servletBean", beanDefinition(servlet)); this.context.registerBeanDefinition("filterBean", beanDefinition(filter)); this.context.refresh(); ServletContext servletContext = getEmbeddedServletContainerFactory() .getServletContext(); verify(initializer).onStartup(servletContext); verify(servletContext).addServlet(anyString(), (Servlet) anyObject()); verify(servletContext).addFilter(anyString(), (Filter) anyObject()); }
@Override public EmbeddedServletContainer getEmbeddedServletContainer( ServletContextInitializer... initializers) { Tomcat tomcat = new Tomcat(); File baseDir = (this.baseDirectory != null ? this.baseDirectory : createTempDir("tomcat")); tomcat.setBaseDir(baseDir.getAbsolutePath()); Connector connector = new Connector(this.protocol); tomcat.getService().addConnector(connector); customizeConnector(connector); tomcat.setConnector(connector); tomcat.getHost().setAutoDeploy(false); tomcat.getEngine().setBackgroundProcessorDelay(-1); for (Connector additionalConnector : this.additionalTomcatConnectors) { tomcat.getService().addConnector(additionalConnector); } prepareContext(tomcat.getHost(), initializers); return getTomcatEmbeddedServletContainer(tomcat); }
/** * Configure the given Jetty {@link WebAppContext} for use. * @param context the context to configure * @param initializers the set of initializers to apply */ protected final void configureWebAppContext(WebAppContext context, ServletContextInitializer... initializers) { Assert.notNull(context, "Context must not be null"); context.setTempDirectory(getTempDirectory()); if (this.resourceLoader != null) { context.setClassLoader(this.resourceLoader.getClassLoader()); } String contextPath = getContextPath(); context.setContextPath(StringUtils.hasLength(contextPath) ? contextPath : "/"); context.setDisplayName(getDisplayName()); configureDocumentRoot(context); if (isRegisterDefaultServlet()) { addDefaultServlet(context); } if (shouldRegisterJspServlet()) { addJspServlet(context); } ServletContextInitializer[] initializersToUse = mergeInitializers(initializers); Configuration[] configurations = getWebAppContextConfigurations(context, initializersToUse); context.setConfigurations(configurations); configureSession(context); postProcessWebAppContext(context); }
@Override protected void configureContext(Context context, ServletContextInitializer[] servletContextInits) { context.setCookies(true); context.setDistributable(true); context.setIgnoreAnnotations(true); context.setTldValidation(true); context.setUseHttpOnly(false); context.setXmlNamespaceAware(true); context.setXmlValidation(true); context.addApplicationListener(WsContextListener.class.getName()); ((StandardContext) context).setWorkDir(this.workDir.getAbsolutePath()); super.configureContext(context, ArrayUtils.add(servletContextInits, 0, new SdcctSessionConfigServletContextInitializer())); }
@Bean public ServletContextInitializer contextInitParamsInitializer(final ResteasyConfigurationProperties resteasy) { return new ServletContextInitializer() { @Override public void onStartup(ServletContext servletContext) throws ServletException { for (Entry<String, String> entry : resteasy.getInit().entrySet()) { servletContext.setInitParameter(entry.getKey(), entry.getValue()); } } }; }
@Bean public ServletContextInitializer initializer() { return new ServletContextInitializer() { @Override public void onStartup(ServletContext servletContext) throws ServletException { servletContext.setInitParameter("resteasy.role.based.security", "true"); } }; }
@Bean public ServletContextInitializer servletContextInitializer() { return new ServletContextInitializer() { @Override public void onStartup(ServletContext servletContext) throws ServletException { ServletContextHolder.setServletContext(servletContext); } }; }
private void addFilters(ConfigurableMockMvcBuilder<?> builder) { ServletContextInitializerBeans Initializers = new ServletContextInitializerBeans( this.context); for (ServletContextInitializer initializer : Initializers) { if (initializer instanceof FilterRegistrationBean) { addFilter(builder, (FilterRegistrationBean) initializer); } if (initializer instanceof DelegatingFilterProxyRegistrationBean) { addFilter(builder, (DelegatingFilterProxyRegistrationBean) initializer); } } }
/** * Utility method that can be used by subclasses wishing to combine the specified * {@link ServletContextInitializer} parameters with those defined in this instance. * @param initializers the initializers to merge * @return a complete set of merged initializers (with the specified parameters * appearing first) */ protected final ServletContextInitializer[] mergeInitializers( ServletContextInitializer... initializers) { List<ServletContextInitializer> mergedInitializers = new ArrayList<ServletContextInitializer>(); mergedInitializers.addAll(Arrays.asList(initializers)); mergedInitializers.addAll(this.initializers); return mergedInitializers .toArray(new ServletContextInitializer[mergedInitializers.size()]); }
protected void prepareContext(Host host, ServletContextInitializer[] initializers) { File docBase = getValidDocumentRoot(); docBase = (docBase != null ? docBase : createTempDir("tomcat-docbase")); TomcatEmbeddedContext context = new TomcatEmbeddedContext(); context.setName(getContextPath()); context.setDisplayName(getDisplayName()); context.setPath(getContextPath()); context.setDocBase(docBase.getAbsolutePath()); context.addLifecycleListener(new FixContextListener()); context.setParentClassLoader( this.resourceLoader != null ? this.resourceLoader.getClassLoader() : ClassUtils.getDefaultClassLoader()); try { context.setUseRelativeRedirects(false); } catch (NoSuchMethodError ex) { // Tomcat is < 8.0.30. Continue } SkipPatternJarScanner.apply(context, this.tldSkip); WebappLoader loader = new WebappLoader(context.getParentClassLoader()); loader.setLoaderClass(TomcatEmbeddedWebappClassLoader.class.getName()); loader.setDelegate(true); context.setLoader(loader); if (isRegisterDefaultServlet()) { addDefaultServlet(context); } if (shouldRegisterJspServlet()) { addJspServlet(context); addJasperInitializer(context); context.addLifecycleListener(new StoreMergedWebXmlListener()); } ServletContextInitializer[] initializersToUse = mergeInitializers(initializers); configureContext(context, initializersToUse); host.addChild(context); postProcessContext(context); }
@Override public EmbeddedServletContainer getEmbeddedServletContainer( ServletContextInitializer... initializers) { DeploymentManager manager = createDeploymentManager(initializers); int port = getPort(); Builder builder = createBuilder(port); return getUndertowEmbeddedServletContainer(builder, manager, port); }
private DeploymentManager createDeploymentManager( ServletContextInitializer... initializers) { DeploymentInfo deployment = Servlets.deployment(); registerServletContainerInitializerToDriveServletContextInitializers(deployment, initializers); deployment.setClassLoader(getServletClassLoader()); deployment.setContextPath(getContextPath()); deployment.setDisplayName(getDisplayName()); deployment.setDeploymentName("spring-boot"); if (isRegisterDefaultServlet()) { deployment.addServlet(Servlets.servlet("default", DefaultServlet.class)); } configureErrorPages(deployment); deployment.setServletStackTraces(ServletStackTraces.NONE); deployment.setResourceManager(getDocumentRootResourceManager()); configureMimeMappings(deployment); for (UndertowDeploymentInfoCustomizer customizer : this.deploymentInfoCustomizers) { customizer.customize(deployment); } if (isAccessLogEnabled()) { configureAccessLog(deployment); } if (isPersistSession()) { File dir = getValidSessionStoreDir(); deployment.setSessionPersistenceManager(new FileSessionPersistence(dir)); } DeploymentManager manager = Servlets.newContainer().addDeployment(deployment); manager.deploy(); SessionManager sessionManager = manager.getDeployment().getSessionManager(); int sessionTimeout = (getSessionTimeout() > 0 ? getSessionTimeout() : -1); sessionManager.setDefaultSessionTimeout(sessionTimeout); return manager; }
private void registerServletContainerInitializerToDriveServletContextInitializers( DeploymentInfo deployment, ServletContextInitializer... initializers) { ServletContextInitializer[] mergedInitializers = mergeInitializers(initializers); Initializer initializer = new Initializer(mergedInitializers); deployment.addServletContainerInitalizer(new ServletContainerInitializerInfo( Initializer.class, new ImmediateInstanceFactory<ServletContainerInitializer>(initializer), NO_CLASSES)); }
@Override public void onStartup(Set<Class<?>> classes, ServletContext servletContext) throws ServletException { for (ServletContextInitializer initializer : this.initializers) { initializer.onStartup(servletContext); } }
/** * Return the Jetty {@link Configuration}s that should be applied to the server. * @param webAppContext the Jetty {@link WebAppContext} * @param initializers the {@link ServletContextInitializer}s to apply * @return configurations to apply */ protected Configuration[] getWebAppContextConfigurations(WebAppContext webAppContext, ServletContextInitializer... initializers) { List<Configuration> configurations = new ArrayList<Configuration>(); configurations.add( getServletContextInitializerConfiguration(webAppContext, initializers)); configurations.addAll(getConfigurations()); configurations.add(getErrorPageConfiguration()); configurations.add(getMimeTypeConfiguration()); return configurations.toArray(new Configuration[configurations.size()]); }
private void callInitializers() throws ServletException { try { setExtendedListenerTypes(true); for (ServletContextInitializer initializer : ServletContextInitializerConfiguration.this.initializers) { initializer.onStartup(this.context.getServletContext()); } } finally { setExtendedListenerTypes(false); } }
/** * Returns the {@link ServletContextInitializer} that will be used to complete the * setup of this {@link WebApplicationContext}. * @return the self initializer * @see #prepareEmbeddedWebApplicationContext(ServletContext) */ private org.springframework.boot.web.servlet.ServletContextInitializer getSelfInitializer() { return new ServletContextInitializer() { @Override public void onStartup(ServletContext servletContext) throws ServletException { selfInitialize(servletContext); } }; }
private void selfInitialize(ServletContext servletContext) throws ServletException { prepareEmbeddedWebApplicationContext(servletContext); ConfigurableListableBeanFactory beanFactory = getBeanFactory(); ExistingWebApplicationScopes existingScopes = new ExistingWebApplicationScopes( beanFactory); WebApplicationContextUtils.registerWebApplicationScopes(beanFactory, getServletContext()); existingScopes.restore(); WebApplicationContextUtils.registerEnvironmentBeans(beanFactory, getServletContext()); for (ServletContextInitializer beans : getServletContextInitializerBeans()) { beans.onStartup(servletContext); } }