Search in sources :

Example 1 with ErrorPage

use of org.apache.tomcat.util.descriptor.web.ErrorPage 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 ErrorPage

use of org.apache.tomcat.util.descriptor.web.ErrorPage in project tomcat 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.addServletMappingDecoded("/async", "time");
    NonAsyncServlet nonAsync = new NonAsyncServlet();
    Wrapper w2 = Tomcat.addServlet(ctx, "nonAsync", nonAsync);
    w2.setAsyncSupported(true);
    ctx.addServletMappingDecoded("/error/nonasync", "nonAsync");
    AsyncErrorPage asyncErrorPage = new AsyncErrorPage(mode);
    Wrapper w3 = Tomcat.addServlet(ctx, "asyncErrorPage", asyncErrorPage);
    w3.setAsyncSupported(true);
    ctx.addServletMappingDecoded("/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) TesterContext(org.apache.tomcat.unittest.TesterContext) Wrapper(org.apache.catalina.Wrapper) ServletResponseWrapper(javax.servlet.ServletResponseWrapper) ServletRequestWrapper(javax.servlet.ServletRequestWrapper) Tomcat(org.apache.catalina.startup.Tomcat) ErrorPage(org.apache.tomcat.util.descriptor.web.ErrorPage) ByteChunk(org.apache.tomcat.util.buf.ByteChunk) IOException(java.io.IOException) TesterAccessLogValve(org.apache.catalina.valves.TesterAccessLogValve)

Example 3 with ErrorPage

use of org.apache.tomcat.util.descriptor.web.ErrorPage in project tomcat 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.addServletMappingDecoded("/timeout", "timeout");
    context.addServletMappingDecoded("/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) TesterContext(org.apache.tomcat.unittest.TesterContext) Tomcat(org.apache.catalina.startup.Tomcat) ErrorPage(org.apache.tomcat.util.descriptor.web.ErrorPage) ByteChunk(org.apache.tomcat.util.buf.ByteChunk) TomcatBaseTest(org.apache.catalina.startup.TomcatBaseTest) Test(org.junit.Test)

Example 4 with ErrorPage

use of org.apache.tomcat.util.descriptor.web.ErrorPage in project tomcat 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.addServletMappingDecoded("/asyncErrorServlet", "asyncErrorServlet");
    if (customError) {
        CustomErrorServlet customErrorServlet = new CustomErrorServlet();
        Tomcat.addServlet(ctx, "customErrorServlet", customErrorServlet);
        ctx.addServletMappingDecoded("/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);
    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);
    assertTrue(responseBody.length() > 0);
    if (customError) {
        assertTrue(responseBody, responseBody.contains(CustomErrorServlet.ERROR_MESSAGE));
    } else {
        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) TesterContext(org.apache.tomcat.unittest.TesterContext) Wrapper(org.apache.catalina.Wrapper) ServletResponseWrapper(javax.servlet.ServletResponseWrapper) ServletRequestWrapper(javax.servlet.ServletRequestWrapper) Tomcat(org.apache.catalina.startup.Tomcat) ErrorPage(org.apache.tomcat.util.descriptor.web.ErrorPage) ByteChunk(org.apache.tomcat.util.buf.ByteChunk) TesterAccessLogValve(org.apache.catalina.valves.TesterAccessLogValve)

Example 5 with ErrorPage

use of org.apache.tomcat.util.descriptor.web.ErrorPage in project tomcat by apache.

the class ContextConfig method configureContext.

private void configureContext(WebXml webxml) {
    // As far as possible, process in alphabetical order so it is easy to
    // check everything is present
    // Some validation depends on correct public ID
    context.setPublicId(webxml.getPublicId());
    // Everything else in order
    context.setEffectiveMajorVersion(webxml.getMajorVersion());
    context.setEffectiveMinorVersion(webxml.getMinorVersion());
    for (Entry<String, String> entry : webxml.getContextParams().entrySet()) {
        context.addParameter(entry.getKey(), entry.getValue());
    }
    context.setDenyUncoveredHttpMethods(webxml.getDenyUncoveredHttpMethods());
    context.setDisplayName(webxml.getDisplayName());
    context.setDistributable(webxml.isDistributable());
    for (ContextLocalEjb ejbLocalRef : webxml.getEjbLocalRefs().values()) {
        context.getNamingResources().addLocalEjb(ejbLocalRef);
    }
    for (ContextEjb ejbRef : webxml.getEjbRefs().values()) {
        context.getNamingResources().addEjb(ejbRef);
    }
    for (ContextEnvironment environment : webxml.getEnvEntries().values()) {
        context.getNamingResources().addEnvironment(environment);
    }
    for (ErrorPage errorPage : webxml.getErrorPages().values()) {
        context.addErrorPage(errorPage);
    }
    for (FilterDef filter : webxml.getFilters().values()) {
        if (filter.getAsyncSupported() == null) {
            filter.setAsyncSupported("false");
        }
        context.addFilterDef(filter);
    }
    for (FilterMap filterMap : webxml.getFilterMappings()) {
        context.addFilterMap(filterMap);
    }
    context.setJspConfigDescriptor(webxml.getJspConfigDescriptor());
    for (String listener : webxml.getListeners()) {
        context.addApplicationListener(listener);
    }
    for (Entry<String, String> entry : webxml.getLocaleEncodingMappings().entrySet()) {
        context.addLocaleEncodingMappingParameter(entry.getKey(), entry.getValue());
    }
    // Prevents IAE
    if (webxml.getLoginConfig() != null) {
        context.setLoginConfig(webxml.getLoginConfig());
    }
    for (MessageDestinationRef mdr : webxml.getMessageDestinationRefs().values()) {
        context.getNamingResources().addMessageDestinationRef(mdr);
    }
    // messageDestinations were ignored in Tomcat 6, so ignore here
    context.setIgnoreAnnotations(webxml.isMetadataComplete());
    for (Entry<String, String> entry : webxml.getMimeMappings().entrySet()) {
        context.addMimeMapping(entry.getKey(), entry.getValue());
    }
    context.setRequestCharacterEncoding(webxml.getRequestEncoding());
    // Name is just used for ordering
    for (ContextResourceEnvRef resource : webxml.getResourceEnvRefs().values()) {
        context.getNamingResources().addResourceEnvRef(resource);
    }
    for (ContextResource resource : webxml.getResourceRefs().values()) {
        context.getNamingResources().addResource(resource);
    }
    context.setResponseCharacterEncoding(webxml.getResponseEncoding());
    boolean allAuthenticatedUsersIsAppRole = webxml.getSecurityRoles().contains(SecurityConstraint.ROLE_ALL_AUTHENTICATED_USERS);
    for (SecurityConstraint constraint : webxml.getSecurityConstraints()) {
        if (allAuthenticatedUsersIsAppRole) {
            constraint.treatAllAuthenticatedUsersAsApplicationRole();
        }
        context.addConstraint(constraint);
    }
    for (String role : webxml.getSecurityRoles()) {
        context.addSecurityRole(role);
    }
    for (ContextService service : webxml.getServiceRefs().values()) {
        context.getNamingResources().addService(service);
    }
    for (ServletDef servlet : webxml.getServlets().values()) {
        Wrapper wrapper = context.createWrapper();
        if (servlet.getLoadOnStartup() != null) {
            wrapper.setLoadOnStartup(servlet.getLoadOnStartup().intValue());
        }
        if (servlet.getEnabled() != null) {
            wrapper.setEnabled(servlet.getEnabled().booleanValue());
        }
        wrapper.setName(servlet.getServletName());
        Map<String, String> params = servlet.getParameterMap();
        for (Entry<String, String> entry : params.entrySet()) {
            wrapper.addInitParameter(entry.getKey(), entry.getValue());
        }
        wrapper.setRunAs(servlet.getRunAs());
        Set<SecurityRoleRef> roleRefs = servlet.getSecurityRoleRefs();
        for (SecurityRoleRef roleRef : roleRefs) {
            wrapper.addSecurityReference(roleRef.getName(), roleRef.getLink());
        }
        wrapper.setServletClass(servlet.getServletClass());
        MultipartDef multipartdef = servlet.getMultipartDef();
        if (multipartdef != null) {
            if (multipartdef.getMaxFileSize() != null && multipartdef.getMaxRequestSize() != null && multipartdef.getFileSizeThreshold() != null) {
                wrapper.setMultipartConfigElement(new MultipartConfigElement(multipartdef.getLocation(), Long.parseLong(multipartdef.getMaxFileSize()), Long.parseLong(multipartdef.getMaxRequestSize()), Integer.parseInt(multipartdef.getFileSizeThreshold())));
            } else {
                wrapper.setMultipartConfigElement(new MultipartConfigElement(multipartdef.getLocation()));
            }
        }
        if (servlet.getAsyncSupported() != null) {
            wrapper.setAsyncSupported(servlet.getAsyncSupported().booleanValue());
        }
        wrapper.setOverridable(servlet.isOverridable());
        context.addChild(wrapper);
    }
    for (Entry<String, String> entry : webxml.getServletMappings().entrySet()) {
        context.addServletMappingDecoded(entry.getKey(), entry.getValue());
    }
    SessionConfig sessionConfig = webxml.getSessionConfig();
    if (sessionConfig != null) {
        if (sessionConfig.getSessionTimeout() != null) {
            context.setSessionTimeout(sessionConfig.getSessionTimeout().intValue());
        }
        SessionCookieConfig scc = context.getServletContext().getSessionCookieConfig();
        scc.setName(sessionConfig.getCookieName());
        scc.setDomain(sessionConfig.getCookieDomain());
        scc.setPath(sessionConfig.getCookiePath());
        scc.setComment(sessionConfig.getCookieComment());
        if (sessionConfig.getCookieHttpOnly() != null) {
            scc.setHttpOnly(sessionConfig.getCookieHttpOnly().booleanValue());
        }
        if (sessionConfig.getCookieSecure() != null) {
            scc.setSecure(sessionConfig.getCookieSecure().booleanValue());
        }
        if (sessionConfig.getCookieMaxAge() != null) {
            scc.setMaxAge(sessionConfig.getCookieMaxAge().intValue());
        }
        if (sessionConfig.getSessionTrackingModes().size() > 0) {
            context.getServletContext().setSessionTrackingModes(sessionConfig.getSessionTrackingModes());
        }
    }
    for (String welcomeFile : webxml.getWelcomeFiles()) {
        /*
             * The following will result in a welcome file of "" so don't add
             * that to the context
             * <welcome-file-list>
             *   <welcome-file/>
             * </welcome-file-list>
             */
        if (welcomeFile != null && welcomeFile.length() > 0) {
            context.addWelcomeFile(welcomeFile);
        }
    }
    // Do this last as it depends on servlets
    for (JspPropertyGroup jspPropertyGroup : webxml.getJspPropertyGroups()) {
        String jspServletName = context.findServletMapping("*.jsp");
        if (jspServletName == null) {
            jspServletName = "jsp";
        }
        if (context.findChild(jspServletName) != null) {
            for (String urlPattern : jspPropertyGroup.getUrlPatterns()) {
                context.addServletMappingDecoded(urlPattern, jspServletName, true);
            }
        } else {
            if (log.isDebugEnabled()) {
                for (String urlPattern : jspPropertyGroup.getUrlPatterns()) {
                    log.debug("Skipping " + urlPattern + " , no servlet " + jspServletName);
                }
            }
        }
    }
    for (Entry<String, String> entry : webxml.getPostConstructMethods().entrySet()) {
        context.addPostConstructMethod(entry.getKey(), entry.getValue());
    }
    for (Entry<String, String> entry : webxml.getPreDestroyMethods().entrySet()) {
        context.addPreDestroyMethod(entry.getKey(), entry.getValue());
    }
}
Also used : ContextEnvironment(org.apache.tomcat.util.descriptor.web.ContextEnvironment) Wrapper(org.apache.catalina.Wrapper) ContextService(org.apache.tomcat.util.descriptor.web.ContextService) ErrorPage(org.apache.tomcat.util.descriptor.web.ErrorPage) FilterDef(org.apache.tomcat.util.descriptor.web.FilterDef) ServletDef(org.apache.tomcat.util.descriptor.web.ServletDef) SessionConfig(org.apache.tomcat.util.descriptor.web.SessionConfig) SecurityRoleRef(org.apache.tomcat.util.descriptor.web.SecurityRoleRef) ContextEjb(org.apache.tomcat.util.descriptor.web.ContextEjb) FilterMap(org.apache.tomcat.util.descriptor.web.FilterMap) SecurityConstraint(org.apache.tomcat.util.descriptor.web.SecurityConstraint) ContextResource(org.apache.tomcat.util.descriptor.web.ContextResource) JspPropertyGroup(org.apache.tomcat.util.descriptor.web.JspPropertyGroup) MessageDestinationRef(org.apache.tomcat.util.descriptor.web.MessageDestinationRef) MultipartConfigElement(javax.servlet.MultipartConfigElement) ContextLocalEjb(org.apache.tomcat.util.descriptor.web.ContextLocalEjb) MultipartDef(org.apache.tomcat.util.descriptor.web.MultipartDef) SessionCookieConfig(javax.servlet.SessionCookieConfig) ContextResourceEnvRef(org.apache.tomcat.util.descriptor.web.ContextResourceEnvRef)

Aggregations

ErrorPage (org.apache.tomcat.util.descriptor.web.ErrorPage)15 Context (org.apache.catalina.Context)11 Tomcat (org.apache.catalina.startup.Tomcat)8 TomcatBaseTest (org.apache.catalina.startup.TomcatBaseTest)6 ByteChunk (org.apache.tomcat.util.buf.ByteChunk)6 Test (org.junit.Test)6 Wrapper (org.apache.catalina.Wrapper)5 SecurityConstraint (org.apache.tomcat.util.descriptor.web.SecurityConstraint)4 IOException (java.io.IOException)3 AsyncContext (javax.servlet.AsyncContext)3 TesterContext (org.apache.tomcat.unittest.TesterContext)3 ServletContext (javax.servlet.ServletContext)2 ServletRequestWrapper (javax.servlet.ServletRequestWrapper)2 ServletResponseWrapper (javax.servlet.ServletResponseWrapper)2 ClientAbortException (org.apache.catalina.connector.ClientAbortException)2 TesterAccessLogValve (org.apache.catalina.valves.TesterAccessLogValve)2 FilterDef (org.apache.tomcat.util.descriptor.web.FilterDef)2 FilterMap (org.apache.tomcat.util.descriptor.web.FilterMap)2 File (java.io.File)1 MultipartConfigElement (javax.servlet.MultipartConfigElement)1