Search in sources :

Example 41 with ServletException

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

the class ApplicationDispatcher method invoke.

// -------------------------------------------------------- Private Methods
/**
 * Ask the resource represented by this RequestDispatcher to process
 * the associated request, and create (or append to) the associated
 * response.
 * <p>
 * <strong>IMPLEMENTATION NOTE</strong>: This implementation assumes
 * that no filters are applied to a forwarded or included resource,
 * because they were already done for the original request.
 *
 * @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 error occurs
 */
private void invoke(ServletRequest request, ServletResponse response, State state) throws IOException, ServletException {
    // Checking to see if the context classloader is the current context
    // classloader. If it's not, we're saving it, and setting the context
    // classloader to the Context classloader
    ClassLoader oldCCL = context.bind(false, null);
    // Initialize local variables we may need
    HttpServletResponse hresponse = state.hresponse;
    Servlet servlet = null;
    IOException ioException = null;
    ServletException servletException = null;
    RuntimeException runtimeException = null;
    boolean unavailable = false;
    // Check for the servlet being marked unavailable
    if (wrapper.isUnavailable()) {
        wrapper.getLogger().warn(sm.getString("applicationDispatcher.isUnavailable", wrapper.getName()));
        long available = wrapper.getAvailable();
        if ((available > 0L) && (available < Long.MAX_VALUE)) {
            hresponse.setDateHeader("Retry-After", available);
        }
        hresponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sm.getString("applicationDispatcher.isUnavailable", wrapper.getName()));
        unavailable = true;
    }
    // Allocate a servlet instance to process this request
    try {
        if (!unavailable) {
            servlet = wrapper.allocate();
        }
    } catch (ServletException e) {
        wrapper.getLogger().error(sm.getString("applicationDispatcher.allocateException", wrapper.getName()), StandardWrapper.getRootCause(e));
        servletException = e;
    } catch (Throwable e) {
        ExceptionUtils.handleThrowable(e);
        wrapper.getLogger().error(sm.getString("applicationDispatcher.allocateException", wrapper.getName()), e);
        servletException = new ServletException(sm.getString("applicationDispatcher.allocateException", wrapper.getName()), e);
        servlet = null;
    }
    // Get the FilterChain Here
    ApplicationFilterChain filterChain = ApplicationFilterFactory.createFilterChain(request, wrapper, servlet);
    // Call the service() method for the allocated servlet instance
    try {
        // for includes/forwards
        if ((servlet != null) && (filterChain != null)) {
            filterChain.doFilter(request, response);
        }
    // Servlet Service Method is called by the FilterChain
    } catch (ClientAbortException e) {
        ioException = e;
    } catch (IOException e) {
        wrapper.getLogger().error(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), e);
        ioException = e;
    } catch (UnavailableException e) {
        wrapper.getLogger().error(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), e);
        servletException = e;
        wrapper.unavailable(e);
    } catch (ServletException e) {
        Throwable rootCause = StandardWrapper.getRootCause(e);
        if (!(rootCause instanceof ClientAbortException)) {
            wrapper.getLogger().error(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), rootCause);
        }
        servletException = e;
    } catch (RuntimeException e) {
        wrapper.getLogger().error(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), e);
        runtimeException = e;
    }
    // Release the filter chain (if any) for this request
    if (filterChain != null) {
        filterChain.release();
    }
    // Deallocate the allocated servlet instance
    try {
        if (servlet != null) {
            wrapper.deallocate(servlet);
        }
    } catch (ServletException e) {
        wrapper.getLogger().error(sm.getString("applicationDispatcher.deallocateException", wrapper.getName()), e);
        servletException = e;
    } catch (Throwable e) {
        ExceptionUtils.handleThrowable(e);
        wrapper.getLogger().error(sm.getString("applicationDispatcher.deallocateException", wrapper.getName()), e);
        servletException = new ServletException(sm.getString("applicationDispatcher.deallocateException", wrapper.getName()), e);
    }
    // Reset the old context class loader
    context.unbind(false, oldCCL);
    // Unwrap request/response if needed
    // See Bugzilla 30949
    unwrapRequest(state);
    unwrapResponse(state);
    // Recycle request if necessary (also BZ 30949)
    recycleRequestWrapper(state);
    // Rethrow an exception if one was thrown by the invoked servlet
    if (ioException != null) {
        throw ioException;
    }
    if (servletException != null) {
        throw servletException;
    }
    if (runtimeException != null) {
        throw runtimeException;
    }
}
Also used : ServletException(jakarta.servlet.ServletException) UnavailableException(jakarta.servlet.UnavailableException) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) Servlet(jakarta.servlet.Servlet) ClientAbortException(org.apache.catalina.connector.ClientAbortException) IOException(java.io.IOException)

Example 42 with ServletException

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

the class AsyncContextImpl method createListener.

@SuppressWarnings("unchecked")
@Override
public <T extends AsyncListener> T createListener(Class<T> clazz) throws ServletException {
    check();
    T listener = null;
    try {
        listener = (T) context.getInstanceManager().newInstance(clazz.getName(), clazz.getClassLoader());
    } catch (ReflectiveOperationException | NamingException e) {
        ServletException se = new ServletException(e);
        throw se;
    } catch (Exception e) {
        ExceptionUtils.handleThrowable(e.getCause());
        ServletException se = new ServletException(e);
        throw se;
    }
    return listener;
}
Also used : ServletException(jakarta.servlet.ServletException) NamingException(javax.naming.NamingException) NamingException(javax.naming.NamingException) ServletException(jakarta.servlet.ServletException) IOException(java.io.IOException)

Example 43 with ServletException

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

the class AsyncContextImpl method doInternalDispatch.

protected void doInternalDispatch() throws ServletException, IOException {
    if (log.isDebugEnabled()) {
        logDebug("intDispatch");
    }
    try {
        Runnable runnable = dispatch;
        dispatch = null;
        runnable.run();
        if (!request.isAsync()) {
            fireOnComplete();
        }
    } catch (RuntimeException x) {
        // doInternalComplete(true);
        if (x.getCause() instanceof ServletException) {
            throw (ServletException) x.getCause();
        }
        if (x.getCause() instanceof IOException) {
            throw (IOException) x.getCause();
        }
        throw new ServletException(x);
    }
}
Also used : ServletException(jakarta.servlet.ServletException) IOException(java.io.IOException)

Example 44 with ServletException

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

the class SSIServletExternalResolver method getFileText.

// We are making lots of unnecessary copies of the included data here. If
// someone ever complains that this is slow, we should connect the included
// stream to the print writer that SSICommand uses.
@Override
public String getFileText(String originalPath, boolean virtual) throws IOException {
    try {
        ServletContextAndPath csAndP = getServletContextAndPath(originalPath, virtual);
        ServletContext context = csAndP.getServletContext();
        String path = csAndP.getPath();
        RequestDispatcher rd = context.getRequestDispatcher(path);
        if (rd == null) {
            throw new IOException(sm.getString("ssiServletExternalResolver.requestDispatcherError", path));
        }
        ByteArrayServletOutputStream basos = new ByteArrayServletOutputStream();
        ResponseIncludeWrapper responseIncludeWrapper = new ResponseIncludeWrapper(res, basos);
        rd.include(req, responseIncludeWrapper);
        // We can't assume the included servlet flushed its output
        responseIncludeWrapper.flushOutputStreamOrWriter();
        byte[] bytes = basos.toByteArray();
        // Assume platform default encoding unless otherwise specified
        String retVal;
        if (inputEncoding == null) {
            retVal = new String(bytes);
        } else {
            retVal = new String(bytes, B2CConverter.getCharset(inputEncoding));
        }
        // were included, but not sure how else to tell.
        if (retVal.equals("") && !req.getMethod().equalsIgnoreCase("HEAD")) {
            throw new IOException(sm.getString("ssiServletExternalResolver.noFile", path));
        }
        return retVal;
    } catch (ServletException e) {
        throw new IOException(sm.getString("ssiServletExternalResolver.noIncludeFile", originalPath), e);
    }
}
Also used : ServletException(jakarta.servlet.ServletException) ServletContext(jakarta.servlet.ServletContext) IOException(java.io.IOException) RequestDispatcher(jakarta.servlet.RequestDispatcher)

Example 45 with ServletException

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

the class UpgradeUtil method doUpgrade.

public static void doUpgrade(WsServerContainer sc, HttpServletRequest req, HttpServletResponse resp, ServerEndpointConfig sec, Map<String, String> pathParams) throws ServletException, IOException {
    // Validate the rest of the headers and reject the request if that
    // validation fails
    String key;
    String subProtocol = null;
    if (!headerContainsToken(req, Constants.CONNECTION_HEADER_NAME, Constants.CONNECTION_HEADER_VALUE)) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }
    if (!headerContainsToken(req, Constants.WS_VERSION_HEADER_NAME, Constants.WS_VERSION_HEADER_VALUE)) {
        resp.setStatus(426);
        resp.setHeader(Constants.WS_VERSION_HEADER_NAME, Constants.WS_VERSION_HEADER_VALUE);
        return;
    }
    key = req.getHeader(Constants.WS_KEY_HEADER_NAME);
    if (key == null) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }
    // Origin check
    String origin = req.getHeader(Constants.ORIGIN_HEADER_NAME);
    if (!sec.getConfigurator().checkOrigin(origin)) {
        resp.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }
    // Sub-protocols
    List<String> subProtocols = getTokensFromHeader(req, Constants.WS_PROTOCOL_HEADER_NAME);
    subProtocol = sec.getConfigurator().getNegotiatedSubprotocol(sec.getSubprotocols(), subProtocols);
    // Extensions
    // Should normally only be one header but handle the case of multiple
    // headers
    List<Extension> extensionsRequested = new ArrayList<>();
    Enumeration<String> extHeaders = req.getHeaders(Constants.WS_EXTENSIONS_HEADER_NAME);
    while (extHeaders.hasMoreElements()) {
        Util.parseExtensionHeader(extensionsRequested, extHeaders.nextElement());
    }
    // Negotiation phase 1. By default this simply filters out the
    // extensions that the server does not support but applications could
    // use a custom configurator to do more than this.
    List<Extension> installedExtensions = null;
    if (sec.getExtensions().size() == 0) {
        installedExtensions = Constants.INSTALLED_EXTENSIONS;
    } else {
        installedExtensions = new ArrayList<>();
        installedExtensions.addAll(sec.getExtensions());
        installedExtensions.addAll(Constants.INSTALLED_EXTENSIONS);
    }
    List<Extension> negotiatedExtensionsPhase1 = sec.getConfigurator().getNegotiatedExtensions(installedExtensions, extensionsRequested);
    // Negotiation phase 2. Create the Transformations that will be applied
    // to this connection. Note than an extension may be dropped at this
    // point if the client has requested a configuration that the server is
    // unable to support.
    List<Transformation> transformations = createTransformations(negotiatedExtensionsPhase1);
    List<Extension> negotiatedExtensionsPhase2;
    if (transformations.isEmpty()) {
        negotiatedExtensionsPhase2 = Collections.emptyList();
    } else {
        negotiatedExtensionsPhase2 = new ArrayList<>(transformations.size());
        for (Transformation t : transformations) {
            negotiatedExtensionsPhase2.add(t.getExtensionResponse());
        }
    }
    // Build the transformation pipeline
    Transformation transformation = null;
    StringBuilder responseHeaderExtensions = new StringBuilder();
    boolean first = true;
    for (Transformation t : transformations) {
        if (first) {
            first = false;
        } else {
            responseHeaderExtensions.append(',');
        }
        append(responseHeaderExtensions, t.getExtensionResponse());
        if (transformation == null) {
            transformation = t;
        } else {
            transformation.setNext(t);
        }
    }
    // Now we have the full pipeline, validate the use of the RSV bits.
    if (transformation != null && !transformation.validateRsvBits(0)) {
        throw new ServletException(sm.getString("upgradeUtil.incompatibleRsv"));
    }
    // If we got this far, all is good. Accept the connection.
    resp.setHeader(Constants.UPGRADE_HEADER_NAME, Constants.UPGRADE_HEADER_VALUE);
    resp.setHeader(Constants.CONNECTION_HEADER_NAME, Constants.CONNECTION_HEADER_VALUE);
    resp.setHeader(HandshakeResponse.SEC_WEBSOCKET_ACCEPT, getWebSocketAccept(key));
    if (subProtocol != null && subProtocol.length() > 0) {
        // RFC6455 4.2.2 explicitly states "" is not valid here
        resp.setHeader(Constants.WS_PROTOCOL_HEADER_NAME, subProtocol);
    }
    if (!transformations.isEmpty()) {
        resp.setHeader(Constants.WS_EXTENSIONS_HEADER_NAME, responseHeaderExtensions.toString());
    }
    // Add method mapping to user properties
    if (!Endpoint.class.isAssignableFrom(sec.getEndpointClass()) && sec.getUserProperties().get(org.apache.tomcat.websocket.pojo.Constants.POJO_METHOD_MAPPING_KEY) == null) {
        // directly. Need to add the method mapping.
        try {
            PojoMethodMapping methodMapping = new PojoMethodMapping(sec.getEndpointClass(), sec.getDecoders(), sec.getPath(), sc.getInstanceManager(Thread.currentThread().getContextClassLoader()));
            if (methodMapping.getOnClose() != null || methodMapping.getOnOpen() != null || methodMapping.getOnError() != null || methodMapping.hasMessageHandlers()) {
                sec.getUserProperties().put(org.apache.tomcat.websocket.pojo.Constants.POJO_METHOD_MAPPING_KEY, methodMapping);
            }
        } catch (DeploymentException e) {
            throw new ServletException(sm.getString("upgradeUtil.pojoMapFail", sec.getEndpointClass().getName()), e);
        }
    }
    WsPerSessionServerEndpointConfig perSessionServerEndpointConfig = new WsPerSessionServerEndpointConfig(sec);
    WsHandshakeRequest wsRequest = new WsHandshakeRequest(req, pathParams);
    WsHandshakeResponse wsResponse = new WsHandshakeResponse();
    sec.getConfigurator().modifyHandshake(perSessionServerEndpointConfig, wsRequest, wsResponse);
    wsRequest.finished();
    // Add any additional headers
    for (Entry<String, List<String>> entry : wsResponse.getHeaders().entrySet()) {
        for (String headerValue : entry.getValue()) {
            resp.addHeader(entry.getKey(), headerValue);
        }
    }
    WsHttpUpgradeHandler wsHandler = req.upgrade(WsHttpUpgradeHandler.class);
    wsHandler.preInit(perSessionServerEndpointConfig, sc, wsRequest, negotiatedExtensionsPhase2, subProtocol, transformation, pathParams, req.isSecure());
}
Also used : Transformation(org.apache.tomcat.websocket.Transformation) WsHandshakeResponse(org.apache.tomcat.websocket.WsHandshakeResponse) ArrayList(java.util.ArrayList) Extension(jakarta.websocket.Extension) ServletException(jakarta.servlet.ServletException) DeploymentException(jakarta.websocket.DeploymentException) ArrayList(java.util.ArrayList) List(java.util.List) PojoMethodMapping(org.apache.tomcat.websocket.pojo.PojoMethodMapping)

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