Search in sources :

Example 1 with Dynamic

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

the class ServletEndpointRegistrar method register.

private void register(ServletContext servletContext, ExposableServletEndpoint endpoint) {
    String name = endpoint.getEndpointId().toLowerCaseString() + "-actuator-endpoint";
    String path = this.basePath + "/" + endpoint.getRootPath();
    String urlMapping = path.endsWith("/") ? path + "*" : path + "/*";
    EndpointServlet endpointServlet = endpoint.getEndpointServlet();
    Dynamic registration = servletContext.addServlet(name, endpointServlet.getServlet());
    registration.addMapping(urlMapping);
    registration.setInitParameters(endpointServlet.getInitParameters());
    registration.setLoadOnStartup(endpointServlet.getLoadOnStartup());
    logger.info("Registered '" + path + "' to " + name);
}
Also used : Dynamic(jakarta.servlet.ServletRegistration.Dynamic)

Example 2 with Dynamic

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

the class JettyServletWebServerFactoryTests method whenServerIsShuttingDownGracefullyThenNewConnectionsCannotBeMade.

@Test
void whenServerIsShuttingDownGracefullyThenNewConnectionsCannotBeMade() throws Exception {
    AbstractServletWebServerFactory factory = getFactory();
    factory.setShutdown(Shutdown.GRACEFUL);
    BlockingServlet blockingServlet = new BlockingServlet();
    this.webServer = factory.getWebServer((context) -> {
        Dynamic registration = context.addServlet("blockingServlet", blockingServlet);
        registration.addMapping("/blocking");
        registration.setAsyncSupported(true);
    });
    this.webServer.start();
    int port = this.webServer.getPort();
    Future<Object> request = initiateGetRequest(port, "/blocking");
    blockingServlet.awaitQueue();
    this.webServer.shutDownGracefully((result) -> {
    });
    Future<Object> unconnectableRequest = initiateGetRequest(port, "/");
    blockingServlet.admitOne();
    Object response = request.get();
    assertThat(response).isInstanceOf(HttpResponse.class);
    assertThat(unconnectableRequest.get()).isInstanceOf(HttpHostConnectException.class);
    this.webServer.stop();
}
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) Dynamic(jakarta.servlet.ServletRegistration.Dynamic) AbstractServletWebServerFactory(org.springframework.boot.web.servlet.server.AbstractServletWebServerFactory) Test(org.junit.jupiter.api.Test)

Example 3 with Dynamic

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

the class TomcatServletWebServerFactoryTests method whenServerIsShuttingDownGracefullyThenNewConnectionsCannotBeMade.

@Test
void whenServerIsShuttingDownGracefullyThenNewConnectionsCannotBeMade() throws Exception {
    AbstractServletWebServerFactory factory = getFactory();
    factory.setShutdown(Shutdown.GRACEFUL);
    BlockingServlet blockingServlet = new BlockingServlet();
    this.webServer = factory.getWebServer((context) -> {
        Dynamic registration = context.addServlet("blockingServlet", blockingServlet);
        registration.addMapping("/blocking");
        registration.setAsyncSupported(true);
    });
    this.webServer.start();
    int port = this.webServer.getPort();
    Future<Object> request = initiateGetRequest(port, "/blocking");
    blockingServlet.awaitQueue();
    this.webServer.shutDownGracefully((result) -> {
    });
    Object unconnectableRequest = Awaitility.await().until(() -> initiateGetRequest(HttpClients.createDefault(), port, "/").get(), (result) -> result instanceof Exception);
    assertThat(unconnectableRequest).isInstanceOf(HttpHostConnectException.class);
    blockingServlet.admitOne();
    assertThat(request.get()).isInstanceOf(HttpResponse.class);
    this.webServer.stop();
}
Also used : Arrays(java.util.Arrays) URISyntaxException(java.net.URISyntaxException) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) NoHttpResponseException(org.apache.http.NoHttpResponseException) NamingException(javax.naming.NamingException) ServletException(jakarta.servlet.ServletException) LifecycleListener(org.apache.catalina.LifecycleListener) ByteArrayResource(org.springframework.core.io.ByteArrayResource) HttpHostConnectException(org.apache.http.conn.HttpHostConnectException) Future(java.util.concurrent.Future) Locale(java.util.Locale) Duration(java.time.Duration) Map(java.util.Map) LifecycleState(org.apache.catalina.LifecycleState) PortInUseException(org.springframework.boot.web.server.PortInUseException) RestTemplate(org.springframework.web.client.RestTemplate) AprLifecycleListener(org.apache.catalina.core.AprLifecycleListener) InitialContext(javax.naming.InitialContext) JspServlet(org.apache.jasper.servlet.JspServlet) HttpHeaders(org.springframework.http.HttpHeaders) MediaType(org.springframework.http.MediaType) SessionIdGenerator(org.apache.catalina.SessionIdGenerator) AbstractServletWebServerFactoryTests(org.springframework.boot.web.servlet.server.AbstractServletWebServerFactoryTests) FileSystemUtils(org.springframework.util.FileSystemUtils) StandardCharsets(java.nio.charset.StandardCharsets) Test(org.junit.jupiter.api.Test) HttpEntity(org.springframework.http.HttpEntity) JarScanFilter(org.apache.tomcat.JarScanFilter) Mockito.inOrder(org.mockito.Mockito.inOrder) ServletContext(jakarta.servlet.ServletContext) StandardContext(org.apache.catalina.core.StandardContext) Awaitility(org.awaitility.Awaitility) HttpClients(org.apache.http.impl.client.HttpClients) Mockito.mock(org.mockito.Mockito.mock) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) LifecycleEvent(org.apache.catalina.LifecycleEvent) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) WebServerException(org.springframework.boot.web.server.WebServerException) Valve(org.apache.catalina.Valve) AbstractHttp11Protocol(org.apache.coyote.http11.AbstractHttp11Protocol) HashMap(java.util.HashMap) Dynamic(jakarta.servlet.ServletRegistration.Dynamic) Connector(org.apache.catalina.connector.Connector) AtomicReference(java.util.concurrent.atomic.AtomicReference) SocketException(java.net.SocketException) CharsetMapper(org.apache.catalina.util.CharsetMapper) ThrowingCallable(org.assertj.core.api.ThrowableAssert.ThrowingCallable) ArgumentCaptor(org.mockito.ArgumentCaptor) Charset(java.nio.charset.Charset) Shutdown(org.springframework.boot.web.server.Shutdown) HttpClient(org.apache.http.client.HttpClient) StandardJarScanFilter(org.apache.tomcat.util.scan.StandardJarScanFilter) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) Service(org.apache.catalina.Service) RemoteIpValve(org.apache.catalina.valves.RemoteIpValve) InOrder(org.mockito.InOrder) JarScanType(org.apache.tomcat.JarScanType) MultiValueMap(org.springframework.util.MultiValueMap) BDDMockito.then(org.mockito.BDDMockito.then) IOException(java.io.IOException) Context(org.apache.catalina.Context) HttpServlet(jakarta.servlet.http.HttpServlet) File(java.io.File) MultipartConfigElement(jakarta.servlet.MultipartConfigElement) Tomcat(org.apache.catalina.startup.Tomcat) HttpStatus(org.springframework.http.HttpStatus) AfterEach(org.junit.jupiter.api.AfterEach) Container(org.apache.catalina.Container) ProtocolHandler(org.apache.coyote.ProtocolHandler) AbstractServletWebServerFactory(org.springframework.boot.web.servlet.server.AbstractServletWebServerFactory) Assertions.assertThatIllegalArgumentException(org.assertj.core.api.Assertions.assertThatIllegalArgumentException) HttpResponse(org.apache.http.HttpResponse) StandardWrapper(org.apache.catalina.core.StandardWrapper) ResponseEntity(org.springframework.http.ResponseEntity) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) CapturedOutput(org.springframework.boot.testsupport.system.CapturedOutput) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) Dynamic(jakarta.servlet.ServletRegistration.Dynamic) AbstractServletWebServerFactory(org.springframework.boot.web.servlet.server.AbstractServletWebServerFactory) URISyntaxException(java.net.URISyntaxException) NoHttpResponseException(org.apache.http.NoHttpResponseException) NamingException(javax.naming.NamingException) ServletException(jakarta.servlet.ServletException) HttpHostConnectException(org.apache.http.conn.HttpHostConnectException) PortInUseException(org.springframework.boot.web.server.PortInUseException) WebServerException(org.springframework.boot.web.server.WebServerException) SocketException(java.net.SocketException) IOException(java.io.IOException) Assertions.assertThatIllegalArgumentException(org.assertj.core.api.Assertions.assertThatIllegalArgumentException) Test(org.junit.jupiter.api.Test)

Example 4 with Dynamic

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

the class TomcatServletWebServerFactoryTests method nonExistentUploadDirectoryIsCreatedUponMultipartUpload.

@Test
void nonExistentUploadDirectoryIsCreatedUponMultipartUpload() throws IOException, URISyntaxException {
    TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory(0);
    AtomicReference<ServletContext> servletContextReference = new AtomicReference<>();
    factory.addInitializers((servletContext) -> {
        servletContextReference.set(servletContext);
        Dynamic servlet = servletContext.addServlet("upload", new HttpServlet() {

            @Override
            protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
                req.getParts();
            }
        });
        servlet.addMapping("/upload");
        servlet.setMultipartConfig(new MultipartConfigElement((String) null));
    });
    this.webServer = factory.getWebServer();
    this.webServer.start();
    File temp = (File) servletContextReference.get().getAttribute(ServletContext.TEMPDIR);
    FileSystemUtils.deleteRecursively(temp);
    RestTemplate restTemplate = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
    body.add("file", new ByteArrayResource(new byte[1024 * 1024]));
    headers.setContentType(MediaType.MULTIPART_FORM_DATA);
    HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
    ResponseEntity<String> response = restTemplate.postForEntity(getLocalUrl("/upload"), requestEntity, String.class);
    assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) Dynamic(jakarta.servlet.ServletRegistration.Dynamic) HttpEntity(org.springframework.http.HttpEntity) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) HttpServlet(jakarta.servlet.http.HttpServlet) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException) ByteArrayResource(org.springframework.core.io.ByteArrayResource) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) ServletException(jakarta.servlet.ServletException) MultipartConfigElement(jakarta.servlet.MultipartConfigElement) RestTemplate(org.springframework.web.client.RestTemplate) ServletContext(jakarta.servlet.ServletContext) File(java.io.File) MultiValueMap(org.springframework.util.MultiValueMap) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) Test(org.junit.jupiter.api.Test)

Example 5 with Dynamic

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

the class TomcatServletWebServerFactoryTests method whenServerIsShuttingDownARequestOnAnIdleConnectionResultsInConnectionReset.

@Test
void whenServerIsShuttingDownARequestOnAnIdleConnectionResultsInConnectionReset() throws Exception {
    AbstractServletWebServerFactory factory = getFactory();
    factory.setShutdown(Shutdown.GRACEFUL);
    BlockingServlet blockingServlet = new BlockingServlet();
    this.webServer = factory.getWebServer((context) -> {
        Dynamic registration = context.addServlet("blockingServlet", blockingServlet);
        registration.addMapping("/blocking");
        registration.setAsyncSupported(true);
    });
    HttpClient httpClient = HttpClients.createMinimal();
    this.webServer.start();
    int port = this.webServer.getPort();
    Future<Object> keepAliveRequest = initiateGetRequest(httpClient, port, "/blocking");
    blockingServlet.awaitQueue();
    blockingServlet.admitOne();
    assertThat(keepAliveRequest.get()).isInstanceOf(HttpResponse.class);
    Future<Object> request = initiateGetRequest(port, "/blocking");
    blockingServlet.awaitQueue();
    this.webServer.shutDownGracefully((result) -> {
    });
    Object idleConnectionRequestResult = Awaitility.await().until(() -> {
        Future<Object> idleConnectionRequest = initiateGetRequest(httpClient, port, "/");
        Object result = idleConnectionRequest.get();
        return result;
    }, (result) -> result instanceof Exception);
    assertThat(idleConnectionRequestResult).isInstanceOfAny(SocketException.class, NoHttpResponseException.class);
    if (idleConnectionRequestResult instanceof SocketException) {
        assertThat((SocketException) idleConnectionRequestResult).hasMessage("Connection reset");
    }
    blockingServlet.admitOne();
    Object response = request.get();
    assertThat(response).isInstanceOf(HttpResponse.class);
    this.webServer.stop();
}
Also used : Arrays(java.util.Arrays) URISyntaxException(java.net.URISyntaxException) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) NoHttpResponseException(org.apache.http.NoHttpResponseException) NamingException(javax.naming.NamingException) ServletException(jakarta.servlet.ServletException) LifecycleListener(org.apache.catalina.LifecycleListener) ByteArrayResource(org.springframework.core.io.ByteArrayResource) HttpHostConnectException(org.apache.http.conn.HttpHostConnectException) Future(java.util.concurrent.Future) Locale(java.util.Locale) Duration(java.time.Duration) Map(java.util.Map) LifecycleState(org.apache.catalina.LifecycleState) PortInUseException(org.springframework.boot.web.server.PortInUseException) RestTemplate(org.springframework.web.client.RestTemplate) AprLifecycleListener(org.apache.catalina.core.AprLifecycleListener) InitialContext(javax.naming.InitialContext) JspServlet(org.apache.jasper.servlet.JspServlet) HttpHeaders(org.springframework.http.HttpHeaders) MediaType(org.springframework.http.MediaType) SessionIdGenerator(org.apache.catalina.SessionIdGenerator) AbstractServletWebServerFactoryTests(org.springframework.boot.web.servlet.server.AbstractServletWebServerFactoryTests) FileSystemUtils(org.springframework.util.FileSystemUtils) StandardCharsets(java.nio.charset.StandardCharsets) Test(org.junit.jupiter.api.Test) HttpEntity(org.springframework.http.HttpEntity) JarScanFilter(org.apache.tomcat.JarScanFilter) Mockito.inOrder(org.mockito.Mockito.inOrder) ServletContext(jakarta.servlet.ServletContext) StandardContext(org.apache.catalina.core.StandardContext) Awaitility(org.awaitility.Awaitility) HttpClients(org.apache.http.impl.client.HttpClients) Mockito.mock(org.mockito.Mockito.mock) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) LifecycleEvent(org.apache.catalina.LifecycleEvent) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) WebServerException(org.springframework.boot.web.server.WebServerException) Valve(org.apache.catalina.Valve) AbstractHttp11Protocol(org.apache.coyote.http11.AbstractHttp11Protocol) HashMap(java.util.HashMap) Dynamic(jakarta.servlet.ServletRegistration.Dynamic) Connector(org.apache.catalina.connector.Connector) AtomicReference(java.util.concurrent.atomic.AtomicReference) SocketException(java.net.SocketException) CharsetMapper(org.apache.catalina.util.CharsetMapper) ThrowingCallable(org.assertj.core.api.ThrowableAssert.ThrowingCallable) ArgumentCaptor(org.mockito.ArgumentCaptor) Charset(java.nio.charset.Charset) Shutdown(org.springframework.boot.web.server.Shutdown) HttpClient(org.apache.http.client.HttpClient) StandardJarScanFilter(org.apache.tomcat.util.scan.StandardJarScanFilter) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) Service(org.apache.catalina.Service) RemoteIpValve(org.apache.catalina.valves.RemoteIpValve) InOrder(org.mockito.InOrder) JarScanType(org.apache.tomcat.JarScanType) MultiValueMap(org.springframework.util.MultiValueMap) BDDMockito.then(org.mockito.BDDMockito.then) IOException(java.io.IOException) Context(org.apache.catalina.Context) HttpServlet(jakarta.servlet.http.HttpServlet) File(java.io.File) MultipartConfigElement(jakarta.servlet.MultipartConfigElement) Tomcat(org.apache.catalina.startup.Tomcat) HttpStatus(org.springframework.http.HttpStatus) AfterEach(org.junit.jupiter.api.AfterEach) Container(org.apache.catalina.Container) ProtocolHandler(org.apache.coyote.ProtocolHandler) AbstractServletWebServerFactory(org.springframework.boot.web.servlet.server.AbstractServletWebServerFactory) Assertions.assertThatIllegalArgumentException(org.assertj.core.api.Assertions.assertThatIllegalArgumentException) HttpResponse(org.apache.http.HttpResponse) StandardWrapper(org.apache.catalina.core.StandardWrapper) ResponseEntity(org.springframework.http.ResponseEntity) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) CapturedOutput(org.springframework.boot.testsupport.system.CapturedOutput) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) SocketException(java.net.SocketException) Dynamic(jakarta.servlet.ServletRegistration.Dynamic) AbstractServletWebServerFactory(org.springframework.boot.web.servlet.server.AbstractServletWebServerFactory) HttpClient(org.apache.http.client.HttpClient) URISyntaxException(java.net.URISyntaxException) NoHttpResponseException(org.apache.http.NoHttpResponseException) NamingException(javax.naming.NamingException) ServletException(jakarta.servlet.ServletException) HttpHostConnectException(org.apache.http.conn.HttpHostConnectException) PortInUseException(org.springframework.boot.web.server.PortInUseException) WebServerException(org.springframework.boot.web.server.WebServerException) SocketException(java.net.SocketException) IOException(java.io.IOException) Assertions.assertThatIllegalArgumentException(org.assertj.core.api.Assertions.assertThatIllegalArgumentException) Test(org.junit.jupiter.api.Test)

Aggregations

Dynamic (jakarta.servlet.ServletRegistration.Dynamic)8 AtomicReference (java.util.concurrent.atomic.AtomicReference)7 Test (org.junit.jupiter.api.Test)7 Charset (java.nio.charset.Charset)6 Duration (java.time.Duration)6 Arrays (java.util.Arrays)6 Locale (java.util.Locale)6 Map (java.util.Map)6 Future (java.util.concurrent.Future)6 HttpResponse (org.apache.http.HttpResponse)6 JspServlet (org.apache.jasper.servlet.JspServlet)6 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)6 Awaitility (org.awaitility.Awaitility)6 ArgumentMatchers.any (org.mockito.ArgumentMatchers.any)6 InOrder (org.mockito.InOrder)6 Mockito.inOrder (org.mockito.Mockito.inOrder)6 Mockito.mock (org.mockito.Mockito.mock)6 PortInUseException (org.springframework.boot.web.server.PortInUseException)6 Shutdown (org.springframework.boot.web.server.Shutdown)6 AbstractServletWebServerFactory (org.springframework.boot.web.servlet.server.AbstractServletWebServerFactory)6