Search in sources :

Example 36 with ServletException

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

the class ServerPropertiesTests method jettyMaxHttpFormPostSizeMatchesDefault.

@Test
void jettyMaxHttpFormPostSizeMatchesDefault() {
    JettyServletWebServerFactory jettyFactory = new JettyServletWebServerFactory(0);
    JettyWebServer jetty = (JettyWebServer) jettyFactory.getWebServer((ServletContextInitializer) (servletContext) -> servletContext.addServlet("formPost", new HttpServlet() {

        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            req.getParameterMap();
        }
    }).addMapping("/form"));
    jetty.start();
    org.eclipse.jetty.server.Connector connector = jetty.getServer().getConnectors()[0];
    final AtomicReference<Throwable> failure = new AtomicReference<>();
    connector.addBean(new HttpChannel.Listener() {

        @Override
        public void onDispatchFailure(Request request, Throwable ex) {
            failure.set(ex);
        }
    });
    try {
        RestTemplate template = new RestTemplate();
        template.setErrorHandler(new ResponseErrorHandler() {

            @Override
            public boolean hasError(ClientHttpResponse response) throws IOException {
                return false;
            }

            @Override
            public void handleError(ClientHttpResponse response) throws IOException {
            }
        });
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        StringBuilder data = new StringBuilder();
        for (int i = 0; i < 250000; i++) {
            data.append("a");
        }
        body.add("data", data.toString());
        HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(body, headers);
        template.postForEntity(URI.create("http://localhost:" + jetty.getPort() + "/form"), entity, Void.class);
        assertThat(failure.get()).isNotNull();
        String message = failure.get().getCause().getMessage();
        int defaultMaxPostSize = Integer.parseInt(message.substring(message.lastIndexOf(' ')).trim());
        assertThat(this.properties.getJetty().getMaxHttpFormPostSize().toBytes()).isEqualTo(defaultMaxPostSize);
    } finally {
        jetty.stop();
    }
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) HttpEntity(org.springframework.http.HttpEntity) ResponseErrorHandler(org.springframework.web.client.ResponseErrorHandler) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) ServletException(jakarta.servlet.ServletException) HttpChannel(org.eclipse.jetty.server.HttpChannel) ServletContextInitializer(org.springframework.boot.web.servlet.ServletContextInitializer) MultiValueMap(org.springframework.util.MultiValueMap) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) JettyWebServer(org.springframework.boot.web.embedded.jetty.JettyWebServer) HttpServlet(jakarta.servlet.http.HttpServlet) Request(org.eclipse.jetty.server.Request) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException) AbstractEndpoint(org.apache.tomcat.util.net.AbstractEndpoint) JettyServletWebServerFactory(org.springframework.boot.web.embedded.jetty.JettyServletWebServerFactory) RestTemplate(org.springframework.web.client.RestTemplate) ClientHttpResponse(org.springframework.http.client.ClientHttpResponse) Test(org.junit.jupiter.api.Test)

Example 37 with ServletException

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

the class ServletWebServerApplicationContext method createWebServer.

private void createWebServer() {
    WebServer webServer = this.webServer;
    ServletContext servletContext = getServletContext();
    if (webServer == null && servletContext == null) {
        StartupStep createWebServer = this.getApplicationStartup().start("spring.boot.webserver.create");
        ServletWebServerFactory factory = getWebServerFactory();
        createWebServer.tag("factory", factory.getClass().toString());
        this.webServer = factory.getWebServer(getSelfInitializer());
        createWebServer.end();
        getBeanFactory().registerSingleton("webServerGracefulShutdown", new WebServerGracefulShutdownLifecycle(this.webServer));
        getBeanFactory().registerSingleton("webServerStartStop", new WebServerStartStopLifecycle(this, this.webServer));
    } else if (servletContext != null) {
        try {
            getSelfInitializer().onStartup(servletContext);
        } catch (ServletException ex) {
            throw new ApplicationContextException("Cannot initialize servlet context", ex);
        }
    }
    initPropertySources();
}
Also used : ServletException(jakarta.servlet.ServletException) ServletWebServerFactory(org.springframework.boot.web.servlet.server.ServletWebServerFactory) WebServer(org.springframework.boot.web.server.WebServer) StartupStep(org.springframework.core.metrics.StartupStep) WebServerGracefulShutdownLifecycle(org.springframework.boot.web.context.WebServerGracefulShutdownLifecycle) ServletContext(jakarta.servlet.ServletContext) ApplicationContextException(org.springframework.context.ApplicationContextException)

Example 38 with ServletException

use of jakarta.servlet.ServletException in project tomcat by apache.

the class ApplicationFilterChain method doFilter.

// ---------------------------------------------------- FilterChain Methods
/**
 * Invoke the next filter in this chain, passing the specified request
 * and response.  If there are no more filters in this chain, invoke
 * the <code>service()</code> method of the servlet itself.
 *
 * @param request The servlet request we are processing
 * @param response The servlet response we are creating
 *
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet exception occurs
 */
@Override
public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException {
    if (Globals.IS_SECURITY_ENABLED) {
        final ServletRequest req = request;
        final ServletResponse res = response;
        try {
            java.security.AccessController.doPrivileged((java.security.PrivilegedExceptionAction<Void>) () -> {
                internalDoFilter(req, res);
                return null;
            });
        } catch (PrivilegedActionException pe) {
            Exception e = pe.getException();
            if (e instanceof ServletException) {
                throw (ServletException) e;
            } else if (e instanceof IOException) {
                throw (IOException) e;
            } else if (e instanceof RuntimeException) {
                throw (RuntimeException) e;
            } else {
                throw new ServletException(e.getMessage(), e);
            }
        }
    } else {
        internalDoFilter(request, response);
    }
}
Also used : ServletException(jakarta.servlet.ServletException) ServletRequest(jakarta.servlet.ServletRequest) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) ServletResponse(jakarta.servlet.ServletResponse) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) PrivilegedActionException(java.security.PrivilegedActionException) IOException(java.io.IOException) PrivilegedActionException(java.security.PrivilegedActionException) IOException(java.io.IOException) ServletException(jakarta.servlet.ServletException)

Example 39 with ServletException

use of jakarta.servlet.ServletException in project tomcat by apache.

the class ApplicationFilterChain method internalDoFilter.

private void internalDoFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException {
    // Call the next filter if there is one
    if (pos < n) {
        ApplicationFilterConfig filterConfig = filters[pos++];
        try {
            Filter filter = filterConfig.getFilter();
            if (request.isAsyncSupported() && "false".equalsIgnoreCase(filterConfig.getFilterDef().getAsyncSupported())) {
                request.setAttribute(Globals.ASYNC_SUPPORTED_ATTR, Boolean.FALSE);
            }
            if (Globals.IS_SECURITY_ENABLED) {
                final ServletRequest req = request;
                final ServletResponse res = response;
                Principal principal = ((HttpServletRequest) req).getUserPrincipal();
                Object[] args = new Object[] { req, res, this };
                SecurityUtil.doAsPrivilege("doFilter", filter, classType, args, principal);
            } else {
                filter.doFilter(request, response, this);
            }
        } catch (IOException | ServletException | RuntimeException e) {
            throw e;
        } catch (Throwable e) {
            e = ExceptionUtils.unwrapInvocationTargetException(e);
            ExceptionUtils.handleThrowable(e);
            throw new ServletException(sm.getString("filterChain.filter"), e);
        }
        return;
    }
    // We fell off the end of the chain -- call the servlet instance
    try {
        if (dispatcherWrapsSameObject) {
            lastServicedRequest.set(request);
            lastServicedResponse.set(response);
        }
        if (request.isAsyncSupported() && !servletSupportsAsync) {
            request.setAttribute(Globals.ASYNC_SUPPORTED_ATTR, Boolean.FALSE);
        }
        // Use potentially wrapped request from this point
        if ((request instanceof HttpServletRequest) && (response instanceof HttpServletResponse) && Globals.IS_SECURITY_ENABLED) {
            final ServletRequest req = request;
            final ServletResponse res = response;
            Principal principal = ((HttpServletRequest) req).getUserPrincipal();
            Object[] args = new Object[] { req, res };
            SecurityUtil.doAsPrivilege("service", servlet, classTypeUsedInService, args, principal);
        } else {
            servlet.service(request, response);
        }
    } catch (IOException | ServletException | RuntimeException e) {
        throw e;
    } catch (Throwable e) {
        e = ExceptionUtils.unwrapInvocationTargetException(e);
        ExceptionUtils.handleThrowable(e);
        throw new ServletException(sm.getString("filterChain.servlet"), e);
    } finally {
        if (dispatcherWrapsSameObject) {
            lastServicedRequest.set(null);
            lastServicedResponse.set(null);
        }
    }
}
Also used : ServletRequest(jakarta.servlet.ServletRequest) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) ServletResponse(jakarta.servlet.ServletResponse) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) IOException(java.io.IOException) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) ServletException(jakarta.servlet.ServletException) Filter(jakarta.servlet.Filter) Principal(java.security.Principal)

Example 40 with ServletException

use of jakarta.servlet.ServletException in project tomcat by apache.

the class ApplicationContext method createServlet.

@Override
public <T extends Servlet> T createServlet(Class<T> c) throws ServletException {
    try {
        @SuppressWarnings("unchecked") T servlet = (T) context.getInstanceManager().newInstance(c.getName());
        context.dynamicServletCreated(servlet);
        return servlet;
    } catch (InvocationTargetException e) {
        ExceptionUtils.handleThrowable(e.getCause());
        throw new ServletException(e);
    } catch (ReflectiveOperationException | NamingException e) {
        throw new ServletException(e);
    }
}
Also used : ServletException(jakarta.servlet.ServletException) NamingException(javax.naming.NamingException) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Aggregations

ServletException (jakarta.servlet.ServletException)127 IOException (java.io.IOException)78 Test (org.junit.jupiter.api.Test)31 HttpServletRequest (jakarta.servlet.http.HttpServletRequest)23 HttpServletResponse (jakarta.servlet.http.HttpServletResponse)23 ServletContext (jakarta.servlet.ServletContext)19 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)17 MockHttpServletRequest (org.springframework.web.testfixture.servlet.MockHttpServletRequest)15 FilterChain (jakarta.servlet.FilterChain)13 MockHttpServletResponse (org.springframework.web.testfixture.servlet.MockHttpServletResponse)13 Enumeration (java.util.Enumeration)12 BeforeEach (org.junit.jupiter.api.BeforeEach)12 HttpHeaders (org.springframework.http.HttpHeaders)11 BeforeMethod (org.testng.annotations.BeforeMethod)11 ServletConfig (jakarta.servlet.ServletConfig)10 ServletRequest (jakarta.servlet.ServletRequest)10 ServletResponse (jakarta.servlet.ServletResponse)10 Arrays (java.util.Arrays)10 UnavailableException (jakarta.servlet.UnavailableException)9 HttpMethod (org.springframework.http.HttpMethod)9