Search in sources :

Example 1 with ClientAbortException

use of org.apache.catalina.connector.ClientAbortException in project tomcat by apache.

the class StandardHostValve method status.

// -------------------------------------------------------- Private Methods
/**
     * Handle the HTTP status code (and corresponding message) generated
     * while processing the specified Request to produce the specified
     * Response.  Any exceptions that occur during generation of the error
     * report are logged and swallowed.
     *
     * @param request The request being processed
     * @param response The response being generated
     */
private void status(Request request, Response response) {
    int statusCode = response.getStatus();
    // Handle a custom error page for this status code
    Context context = request.getContext();
    if (context == null) {
        return;
    }
    /* Only look for error pages when isError() is set.
         * isError() is set when response.sendError() is invoked. This
         * allows custom error pages without relying on default from
         * web.xml.
         */
    if (!response.isError()) {
        return;
    }
    ErrorPage errorPage = context.findErrorPage(statusCode);
    if (errorPage == null) {
        // Look for a default error page
        errorPage = context.findErrorPage(0);
    }
    if (errorPage != null && response.isErrorReportRequired()) {
        response.setAppCommitted(false);
        request.setAttribute(RequestDispatcher.ERROR_STATUS_CODE, Integer.valueOf(statusCode));
        String message = response.getMessage();
        if (message == null) {
            message = "";
        }
        request.setAttribute(RequestDispatcher.ERROR_MESSAGE, message);
        request.setAttribute(Globals.DISPATCHER_REQUEST_PATH_ATTR, errorPage.getLocation());
        request.setAttribute(Globals.DISPATCHER_TYPE_ATTR, DispatcherType.ERROR);
        Wrapper wrapper = request.getWrapper();
        if (wrapper != null) {
            request.setAttribute(RequestDispatcher.ERROR_SERVLET_NAME, wrapper.getName());
        }
        request.setAttribute(RequestDispatcher.ERROR_REQUEST_URI, request.getRequestURI());
        if (custom(request, response, errorPage)) {
            response.setErrorReported();
            try {
                response.finishResponse();
            } catch (ClientAbortException e) {
            // Ignore
            } catch (IOException e) {
                container.getLogger().warn("Exception Processing " + errorPage, e);
            }
        }
    }
}
Also used : Context(org.apache.catalina.Context) ServletContext(javax.servlet.ServletContext) Wrapper(org.apache.catalina.Wrapper) ErrorPage(org.apache.tomcat.util.descriptor.web.ErrorPage) ClientAbortException(org.apache.catalina.connector.ClientAbortException) IOException(java.io.IOException)

Example 2 with ClientAbortException

use of org.apache.catalina.connector.ClientAbortException 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
    try {
        if (filterChain != null)
            filterChain.release();
    } catch (Throwable e) {
        ExceptionUtils.handleThrowable(e);
        wrapper.getLogger().error(sm.getString("standardWrapper.releaseFilters", wrapper.getName()), e);
    // FIXME: Exception handling needs to be similar to what is in the StandardWrapperValue
    }
    // 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(javax.servlet.ServletException) UnavailableException(javax.servlet.UnavailableException) HttpServletResponse(javax.servlet.http.HttpServletResponse) Servlet(javax.servlet.Servlet) ClientAbortException(org.apache.catalina.connector.ClientAbortException) IOException(java.io.IOException)

Example 3 with ClientAbortException

use of org.apache.catalina.connector.ClientAbortException in project fess by codelibs.

the class EsApiManager method processRequest.

protected void processRequest(final HttpServletRequest request, final HttpServletResponse response, final String path) {
    if (StringUtil.isNotBlank(path)) {
        final String lowerPath = path.toLowerCase(Locale.ROOT);
        if (lowerPath.endsWith(".html")) {
            response.setContentType("text/html;charset=utf-8");
        } else if (lowerPath.endsWith(".txt")) {
            response.setContentType("text/plain");
        } else if (lowerPath.endsWith(".css")) {
            response.setContentType("text/css");
        }
    }
    if (path.startsWith("/_plugin/") || path.equals("/_plugin")) {
        processPluginRequest(request, response, path.replaceFirst("^/_plugin", StringUtil.EMPTY));
        return;
    }
    final Method httpMethod = Method.valueOf(request.getMethod().toUpperCase(Locale.ROOT));
    final CurlRequest curlRequest = new CurlRequest(httpMethod, ResourceUtil.getElasticsearchHttpUrl() + path);
    request.getParameterMap().entrySet().stream().forEach(entry -> {
        if (entry.getValue().length > 1) {
            curlRequest.param(entry.getKey(), String.join(",", entry.getValue()));
        } else if (entry.getValue().length == 1) {
            curlRequest.param(entry.getKey(), entry.getValue()[0]);
        }
    });
    curlRequest.onConnect((req, con) -> {
        con.setDoOutput(true);
        if (httpMethod != Method.GET) {
            try (ServletInputStream in = request.getInputStream();
                OutputStream out = con.getOutputStream()) {
                CopyUtil.copy(in, out);
            } catch (final IOException e) {
                throw new WebApiException(HttpServletResponse.SC_BAD_REQUEST, e);
            }
        }
    }).execute(con -> {
        try (ServletOutputStream out = response.getOutputStream()) {
            try (InputStream in = con.getInputStream()) {
                response.setStatus(con.getResponseCode());
                CopyUtil.copy(in, out);
            } catch (final Exception e) {
                response.setStatus(con.getResponseCode());
                try (InputStream err = con.getErrorStream()) {
                    CopyUtil.copy(err, out);
                }
            }
        } catch (final ClientAbortException e) {
            logger.debug("Client aborts this request.", e);
        } catch (final Exception e) {
            if (e.getCause() instanceof ClientAbortException) {
                logger.debug("Client aborts this request.", e);
            } else {
                throw new WebApiException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e);
            }
        }
    });
}
Also used : FilterChain(javax.servlet.FilterChain) Constants(org.codelibs.fess.Constants) ServletException(javax.servlet.ServletException) FessSystemException(org.codelibs.fess.exception.FessSystemException) ServletInputStream(javax.servlet.ServletInputStream) BaseApiManager(org.codelibs.fess.api.BaseApiManager) LoggerFactory(org.slf4j.LoggerFactory) ClientAbortException(org.apache.catalina.connector.ClientAbortException) SessionManager(org.lastaflute.web.servlet.session.SessionManager) WebApiException(org.codelibs.fess.exception.WebApiException) FessUserBean(org.codelibs.fess.mylasta.action.FessUserBean) ResourceUtil(org.codelibs.fess.util.ResourceUtil) HttpServletRequest(javax.servlet.http.HttpServletRequest) RequestManager(org.lastaflute.web.servlet.request.RequestManager) ServletOutputStream(javax.servlet.ServletOutputStream) Locale(java.util.Locale) CopyUtil(org.codelibs.core.io.CopyUtil) Path(java.nio.file.Path) OutputStream(java.io.OutputStream) Logger(org.slf4j.Logger) Files(java.nio.file.Files) HttpServletResponse(javax.servlet.http.HttpServletResponse) StringUtil(org.codelibs.core.lang.StringUtil) IOException(java.io.IOException) UUID(java.util.UUID) ComponentUtil(org.codelibs.fess.util.ComponentUtil) CurlRequest(org.codelibs.elasticsearch.runner.net.CurlRequest) InputStream(java.io.InputStream) Method(org.codelibs.elasticsearch.runner.net.Curl.Method) ServletInputStream(javax.servlet.ServletInputStream) ServletOutputStream(javax.servlet.ServletOutputStream) ServletInputStream(javax.servlet.ServletInputStream) InputStream(java.io.InputStream) ServletOutputStream(javax.servlet.ServletOutputStream) OutputStream(java.io.OutputStream) CurlRequest(org.codelibs.elasticsearch.runner.net.CurlRequest) ClientAbortException(org.apache.catalina.connector.ClientAbortException) Method(org.codelibs.elasticsearch.runner.net.Curl.Method) IOException(java.io.IOException) WebApiException(org.codelibs.fess.exception.WebApiException) ServletException(javax.servlet.ServletException) FessSystemException(org.codelibs.fess.exception.FessSystemException) ClientAbortException(org.apache.catalina.connector.ClientAbortException) WebApiException(org.codelibs.fess.exception.WebApiException) IOException(java.io.IOException)

Example 4 with ClientAbortException

use of org.apache.catalina.connector.ClientAbortException in project fess by codelibs.

the class EsApiManager method processPluginRequest.

private void processPluginRequest(final HttpServletRequest request, final HttpServletResponse response, final String path) {
    Path filePath = ResourceUtil.getSitePath(path.replaceAll("\\.\\.+", StringUtil.EMPTY).replaceAll("/+", "/").split("/"));
    if (Files.isDirectory(filePath)) {
        filePath = filePath.resolve("index.html");
    }
    if (Files.exists(filePath)) {
        try (InputStream in = Files.newInputStream(filePath);
            ServletOutputStream out = response.getOutputStream()) {
            response.setStatus(HttpServletResponse.SC_OK);
            CopyUtil.copy(in, out);
        } catch (final ClientAbortException e) {
            logger.debug("Client aborts this request.", e);
        } catch (final IOException e) {
            logger.error("Failed to read " + path + " from " + filePath);
            throw new WebApiException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e);
        }
    } else {
        try {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, path + " is not found.");
        } catch (final ClientAbortException e) {
            logger.debug("Client aborts this request.", e);
        } catch (final IOException e) {
            logger.error("Failed to read " + path + " from " + filePath);
            throw new WebApiException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e);
        }
    }
}
Also used : Path(java.nio.file.Path) ServletOutputStream(javax.servlet.ServletOutputStream) ServletInputStream(javax.servlet.ServletInputStream) InputStream(java.io.InputStream) ClientAbortException(org.apache.catalina.connector.ClientAbortException) IOException(java.io.IOException) WebApiException(org.codelibs.fess.exception.WebApiException)

Example 5 with ClientAbortException

use of org.apache.catalina.connector.ClientAbortException in project fess by codelibs.

the class ViewHelper method writeContent.

protected StreamResponse writeContent(final String configId, final String url, final CrawlerClient client) {
    final ResponseData responseData = client.execute(RequestDataBuilder.newRequestData().get().url(url).build());
    final StreamResponse response = new StreamResponse(StringUtil.EMPTY);
    writeFileName(response, responseData);
    writeContentType(response, responseData);
    writeNoCache(response, responseData);
    if (responseData.getHttpStatusCode() == 404) {
        response.httpStatus(responseData.getHttpStatusCode());
        return response;
    }
    response.stream(out -> {
        try (final InputStream is = new BufferedInputStream(responseData.getResponseBody())) {
            out.write(is);
        } catch (final IOException e) {
            if (!(e.getCause() instanceof ClientAbortException)) {
                throw new FessSystemException("Failed to write a content. configId: " + configId + ", url: " + url, e);
            }
        } finally {
            responseData.close();
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Finished to write " + url);
        }
    });
    return response;
}
Also used : BufferedInputStream(java.io.BufferedInputStream) BufferedInputStream(java.io.BufferedInputStream) InputStream(java.io.InputStream) ResponseData(org.codelibs.fess.crawler.entity.ResponseData) StreamResponse(org.lastaflute.web.response.StreamResponse) ClientAbortException(org.apache.catalina.connector.ClientAbortException) IOException(java.io.IOException) FessSystemException(org.codelibs.fess.exception.FessSystemException)

Aggregations

IOException (java.io.IOException)7 ClientAbortException (org.apache.catalina.connector.ClientAbortException)7 ServletException (javax.servlet.ServletException)4 InputStream (java.io.InputStream)3 Context (org.apache.catalina.Context)3 Path (java.nio.file.Path)2 Servlet (javax.servlet.Servlet)2 ServletContext (javax.servlet.ServletContext)2 ServletInputStream (javax.servlet.ServletInputStream)2 ServletOutputStream (javax.servlet.ServletOutputStream)2 UnavailableException (javax.servlet.UnavailableException)2 HttpServletResponse (javax.servlet.http.HttpServletResponse)2 Wrapper (org.apache.catalina.Wrapper)2 ErrorPage (org.apache.tomcat.util.descriptor.web.ErrorPage)2 FessSystemException (org.codelibs.fess.exception.FessSystemException)2 WebApiException (org.codelibs.fess.exception.WebApiException)2 BufferedInputStream (java.io.BufferedInputStream)1 OutputStream (java.io.OutputStream)1 Files (java.nio.file.Files)1 Locale (java.util.Locale)1