Search in sources :

Example 36 with ServletContext

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

the class AbstractServletWebServerFactoryTests method sessionConfiguration.

@Test
void sessionConfiguration() {
    AbstractServletWebServerFactory factory = getFactory();
    factory.getSession().setTimeout(Duration.ofSeconds(123));
    factory.getSession().setTrackingModes(EnumSet.of(SessionTrackingMode.COOKIE, SessionTrackingMode.URL));
    factory.getSession().getCookie().setName("testname");
    factory.getSession().getCookie().setDomain("testdomain");
    factory.getSession().getCookie().setPath("/testpath");
    factory.getSession().getCookie().setComment("testcomment");
    factory.getSession().getCookie().setHttpOnly(true);
    factory.getSession().getCookie().setSecure(true);
    factory.getSession().getCookie().setMaxAge(Duration.ofMinutes(1));
    AtomicReference<ServletContext> contextReference = new AtomicReference<>();
    factory.getWebServer(contextReference::set).start();
    ServletContext servletContext = contextReference.get();
    assertThat(servletContext.getEffectiveSessionTrackingModes()).isEqualTo(EnumSet.of(jakarta.servlet.SessionTrackingMode.COOKIE, jakarta.servlet.SessionTrackingMode.URL));
    assertThat(servletContext.getSessionCookieConfig().getName()).isEqualTo("testname");
    assertThat(servletContext.getSessionCookieConfig().getDomain()).isEqualTo("testdomain");
    assertThat(servletContext.getSessionCookieConfig().getPath()).isEqualTo("/testpath");
    assertThat(servletContext.getSessionCookieConfig().getComment()).isEqualTo("testcomment");
    assertThat(servletContext.getSessionCookieConfig().isHttpOnly()).isTrue();
    assertThat(servletContext.getSessionCookieConfig().isSecure()).isTrue();
    assertThat(servletContext.getSessionCookieConfig().getMaxAge()).isEqualTo(60);
}
Also used : ServletContext(jakarta.servlet.ServletContext) AtomicReference(java.util.concurrent.atomic.AtomicReference) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) Test(org.junit.jupiter.api.Test)

Example 37 with ServletContext

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

the class AbstractServletWebServerFactoryTests method servletContextListenerContextDestroyedIsCalledWhenContainerIsStopped.

@Test
void servletContextListenerContextDestroyedIsCalledWhenContainerIsStopped() throws Exception {
    ServletContextListener listener = mock(ServletContextListener.class);
    this.webServer = getFactory().getWebServer((servletContext) -> servletContext.addListener(listener));
    this.webServer.start();
    this.webServer.stop();
    then(listener).should().contextDestroyed(any(ServletContextEvent.class));
}
Also used : Arrays(java.util.Arrays) GZIPInputStream(java.util.zip.GZIPInputStream) SSLContext(javax.net.ssl.SSLContext) KeyStoreException(java.security.KeyStoreException) ServletException(jakarta.servlet.ServletException) Assertions.assertThatIOException(org.assertj.core.api.Assertions.assertThatIOException) InetAddress(java.net.InetAddress) ServerSocket(java.net.ServerSocket) HttpSession(jakarta.servlet.http.HttpSession) Future(java.util.concurrent.Future) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) BDDMockito.given(org.mockito.BDDMockito.given) Duration(java.time.Duration) Map(java.util.Map) PortInUseException(org.springframework.boot.web.server.PortInUseException) ClientAuth(org.springframework.boot.web.server.Ssl.ClientAuth) EnumSet(java.util.EnumSet) ServletContextInitializer(org.springframework.boot.web.servlet.ServletContextInitializer) Resource(org.springframework.core.io.Resource) PrintWriter(java.io.PrintWriter) ClassUtils(org.springframework.util.ClassUtils) ErrorPage(org.springframework.boot.web.server.ErrorPage) Mockito.atLeastOnce(org.mockito.Mockito.atLeastOnce) BlockingQueue(java.util.concurrent.BlockingQueue) StandardCharsets(java.nio.charset.StandardCharsets) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) SSLException(javax.net.ssl.SSLException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ServletContextEvent(jakarta.servlet.ServletContextEvent) Awaitility(org.awaitility.Awaitility) InputStreamFactory(org.apache.http.client.entity.InputStreamFactory) TrustSelfSignedStrategy(org.apache.http.conn.ssl.TrustSelfSignedStrategy) FileCopyUtils(org.springframework.util.FileCopyUtils) ServletContextListener(jakarta.servlet.ServletContextListener) Mockito.mock(org.mockito.Mockito.mock) Assertions.fail(org.junit.jupiter.api.Assertions.fail) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) HttpClientTransportOverHTTP2(org.eclipse.jetty.http2.client.http.HttpClientTransportOverHTTP2) WebServerException(org.springframework.boot.web.server.WebServerException) FutureTask(java.util.concurrent.FutureTask) SameSite(org.springframework.boot.web.server.Cookie.SameSite) Callable(java.util.concurrent.Callable) ApplicationTemp(org.springframework.boot.system.ApplicationTemp) Supplier(java.util.function.Supplier) WebServer(org.springframework.boot.web.server.WebServer) ClientHttpRequest(org.springframework.http.client.ClientHttpRequest) ThrowingCallable(org.assertj.core.api.ThrowableAssert.ThrowingCallable) HttpClient(org.apache.http.client.HttpClient) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) StandardHttpRequestRetryHandler(org.apache.http.impl.client.StandardHttpRequestRetryHandler) GenericServlet(jakarta.servlet.GenericServlet) HttpMethod(org.springframework.http.HttpMethod) IOException(java.io.IOException) BrokenBarrierException(java.util.concurrent.BrokenBarrierException) HttpServlet(jakarta.servlet.http.HttpServlet) SSLContextBuilder(org.apache.http.ssl.SSLContextBuilder) GracefulShutdownResult(org.springframework.boot.web.server.GracefulShutdownResult) Ssl(org.springframework.boot.web.server.Ssl) File(java.io.File) ExecutionException(java.util.concurrent.ExecutionException) HttpStatus(org.springframework.http.HttpStatus) Cookie(jakarta.servlet.http.Cookie) AfterEach(org.junit.jupiter.api.AfterEach) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) Assumptions(org.junit.jupiter.api.Assumptions) HttpContext(org.apache.http.protocol.HttpContext) Assertions.assertThatIllegalArgumentException(org.assertj.core.api.Assertions.assertThatIllegalArgumentException) HttpResponse(org.apache.http.HttpResponse) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) CapturedOutput(org.springframework.boot.testsupport.system.CapturedOutput) X509Certificate(java.security.cert.X509Certificate) FilterRegistrationBean(org.springframework.boot.web.servlet.FilterRegistrationBean) ExampleFilter(org.springframework.boot.testsupport.web.servlet.ExampleFilter) URL(java.net.URL) Date(java.util.Date) URISyntaxException(java.net.URISyntaxException) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) HTTP2Client(org.eclipse.jetty.http2.client.HTTP2Client) ExampleServlet(org.springframework.boot.testsupport.web.servlet.ExampleServlet) Filter(jakarta.servlet.Filter) FilterConfig(jakarta.servlet.FilterConfig) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) Locale(java.util.Locale) DefaultHttpRequestRetryHandler(org.apache.http.impl.client.DefaultHttpRequestRetryHandler) URI(java.net.URI) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) JspServlet(org.apache.jasper.servlet.JspServlet) MimeMappings(org.springframework.boot.web.server.MimeMappings) ServletRequest(jakarta.servlet.ServletRequest) Collection(java.util.Collection) Http2(org.springframework.boot.web.server.Http2) FileSystemResource(org.springframework.core.io.FileSystemResource) KeyStore(java.security.KeyStore) Objects(java.util.Objects) Test(org.junit.jupiter.api.Test) List(java.util.List) HttpGet(org.apache.http.client.methods.HttpGet) ApplicationHome(org.springframework.boot.system.ApplicationHome) TempDir(org.junit.jupiter.api.io.TempDir) Mockito.inOrder(org.mockito.Mockito.inOrder) ServletResponse(jakarta.servlet.ServletResponse) ServletContext(jakarta.servlet.ServletContext) HttpClients(org.apache.http.impl.client.HttpClients) AsyncContext(jakarta.servlet.AsyncContext) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) TrustStrategy(org.apache.http.ssl.TrustStrategy) SessionCookieConfig(jakarta.servlet.SessionCookieConfig) ClassPathResource(org.springframework.core.io.ClassPathResource) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) Dynamic(jakarta.servlet.ServletRegistration.Dynamic) EnumSource(org.junit.jupiter.params.provider.EnumSource) AtomicReference(java.util.concurrent.atomic.AtomicReference) EmbeddedServletOptions(org.apache.jasper.EmbeddedServletOptions) SessionTrackingMode(org.springframework.boot.web.servlet.server.Session.SessionTrackingMode) Charset(java.nio.charset.Charset) OutputCaptureExtension(org.springframework.boot.testsupport.system.OutputCaptureExtension) Compression(org.springframework.boot.web.server.Compression) Shutdown(org.springframework.boot.web.server.Shutdown) Assertions.assertThatThrownBy(org.assertj.core.api.Assertions.assertThatThrownBy) TomcatURLStreamHandlerFactory(org.apache.catalina.webresources.TomcatURLStreamHandlerFactory) ServletRegistrationBean(org.springframework.boot.web.servlet.ServletRegistrationBean) ClientHttpResponse(org.springframework.http.client.ClientHttpResponse) RunnableFuture(java.util.concurrent.RunnableFuture) StreamUtils(org.springframework.util.StreamUtils) Assertions.assertThatIllegalStateException(org.assertj.core.api.Assertions.assertThatIllegalStateException) InOrder(org.mockito.InOrder) MalformedURLException(java.net.MalformedURLException) FileWriter(java.io.FileWriter) FilterChain(jakarta.servlet.FilterChain) ReflectionTestUtils(org.springframework.test.util.ReflectionTestUtils) BDDMockito.then(org.mockito.BDDMockito.then) CertificateException(java.security.cert.CertificateException) HttpComponentsClientHttpRequestFactory(org.springframework.http.client.HttpComponentsClientHttpRequestFactory) SslStoreProvider(org.springframework.boot.web.server.SslStoreProvider) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) Collections(java.util.Collections) InputStream(java.io.InputStream) ServletContextListener(jakarta.servlet.ServletContextListener) ServletContextEvent(jakarta.servlet.ServletContextEvent) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) Test(org.junit.jupiter.api.Test)

Example 38 with ServletContext

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

the class ServletWebServerApplicationContextTests method multipleServletBeansWithMainDispatcher.

@Test
void multipleServletBeansWithMainDispatcher() {
    addWebServerFactoryBean();
    Servlet servlet1 = mock(Servlet.class, withSettings().extraInterfaces(Ordered.class));
    given(((Ordered) servlet1).getOrder()).willReturn(1);
    Servlet servlet2 = mock(Servlet.class, withSettings().extraInterfaces(Ordered.class));
    given(((Ordered) servlet2).getOrder()).willReturn(2);
    this.context.registerBeanDefinition("servletBean2", beanDefinition(servlet2));
    this.context.registerBeanDefinition("dispatcherServlet", beanDefinition(servlet1));
    this.context.refresh();
    MockServletWebServerFactory factory = getWebServerFactory();
    ServletContext servletContext = factory.getServletContext();
    InOrder ordered = inOrder(servletContext);
    then(servletContext).should(ordered).addServlet("dispatcherServlet", servlet1);
    then(servletContext).should(ordered).addServlet("servletBean2", servlet2);
    then(factory.getRegisteredServlet(0).getRegistration()).should().addMapping("/");
    then(factory.getRegisteredServlet(1).getRegistration()).should().addMapping("/servletBean2/");
}
Also used : MockServletWebServerFactory(org.springframework.boot.web.servlet.server.MockServletWebServerFactory) InOrder(org.mockito.InOrder) Ordered(org.springframework.core.Ordered) Servlet(jakarta.servlet.Servlet) ServletContext(jakarta.servlet.ServletContext) Test(org.junit.jupiter.api.Test)

Example 39 with ServletContext

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

the class ServletWebServerApplicationContextTests method servletContextInitializerBeansSkipsRegisteredServletsAndFilters.

@Test
void servletContextInitializerBeansSkipsRegisteredServletsAndFilters() {
    addWebServerFactoryBean();
    Servlet servlet = mock(Servlet.class);
    Filter filter = mock(Filter.class);
    ServletRegistrationBean<Servlet> initializer = new ServletRegistrationBean<>(servlet, "/foo");
    this.context.registerBeanDefinition("initializerBean", beanDefinition(initializer));
    this.context.registerBeanDefinition("servletBean", beanDefinition(servlet));
    this.context.registerBeanDefinition("filterBean", beanDefinition(filter));
    this.context.refresh();
    ServletContext servletContext = getWebServerFactory().getServletContext();
    then(servletContext).should(atMost(1)).addServlet(anyString(), any(Servlet.class));
    then(servletContext).should(atMost(1)).addFilter(anyString(), any(Filter.class));
}
Also used : Filter(jakarta.servlet.Filter) ServletRegistrationBean(org.springframework.boot.web.servlet.ServletRegistrationBean) Servlet(jakarta.servlet.Servlet) ServletContext(jakarta.servlet.ServletContext) Test(org.junit.jupiter.api.Test)

Example 40 with ServletContext

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

the class ServletWebServerApplicationContextTests method multipleServletBeans.

@Test
void multipleServletBeans() {
    addWebServerFactoryBean();
    Servlet servlet1 = mock(Servlet.class, withSettings().extraInterfaces(Ordered.class));
    given(((Ordered) servlet1).getOrder()).willReturn(1);
    Servlet servlet2 = mock(Servlet.class, withSettings().extraInterfaces(Ordered.class));
    given(((Ordered) servlet2).getOrder()).willReturn(2);
    this.context.registerBeanDefinition("servletBean2", beanDefinition(servlet2));
    this.context.registerBeanDefinition("servletBean1", beanDefinition(servlet1));
    this.context.refresh();
    MockServletWebServerFactory factory = getWebServerFactory();
    ServletContext servletContext = factory.getServletContext();
    InOrder ordered = inOrder(servletContext);
    then(servletContext).should(ordered).addServlet("servletBean1", servlet1);
    then(servletContext).should(ordered).addServlet("servletBean2", servlet2);
    then(factory.getRegisteredServlet(0).getRegistration()).should().addMapping("/servletBean1/");
    then(factory.getRegisteredServlet(1).getRegistration()).should().addMapping("/servletBean2/");
}
Also used : MockServletWebServerFactory(org.springframework.boot.web.servlet.server.MockServletWebServerFactory) InOrder(org.mockito.InOrder) Ordered(org.springframework.core.Ordered) Servlet(jakarta.servlet.Servlet) ServletContext(jakarta.servlet.ServletContext) Test(org.junit.jupiter.api.Test)

Aggregations

ServletContext (jakarta.servlet.ServletContext)148 Test (org.junit.jupiter.api.Test)63 ServletConfig (jakarta.servlet.ServletConfig)40 Enumeration (java.util.Enumeration)29 MockServletContext (org.springframework.web.testfixture.servlet.MockServletContext)24 BeforeMethod (org.testng.annotations.BeforeMethod)22 IOException (java.io.IOException)20 ServletException (jakarta.servlet.ServletException)17 FilterRegistration (jakarta.servlet.FilterRegistration)16 DelegatingFilterProxy (org.springframework.web.filter.DelegatingFilterProxy)15 Filter (jakarta.servlet.Filter)13 Test (org.junit.Test)13 ServletContextAwareProcessor (org.springframework.web.context.support.ServletContextAwareProcessor)12 MockHttpServletRequest (org.springframework.web.testfixture.servlet.MockHttpServletRequest)12 MockHttpServletResponse (org.springframework.web.testfixture.servlet.MockHttpServletResponse)12 StaticWebApplicationContext (org.springframework.web.context.support.StaticWebApplicationContext)11 WebApplicationContext (org.springframework.web.context.WebApplicationContext)9 File (java.io.File)8 Context (org.apache.catalina.Context)7 BlockingIOCometSupport (org.atmosphere.container.BlockingIOCometSupport)7