Search in sources :

Example 11 with ErrorPage

use of org.apache.catalina.deploy.ErrorPage in project Payara by payara.

the class ApplicationDispatcherForward method status.

/*
     * Searches and processes a custom error page for the given status code.
     *
     * This method attempts to map the given status code to an error page,
     * using the mappings of the given context or those of the host on which
     * the given context has been deployed.
     *
     * If a match is found using the context mappings, the request is forwarded
     * to the error page. Otherwise, if a match is found using the host 
     * mappings, the contents of the error page are returned. If no match is
     * found, no action is taken.
     *
     * @return true if a matching error page was found, false otherwise
     */
private static boolean status(HttpServletRequest request, HttpServletResponse response, Context context, Wrapper wrapper, int statusCode) {
    RequestFacadeHelper reqFacHelper = RequestFacadeHelper.getInstance(request);
    /*
         * Attempt error-page mapping only if response.sendError(), as
         * opposed to response.setStatus(), was called.
         */
    if (reqFacHelper == null || !reqFacHelper.isResponseError()) {
        return false;
    }
    boolean matchFound = false;
    ErrorPage errorPage = context.findErrorPage(statusCode);
    if (errorPage != null) {
        matchFound = true;
        // Prevent infinite loop
        String requestPath = (String) request.getAttribute(Globals.DISPATCHER_REQUEST_PATH_ATTR);
        if (requestPath == null || !requestPath.equals(errorPage.getLocation())) {
            String message = reqFacHelper.getResponseMessage();
            if (message == null) {
                message = "";
            } else {
                message = HtmlEntityEncoder.encodeXSS(message);
            }
            prepareRequestForDispatch(request, wrapper, errorPage.getLocation(), statusCode, message);
            custom(request, response, errorPage, context);
        }
    } else {
        errorPage = ((StandardHost) context.getParent()).findErrorPage(statusCode);
        if (errorPage != null) {
            matchFound = true;
            try {
                serveErrorPage(response, errorPage, statusCode);
            } catch (Exception e) {
                String msg = MessageFormat.format(rb.getString(LogFacade.EXCEPTION_PROCESSING), errorPage);
                log.log(Level.WARNING, msg, e);
            }
        }
    }
    return matchFound;
}
Also used : ErrorPage(org.apache.catalina.deploy.ErrorPage)

Example 12 with ErrorPage

use of org.apache.catalina.deploy.ErrorPage in project Payara by payara.

the class StandardHostValve method throwable.

// ------------------------------------------------------ Protected Methods
/**
 * Handle the specified Throwable encountered while processing
 * the specified Request to produce the specified Response.  Any
 * exceptions that occur during generation of the exception report are
 * logged and swallowed.
 *
 * @param request The request being processed
 * @param response The response being generated
 * @param throwable The throwable that occurred (which possibly wraps
 *  a root cause exception
 */
protected void throwable(Request request, Response response, Throwable throwable) {
    Context context = request.getContext();
    if (context == null)
        return;
    Throwable realError = throwable;
    if (realError instanceof ServletException) {
        realError = ((ServletException) realError).getRootCause();
        if (realError == null) {
            realError = throwable;
        }
    }
    // If this is an aborted request from a client just log it and return
    if (realError instanceof ClientAbortException) {
        if (log.isLoggable(Level.FINE)) {
            log.log(Level.FINE, LogFacade.REMOTE_CLIENT_ABORTED_EXCEPTION, realError.getCause().getMessage());
        }
        return;
    }
    ErrorPage errorPage = findErrorPage(context, throwable);
    if ((errorPage == null) && (realError != throwable)) {
        errorPage = findErrorPage(context, realError);
    }
    if (errorPage != null) {
        dispatchToErrorPage(request, response, errorPage, throwable, realError, 0);
    } else if (context.getDefaultErrorPage() != null) {
        dispatchToErrorPage(request, response, context.getDefaultErrorPage(), throwable, realError, 0);
    } else {
        // A custom error-page has not been defined for the exception
        // that was thrown during request processing. Check if an
        // error-page for error code 500 was specified and if so,
        // send that page back as the response.
        ServletResponse sresp = (ServletResponse) response;
        /* GlassFish 6386229
            if (sresp instanceof HttpServletResponse) {
                ((HttpServletResponse) sresp).setStatus(
                    HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                // The response is an error
                response.setError();

                status(request, response);
            }
            */
        // START GlassFish 6386229
        ((HttpServletResponse) sresp).setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        // The response is an error
        response.setError();
        status(request, response);
    // END GlassFish 6386229
    }
}
Also used : HttpServletResponse(javax.servlet.http.HttpServletResponse) ErrorPage(org.apache.catalina.deploy.ErrorPage) ClientAbortException(org.apache.catalina.connector.ClientAbortException)

Example 13 with ErrorPage

use of org.apache.catalina.deploy.ErrorPage in project tomcat70 by apache.

the class TestAsyncContextImpl method doTestTimeoutErrorDispatch.

private void doTestTimeoutErrorDispatch(Boolean asyncError, ErrorPageAsyncMode mode) throws Exception {
    resetTracker();
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    TimeoutServlet timeout = new TimeoutServlet(null, null);
    Wrapper w1 = Tomcat.addServlet(ctx, "time", timeout);
    w1.setAsyncSupported(true);
    ctx.addServletMapping("/async", "time");
    NonAsyncServlet nonAsync = new NonAsyncServlet();
    Wrapper w2 = Tomcat.addServlet(ctx, "nonAsync", nonAsync);
    w2.setAsyncSupported(true);
    ctx.addServletMapping("/error/nonasync", "nonAsync");
    AsyncErrorPage asyncErrorPage = new AsyncErrorPage(mode);
    Wrapper w3 = Tomcat.addServlet(ctx, "asyncErrorPage", asyncErrorPage);
    w3.setAsyncSupported(true);
    ctx.addServletMapping("/error/async", "asyncErrorPage");
    if (asyncError != null) {
        ErrorPage ep = new ErrorPage();
        ep.setErrorCode(500);
        if (asyncError.booleanValue()) {
            ep.setLocation("/error/async");
        } else {
            ep.setLocation("/error/nonasync");
        }
        ctx.addErrorPage(ep);
    }
    ctx.addApplicationListener(TrackingRequestListener.class.getName());
    TesterAccessLogValve alv = new TesterAccessLogValve();
    ctx.getPipeline().addValve(alv);
    TesterAccessLogValve alvGlobal = new TesterAccessLogValve();
    tomcat.getHost().getPipeline().addValve(alvGlobal);
    tomcat.start();
    ByteChunk res = new ByteChunk();
    try {
        getUrl("http://localhost:" + getPort() + "/async", res, null);
    } catch (IOException ioe) {
    // Ignore - expected for some error conditions
    }
    StringBuilder expected = new StringBuilder();
    expected.append("requestInitialized-TimeoutServletGet-");
    if (asyncError != null) {
        if (asyncError.booleanValue()) {
            expected.append("AsyncErrorPageGet-");
            if (mode == ErrorPageAsyncMode.NO_COMPLETE) {
                expected.append("NoOp-");
            } else if (mode == ErrorPageAsyncMode.COMPLETE) {
                expected.append("Complete-");
            } else if (mode == ErrorPageAsyncMode.DISPATCH) {
                expected.append("Dispatch-NonAsyncServletGet-");
            }
        } else {
            expected.append("NonAsyncServletGet-");
        }
    }
    expected.append("requestDestroyed");
    // Request may complete before listener has finished processing so wait
    // up to 5 seconds for the right response
    String expectedTrack = expected.toString();
    int count = 0;
    while (!expectedTrack.equals(getTrack()) && count < 100) {
        Thread.sleep(50);
        count++;
    }
    Assert.assertEquals(expectedTrack, getTrack());
    // Check the access log
    alvGlobal.validateAccessLog(1, 500, TimeoutServlet.ASYNC_TIMEOUT, TimeoutServlet.ASYNC_TIMEOUT + TIMEOUT_MARGIN + REQUEST_TIME);
    alv.validateAccessLog(1, 500, TimeoutServlet.ASYNC_TIMEOUT, TimeoutServlet.ASYNC_TIMEOUT + TIMEOUT_MARGIN + REQUEST_TIME);
}
Also used : AsyncContext(javax.servlet.AsyncContext) Context(org.apache.catalina.Context) Wrapper(org.apache.catalina.Wrapper) ServletResponseWrapper(javax.servlet.ServletResponseWrapper) ServletRequestWrapper(javax.servlet.ServletRequestWrapper) Tomcat(org.apache.catalina.startup.Tomcat) ErrorPage(org.apache.catalina.deploy.ErrorPage) ByteChunk(org.apache.tomcat.util.buf.ByteChunk) IOException(java.io.IOException) TesterAccessLogValve(org.apache.catalina.valves.TesterAccessLogValve)

Example 14 with ErrorPage

use of org.apache.catalina.deploy.ErrorPage in project tomcat70 by apache.

the class TestAsyncContextImpl method testTimeoutDispatchCustomErrorPage.

/*
     * See https://bz.apache.org/bugzilla/show_bug.cgi?id=58751 comment 1
     */
@Test
public void testTimeoutDispatchCustomErrorPage() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    Context context = tomcat.addContext("", null);
    tomcat.addServlet("", "timeout", Bug58751AsyncServlet.class.getName()).setAsyncSupported(true);
    CustomErrorServlet customErrorServlet = new CustomErrorServlet();
    Tomcat.addServlet(context, "customErrorServlet", customErrorServlet);
    context.addServletMapping("/timeout", "timeout");
    context.addServletMapping("/error", "customErrorServlet");
    ErrorPage errorPage = new ErrorPage();
    errorPage.setLocation("/error");
    context.addErrorPage(errorPage);
    tomcat.start();
    ByteChunk responseBody = new ByteChunk();
    int rc = getUrl("http://localhost:" + getPort() + "/timeout", responseBody, null);
    Assert.assertEquals(503, rc);
    Assert.assertEquals(CustomErrorServlet.ERROR_MESSAGE, responseBody.toString());
}
Also used : AsyncContext(javax.servlet.AsyncContext) Context(org.apache.catalina.Context) Tomcat(org.apache.catalina.startup.Tomcat) ErrorPage(org.apache.catalina.deploy.ErrorPage) ByteChunk(org.apache.tomcat.util.buf.ByteChunk) TomcatBaseTest(org.apache.catalina.startup.TomcatBaseTest) Test(org.junit.Test)

Example 15 with ErrorPage

use of org.apache.catalina.deploy.ErrorPage in project tomcat70 by apache.

the class TestAsyncContextImpl method doTestBug51197.

private void doTestBug51197(boolean threaded, boolean customError) throws Exception {
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    AsyncErrorServlet asyncErrorServlet = new AsyncErrorServlet(HttpServletResponse.SC_BAD_REQUEST, threaded);
    Wrapper wrapper = Tomcat.addServlet(ctx, "asyncErrorServlet", asyncErrorServlet);
    wrapper.setAsyncSupported(true);
    ctx.addServletMapping("/asyncErrorServlet", "asyncErrorServlet");
    if (customError) {
        CustomErrorServlet customErrorServlet = new CustomErrorServlet();
        Tomcat.addServlet(ctx, "customErrorServlet", customErrorServlet);
        ctx.addServletMapping("/customErrorServlet", "customErrorServlet");
        ErrorPage ep = new ErrorPage();
        ep.setLocation("/customErrorServlet");
        ctx.addErrorPage(ep);
    }
    TesterAccessLogValve alv = new TesterAccessLogValve();
    ctx.getPipeline().addValve(alv);
    tomcat.start();
    StringBuilder url = new StringBuilder(48);
    url.append("http://localhost:");
    url.append(getPort());
    url.append("/asyncErrorServlet");
    ByteChunk res = new ByteChunk();
    int rc = getUrl(url.toString(), res, null);
    Assert.assertEquals(HttpServletResponse.SC_BAD_REQUEST, rc);
    // SRV 10.9.2 - Handling an error is entirely the application's
    // responsibility when an error occurs on an application thread.
    // Calling sendError() followed by complete() and expecting the standard
    // error page mechanism to kick in could be viewed as handling the error
    String responseBody = res.toString();
    Assert.assertNotNull(responseBody);
    Assert.assertTrue(responseBody.length() > 0);
    if (customError) {
        Assert.assertTrue(responseBody, responseBody.contains(CustomErrorServlet.ERROR_MESSAGE));
    } else {
        Assert.assertTrue(responseBody, responseBody.contains(AsyncErrorServlet.ERROR_MESSAGE));
    }
    // Without this test may complete before access log has a chance to log
    // the request
    Thread.sleep(REQUEST_TIME);
    // Check the access log
    alv.validateAccessLog(1, HttpServletResponse.SC_BAD_REQUEST, 0, REQUEST_TIME);
}
Also used : AsyncContext(javax.servlet.AsyncContext) Context(org.apache.catalina.Context) Wrapper(org.apache.catalina.Wrapper) ServletResponseWrapper(javax.servlet.ServletResponseWrapper) ServletRequestWrapper(javax.servlet.ServletRequestWrapper) Tomcat(org.apache.catalina.startup.Tomcat) ErrorPage(org.apache.catalina.deploy.ErrorPage) ByteChunk(org.apache.tomcat.util.buf.ByteChunk) TesterAccessLogValve(org.apache.catalina.valves.TesterAccessLogValve)

Aggregations

ErrorPage (org.apache.catalina.deploy.ErrorPage)20 Context (org.apache.catalina.Context)11 Tomcat (org.apache.catalina.startup.Tomcat)8 TomcatBaseTest (org.apache.catalina.startup.TomcatBaseTest)6 Test (org.junit.Test)6 Wrapper (org.apache.catalina.Wrapper)5 ByteChunk (org.apache.tomcat.util.buf.ByteChunk)5 ClientAbortException (org.apache.catalina.connector.ClientAbortException)4 IOException (java.io.IOException)3 AsyncContext (javax.servlet.AsyncContext)3 ServletContext (javax.servlet.ServletContext)3 SecurityConstraint (org.apache.catalina.deploy.SecurityConstraint)3 ServletRequestWrapper (javax.servlet.ServletRequestWrapper)2 ServletResponseWrapper (javax.servlet.ServletResponseWrapper)2 HttpServletResponse (javax.servlet.http.HttpServletResponse)2 FilterMap (org.apache.catalina.deploy.FilterMap)2 TesterAccessLogValve (org.apache.catalina.valves.TesterAccessLogValve)2 File (java.io.File)1 SimpleDateFormat (java.text.SimpleDateFormat)1 Date (java.util.Date)1