Search in sources :

Example 6 with ServletContextEvent

use of jakarta.servlet.ServletContextEvent in project spring-framework by spring-projects.

the class ContextLoaderTests method contextLoaderWithInvalidContext.

@Test
void contextLoaderWithInvalidContext() throws Exception {
    MockServletContext sc = new MockServletContext("");
    sc.addInitParameter(ContextLoader.CONTEXT_CLASS_PARAM, "org.springframework.web.context.support.InvalidWebApplicationContext");
    ServletContextListener listener = new ContextLoaderListener();
    ServletContextEvent event = new ServletContextEvent(sc);
    assertThatExceptionOfType(ApplicationContextException.class).isThrownBy(() -> listener.contextInitialized(event)).withCauseInstanceOf(ClassNotFoundException.class);
}
Also used : ServletContextListener(jakarta.servlet.ServletContextListener) MockServletContext(org.springframework.web.testfixture.servlet.MockServletContext) ServletContextEvent(jakarta.servlet.ServletContextEvent) Test(org.junit.jupiter.api.Test)

Example 7 with ServletContextEvent

use of jakarta.servlet.ServletContextEvent in project spring-framework by spring-projects.

the class ContextLoaderTests method contextLoaderListenerWithDefaultContext.

@Test
void contextLoaderListenerWithDefaultContext() {
    MockServletContext sc = new MockServletContext("");
    sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM, "/org/springframework/web/context/WEB-INF/applicationContext.xml " + "/org/springframework/web/context/WEB-INF/context-addition.xml");
    ServletContextListener listener = new ContextLoaderListener();
    ServletContextEvent event = new ServletContextEvent(sc);
    listener.contextInitialized(event);
    String contextAttr = WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE;
    WebApplicationContext context = (WebApplicationContext) sc.getAttribute(contextAttr);
    boolean condition1 = context instanceof XmlWebApplicationContext;
    assertThat(condition1).as("Correct WebApplicationContext exposed in ServletContext").isTrue();
    assertThat(WebApplicationContextUtils.getRequiredWebApplicationContext(sc) instanceof XmlWebApplicationContext).isTrue();
    LifecycleBean lb = (LifecycleBean) context.getBean("lifecycle");
    assertThat(context.containsBean("father")).as("Has father").isTrue();
    assertThat(context.containsBean("rod")).as("Has rod").isTrue();
    assertThat(context.containsBean("kerry")).as("Has kerry").isTrue();
    boolean condition = !lb.isDestroyed();
    assertThat(condition).as("Not destroyed").isTrue();
    assertThat(context.containsBean("beans1.bean1")).isFalse();
    assertThat(context.containsBean("beans1.bean2")).isFalse();
    listener.contextDestroyed(event);
    assertThat(lb.isDestroyed()).as("Destroyed").isTrue();
    assertThat(sc.getAttribute(contextAttr)).isNull();
    assertThat(WebApplicationContextUtils.getWebApplicationContext(sc)).isNull();
}
Also used : XmlWebApplicationContext(org.springframework.web.context.support.XmlWebApplicationContext) ServletContextListener(jakarta.servlet.ServletContextListener) LifecycleBean(org.springframework.beans.testfixture.beans.LifecycleBean) MockServletContext(org.springframework.web.testfixture.servlet.MockServletContext) ServletContextEvent(jakarta.servlet.ServletContextEvent) SimpleWebApplicationContext(org.springframework.web.servlet.SimpleWebApplicationContext) XmlWebApplicationContext(org.springframework.web.context.support.XmlWebApplicationContext) Test(org.junit.jupiter.api.Test)

Example 8 with ServletContextEvent

use of jakarta.servlet.ServletContextEvent in project spring-framework by spring-projects.

the class ContextLoaderTests method contextLoaderListenerWithMixedContextInitializers.

@Test
void contextLoaderListenerWithMixedContextInitializers() {
    MockServletContext sc = new MockServletContext("");
    sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM, "org/springframework/web/context/WEB-INF/ContextLoaderTests-acc-context.xml");
    sc.addInitParameter(ContextLoader.CONTEXT_INITIALIZER_CLASSES_PARAM, TestContextInitializer.class.getName());
    sc.addInitParameter(ContextLoader.GLOBAL_INITIALIZER_CLASSES_PARAM, TestWebContextInitializer.class.getName());
    ContextLoaderListener listener = new ContextLoaderListener();
    listener.contextInitialized(new ServletContextEvent(sc));
    WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
    TestBean testBean = wac.getBean(TestBean.class);
    assertThat(testBean.getName()).isEqualTo("testName");
    assertThat(wac.getServletContext().getAttribute("initialized")).isNotNull();
}
Also used : TestBean(org.springframework.beans.testfixture.beans.TestBean) MockServletContext(org.springframework.web.testfixture.servlet.MockServletContext) ServletContextEvent(jakarta.servlet.ServletContextEvent) SimpleWebApplicationContext(org.springframework.web.servlet.SimpleWebApplicationContext) XmlWebApplicationContext(org.springframework.web.context.support.XmlWebApplicationContext) Test(org.junit.jupiter.api.Test)

Example 9 with ServletContextEvent

use of jakarta.servlet.ServletContextEvent in project spring-boot by spring-projects.

the class JettyServletWebServerFactoryTests method faultyListenerCausesStartFailure.

@Test
void faultyListenerCausesStartFailure() {
    JettyServletWebServerFactory factory = getFactory();
    factory.addServerCustomizers((JettyServerCustomizer) (server) -> {
        Collection<WebAppContext> contexts = server.getBeans(WebAppContext.class);
        EventListener eventListener = new ServletContextListener() {

            @Override
            public void contextInitialized(ServletContextEvent event) {
                throw new RuntimeException();
            }

            @Override
            public void contextDestroyed(ServletContextEvent event) {
            }
        };
        WebAppContext context = contexts.iterator().next();
        try {
            context.addEventListener(eventListener);
        } catch (NoSuchMethodError ex) {
            Method addEventListener = ReflectionUtils.findMethod(context.getClass(), "addEventListener", EventListener.class);
            ReflectionUtils.invokeMethod(addEventListener, context, eventListener);
        }
    });
    assertThatExceptionOfType(WebServerException.class).isThrownBy(() -> {
        JettyWebServer jettyWebServer = (JettyWebServer) factory.getWebServer();
        try {
            jettyWebServer.start();
        } finally {
            QueuedThreadPool threadPool = (QueuedThreadPool) jettyWebServer.getServer().getThreadPool();
            assertThat(threadPool.isRunning()).isFalse();
        }
    });
}
Also used : SslConnectionFactory(org.eclipse.jetty.server.SslConnectionFactory) WebAppContext(org.eclipse.jetty.webapp.WebAppContext) Arrays(java.util.Arrays) ClassMatcher(org.eclipse.jetty.webapp.ClassMatcher) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Disabled(org.junit.jupiter.api.Disabled) Header(org.apache.http.Header) HttpHostConnectException(org.apache.http.conn.HttpHostConnectException) InetAddress(java.net.InetAddress) Future(java.util.concurrent.Future) AbstractConfiguration(org.eclipse.jetty.webapp.AbstractConfiguration) Configuration(org.eclipse.jetty.webapp.Configuration) BDDMockito.given(org.mockito.BDDMockito.given) Locale(java.util.Locale) QueuedThreadPool(org.eclipse.jetty.util.thread.QueuedThreadPool) Duration(java.time.Duration) Map(java.util.Map) PortInUseException(org.springframework.boot.web.server.PortInUseException) Method(java.lang.reflect.Method) Server(org.eclipse.jetty.server.Server) JspServlet(org.apache.jasper.servlet.JspServlet) Collection(java.util.Collection) ServletHolder(org.eclipse.jetty.servlet.ServletHolder) AbstractServletWebServerFactoryTests(org.springframework.boot.web.servlet.server.AbstractServletWebServerFactoryTests) ThreadPool(org.eclipse.jetty.util.thread.ThreadPool) Test(org.junit.jupiter.api.Test) EventListener(java.util.EventListener) Mockito.inOrder(org.mockito.Mockito.inOrder) ServletContextEvent(jakarta.servlet.ServletContextEvent) Awaitility(org.awaitility.Awaitility) HttpClients(org.apache.http.impl.client.HttpClients) ServletContextListener(jakarta.servlet.ServletContextListener) Mockito.mock(org.mockito.Mockito.mock) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) Handler(org.eclipse.jetty.server.Handler) SslContextFactory(org.eclipse.jetty.util.ssl.SslContextFactory) WebServerException(org.springframework.boot.web.server.WebServerException) Dynamic(jakarta.servlet.ServletRegistration.Dynamic) AtomicReference(java.util.concurrent.atomic.AtomicReference) Charset(java.nio.charset.Charset) Compression(org.springframework.boot.web.server.Compression) Shutdown(org.springframework.boot.web.server.Shutdown) HttpClient(org.apache.http.client.HttpClient) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) ErrorPageErrorHandler(org.eclipse.jetty.servlet.ErrorPageErrorHandler) InOrder(org.mockito.InOrder) HandlerWrapper(org.eclipse.jetty.server.handler.HandlerWrapper) GracefulShutdownResult(org.springframework.boot.web.server.GracefulShutdownResult) Ssl(org.springframework.boot.web.server.Ssl) ExecutionException(java.util.concurrent.ExecutionException) ServerConnector(org.eclipse.jetty.server.ServerConnector) ReflectionUtils(org.springframework.util.ReflectionUtils) AbstractServletWebServerFactory(org.springframework.boot.web.servlet.server.AbstractServletWebServerFactory) HttpResponse(org.apache.http.HttpResponse) Connector(org.eclipse.jetty.server.Connector) Collections(java.util.Collections) CapturedOutput(org.springframework.boot.testsupport.system.CapturedOutput) HandlerCollection(org.eclipse.jetty.server.handler.HandlerCollection) ServletContextListener(jakarta.servlet.ServletContextListener) WebServerException(org.springframework.boot.web.server.WebServerException) Method(java.lang.reflect.Method) WebAppContext(org.eclipse.jetty.webapp.WebAppContext) QueuedThreadPool(org.eclipse.jetty.util.thread.QueuedThreadPool) Collection(java.util.Collection) HandlerCollection(org.eclipse.jetty.server.handler.HandlerCollection) EventListener(java.util.EventListener) ServletContextEvent(jakarta.servlet.ServletContextEvent) Test(org.junit.jupiter.api.Test)

Example 10 with ServletContextEvent

use of jakarta.servlet.ServletContextEvent in project spring-boot by spring-projects.

the class SpringBootServletInitializerTests method whenServletContextIsDestroyedThenJdbcDriversAreDeregistered.

@Test
void whenServletContextIsDestroyedThenJdbcDriversAreDeregistered() throws ServletException {
    ServletContext servletContext = mock(ServletContext.class);
    given(servletContext.getInitParameterNames()).willReturn(new Vector<String>().elements());
    given(servletContext.getAttributeNames()).willReturn(new Vector<String>().elements());
    AtomicBoolean driversDeregistered = new AtomicBoolean();
    new SpringBootServletInitializer() {

        @Override
        protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
            return builder.sources(Config.class);
        }

        @Override
        protected void deregisterJdbcDrivers(ServletContext servletContext) {
            driversDeregistered.set(true);
        }
    }.onStartup(servletContext);
    ArgumentCaptor<ServletContextListener> captor = ArgumentCaptor.forClass(ServletContextListener.class);
    then(servletContext).should().addListener(captor.capture());
    captor.getValue().contextDestroyed(new ServletContextEvent(servletContext));
    assertThat(driversDeregistered).isTrue();
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ServletContextListener(jakarta.servlet.ServletContextListener) SpringApplicationBuilder(org.springframework.boot.builder.SpringApplicationBuilder) MockServletContext(org.springframework.mock.web.MockServletContext) ServletContext(jakarta.servlet.ServletContext) Vector(java.util.Vector) ServletContextEvent(jakarta.servlet.ServletContextEvent) Test(org.junit.jupiter.api.Test)

Aggregations

ServletContextEvent (jakarta.servlet.ServletContextEvent)28 Test (org.junit.jupiter.api.Test)25 MockServletContext (org.springframework.web.testfixture.servlet.MockServletContext)21 ServletContextListener (jakarta.servlet.ServletContextListener)10 XmlWebApplicationContext (org.springframework.web.context.support.XmlWebApplicationContext)8 SimpleWebApplicationContext (org.springframework.web.servlet.SimpleWebApplicationContext)8 TestBean (org.springframework.beans.testfixture.beans.TestBean)6 ContextLoaderListener (org.springframework.web.context.ContextLoaderListener)6 ServletContext (jakarta.servlet.ServletContext)3 SecurityConstraint (org.apache.tomcat.util.descriptor.web.SecurityConstraint)2 ServletContextAttributeListener (jakarta.servlet.ServletContextAttributeListener)1 Dynamic (jakarta.servlet.ServletRegistration.Dynamic)1 ServletRequestAttributeListener (jakarta.servlet.ServletRequestAttributeListener)1 ServletRequestListener (jakarta.servlet.ServletRequestListener)1 HttpSessionAttributeListener (jakarta.servlet.http.HttpSessionAttributeListener)1 HttpSessionIdListener (jakarta.servlet.http.HttpSessionIdListener)1 HttpSessionListener (jakarta.servlet.http.HttpSessionListener)1 IOException (java.io.IOException)1 Method (java.lang.reflect.Method)1 InetAddress (java.net.InetAddress)1