Java Code Examples for org.apache.catalina.Context#addErrorPage()

The following examples show how to use org.apache.catalina.Context#addErrorPage() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TestAsyncContextImpl.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example 2
Source File: DebugTomcat.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    setupDebugEnv();

    int port = 7070;
    if (args.length >= 1) {
        port = Integer.parseInt(args[0]);
    }

    File webBase = new File("../webapp/app");
    File webInfDir = new File(webBase, "WEB-INF");
    FileUtils.deleteDirectory(webInfDir);
    FileUtils.copyDirectoryToDirectory(new File("../server/src/main/webapp/WEB-INF"), webBase);

    Tomcat tomcat = new Tomcat();
    tomcat.setPort(port);
    tomcat.setBaseDir(".");

    // Add AprLifecycleListener
    StandardServer server = (StandardServer) tomcat.getServer();
    AprLifecycleListener listener = new AprLifecycleListener();
    server.addLifecycleListener(listener);

    Context webContext = tomcat.addWebapp("/kylin", webBase.getAbsolutePath());
    ErrorPage notFound = new ErrorPage();
    notFound.setErrorCode(404);
    notFound.setLocation("/index.html");
    webContext.addErrorPage(notFound);
    webContext.addWelcomeFile("index.html");

    // tomcat start
    tomcat.start();
    tomcat.getServer().await();
}
 
Example 3
Source File: TestStandardHostValve.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@Test(expected=IllegalArgumentException.class)
public void testInvalidErrorPage() throws Exception {
    // Set up a container
    Tomcat tomcat = getTomcatInstance();

    // No file system docBase required
    Context ctx = tomcat.addContext("", null);

    // Add a broken error page configuration
    ErrorPage errorPage500 = new ErrorPage();
    errorPage500.setErrorCode("java.lang.Exception");
    errorPage500.setLocation("/report/500");
    ctx.addErrorPage(errorPage500);
}
 
Example 4
Source File: TestStandardHostValve.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@Test
public void testErrorPageHandling() throws Exception {
    // Set up a container
    Tomcat tomcat = getTomcatInstance();

    // No file system docBase required
    Context ctx = tomcat.addContext("", null);

    // Add the error page
    Tomcat.addServlet(ctx, "error", new ErrorServlet());
    ctx.addServletMapping("/error", "error");

    // Add the error handling page
    Tomcat.addServlet(ctx, "report", new ReportServlet());
    ctx.addServletMapping("/report/*", "report");

    // And the handling for 500 responses
    ErrorPage errorPage500 = new ErrorPage();
    errorPage500.setErrorCode(Response.SC_INTERNAL_SERVER_ERROR);
    errorPage500.setLocation("/report/500");
    ctx.addErrorPage(errorPage500);

    // And the default error handling
    ErrorPage errorPageDefault = new ErrorPage();
    errorPageDefault.setLocation("/report/default");
    ctx.addErrorPage(errorPageDefault);

    tomcat.start();

    doTestErrorPageHandling(500, "/500");
    doTestErrorPageHandling(501, "/default");
}
 
Example 5
Source File: MdwServletContainerFactory.java    From mdw with Apache License 2.0 5 votes vote down vote up
@Override
public void customize(Context context) {
    context.addApplicationListener("org.apache.tomcat.websocket.server.WsContextListener");
    context.addErrorPage(new ErrorPage() {
        @Override
        public int getErrorCode() {
            return 404;
        }

        @Override
        public String getLocation() {
            return "/404";
        }
    });
    context.addErrorPage(new ErrorPage() {
        @Override
        public int getErrorCode() {
            return 500;
        }

        @Override
        public String getLocation() {
            return "/error";
        }
    });

    // CORS access is wide open
    FilterDef corsFilter = new FilterDef();
    corsFilter.setFilterName("CorsFilter");
    corsFilter.setFilterClass("org.apache.catalina.filters.CorsFilter");
    corsFilter.addInitParameter("cors.allowed.methods", "GET,POST,PUT,DELETE,HEAD,OPTIONS");
    corsFilter.addInitParameter("cors.allowed.headers", "Authorization,Content-Type,X-Requested-With,Accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,Accept-Encoding,Accept-Language,Cache-Control,Connection,Host,Pragma,Referer,User-Agent");
    corsFilter.addInitParameter("cors.allowed.origins", "*");
    context.addFilterDef(corsFilter);
    FilterMap filterMap = new FilterMap();
    filterMap.setFilterName(corsFilter.getFilterName());
    filterMap.addURLPattern("/api/*");
    filterMap.addURLPattern("/services/AppSummary");
    context.addFilterMap(filterMap);
}
 
Example 6
Source File: TestStandardHostValve.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
@Test
public void testErrorPageHandling() throws Exception {
    // Set up a container
    Tomcat tomcat = getTomcatInstance();

    // No file system docBase required
    Context ctx = tomcat.addContext("", null);

    // Add the error page
    Tomcat.addServlet(ctx, "error", new ErrorServlet());
    ctx.addServletMapping("/error", "error");

    // Add the error handling page
    Tomcat.addServlet(ctx, "report", new ReportServlet());
    ctx.addServletMapping("/report/*", "report");

    // And the handling for 500 responses
    ErrorPage errorPage500 = new ErrorPage();
    errorPage500.setErrorCode(Response.SC_INTERNAL_SERVER_ERROR);
    errorPage500.setLocation("/report/500");
    ctx.addErrorPage(errorPage500);

    // And the default error handling
    ErrorPage errorPageDefault = new ErrorPage();
    errorPageDefault.setLocation("/report/default");
    ctx.addErrorPage(errorPageDefault);

    tomcat.start();

    doTestErrorPageHandling(500, "/500");
    doTestErrorPageHandling(501, "/default");
}
 
Example 7
Source File: DebugTomcat.java    From kylin with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    setupDebugEnv();

    int port = 7070;
    if (args.length >= 1) {
        port = Integer.parseInt(args[0]);
    }

    File webBase = new File("../webapp/app");
    File webInfDir = new File(webBase, "WEB-INF");
    FileUtils.deleteDirectory(webInfDir);
    FileUtils.copyDirectoryToDirectory(new File("../server/src/main/webapp/WEB-INF"), webBase);

    Tomcat tomcat = new Tomcat();
    tomcat.setPort(port);
    tomcat.setBaseDir(".");

    // Add AprLifecycleListener
    StandardServer server = (StandardServer) tomcat.getServer();
    AprLifecycleListener listener = new AprLifecycleListener();
    server.addLifecycleListener(listener);

    Context webContext = tomcat.addWebapp("/kylin", webBase.getAbsolutePath());
    ErrorPage notFound = new ErrorPage();
    notFound.setErrorCode(404);
    notFound.setLocation("/index.html");
    webContext.addErrorPage(notFound);
    webContext.addWelcomeFile("index.html");

    // tomcat start
    tomcat.start();
    tomcat.getServer().await();
}
 
Example 8
Source File: TestStandardHostValve.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Test(expected=IllegalArgumentException.class)
public void testInvalidErrorPage() throws Exception {
    // Set up a container
    Tomcat tomcat = getTomcatInstance();

    // No file system docBase required
    Context ctx = tomcat.addContext("", null);

    // Add a broken error page configuration
    ErrorPage errorPage500 = new ErrorPage();
    errorPage500.setErrorCode("java.lang.Exception");
    errorPage500.setLocation("/report/500");
    ctx.addErrorPage(errorPage500);
}
 
Example 9
Source File: TestStandardHostValve.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Test
public void testErrorPageHandling() throws Exception {
    // Set up a container
    Tomcat tomcat = getTomcatInstance();

    // No file system docBase required
    Context ctx = tomcat.addContext("", null);

    // Add the error page
    Tomcat.addServlet(ctx, "error", new ErrorServlet());
    ctx.addServletMappingDecoded("/error", "error");

    // Add the error handling page
    Tomcat.addServlet(ctx, "report", new ReportServlet());
    ctx.addServletMappingDecoded("/report/*", "report");

    // And the handling for 500 responses
    ErrorPage errorPage500 = new ErrorPage();
    errorPage500.setErrorCode(Response.SC_INTERNAL_SERVER_ERROR);
    errorPage500.setLocation("/report/500");
    ctx.addErrorPage(errorPage500);

    // And the default error handling
    ErrorPage errorPageDefault = new ErrorPage();
    errorPageDefault.setLocation("/report/default");
    ctx.addErrorPage(errorPageDefault);

    tomcat.start();

    doTestErrorPageHandling(500, "/500");
    doTestErrorPageHandling(501, "/default");
}
 
Example 10
Source File: TestAsyncContextImpl.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
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);
}
 
Example 11
Source File: TestAsyncContextImpl.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
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);

    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);
}
 
Example 12
Source File: TestHttpServletResponseSendError.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
@Test
public void testSendError() throws Exception {
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();

    // No file system docBase required
    Context ctx = tomcat.addContext("", null);

    if (async) {
        Wrapper w = Tomcat.addServlet(ctx, "target",
                new TesterAsyncServlet(throwException, useDispatch, errorPoint, useStart));
        w.setAsyncSupported(true);
    } else {
        Tomcat.addServlet(ctx, "target", new TesterServlet(throwException));
    }
    ctx.addServletMappingDecoded("/target", "target");
    Tomcat.addServlet(ctx, "dispatch", new TesterDispatchServlet());
    ctx.addServletMappingDecoded("/dispatch", "dispatch");

    Tomcat.addServlet(ctx, "error599", new ErrorServletStatic599());
    ctx.addServletMappingDecoded("/error599", "error599");
    Tomcat.addServlet(ctx, "errorException", new ErrorServletStaticException());
    ctx.addServletMappingDecoded("/errorException", "errorException");

    ErrorPage ep1 = new ErrorPage();
    ep1.setErrorCode(599);
    ep1.setLocation("/error599");
    ctx.addErrorPage(ep1);

    ErrorPage ep2 = new ErrorPage();
    ep2.setExceptionType(SendErrorException.class.getName());
    ep2.setLocation("/errorException");
    ctx.addErrorPage(ep2);

    tomcat.start();

    ByteChunk bc = new ByteChunk();
    int rc;

    rc = getUrl("http://localhost:" + getPort() + "/target", bc, null, null);

    String body = bc.toString();

    if (throwException) {
        Assert.assertEquals(500, rc);
        Assert.assertEquals("FAIL-Exception", body);
    } else {
        Assert.assertEquals(599, rc);
        Assert.assertEquals("FAIL-599", body);
    }
}
 
Example 13
Source File: TestDefaultServlet.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
@Test
public void testCustomErrorPage() throws Exception {

    Tomcat tomcat = getTomcatInstance();

    File appDir = new File("test/webapp");

    // app dir is relative to server home
    Context ctxt = tomcat.addContext("", appDir.getAbsolutePath());
    Wrapper defaultServlet = Tomcat.addServlet(ctxt, "default",
            DefaultServlet.class.getName());
    defaultServlet.addInitParameter("fileEncoding", "ISO-8859-1");

    ctxt.addServletMappingDecoded("/", "default");
    ctxt.addMimeMapping("html", "text/html");
    ErrorPage ep = new ErrorPage();
    ep.setErrorCode(404);
    ep.setLocation("/404.html");
    ctxt.addErrorPage(ep);

    tomcat.start();

    TestCustomErrorClient client =
            new TestCustomErrorClient(tomcat.getConnector().getLocalPort());

    client.reset();
    client.setRequest(new String[] {
            "GET /MyApp/missing HTTP/1.0" +CRLF + CRLF });
    client.connect();
    client.processRequest();
    Assert.assertTrue(client.isResponse404());
    Assert.assertEquals("It is 404.html", client.getResponseBody());

    SimpleDateFormat format = new SimpleDateFormat(
            "EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US);
    format.setTimeZone(TimeZone.getTimeZone("GMT"));
    String tomorrow = format.format(new Date(System.currentTimeMillis()
            + 24 * 60 * 60 * 1000));

    // https://bz.apache.org/bugzilla/show_bug.cgi?id=50413
    //
    client.reset();
    client.setRequest(new String[] {
            "GET /MyApp/missing HTTP/1.1" + CRLF +
            "Host: localhost" + CRLF +
            "Connection: close" + CRLF +
            "If-Modified-Since: " + tomorrow + CRLF + CRLF });
    client.connect();
    client.processRequest();
    Assert.assertTrue(client.isResponse404());
    Assert.assertEquals("It is 404.html", client.getResponseBody());

    // https://bz.apache.org/bugzilla/show_bug.cgi?id=50413#c6
    //
    client.reset();
    client.setRequest(new String[] {
            "GET /MyApp/missing HTTP/1.1" + CRLF +
            "Host: localhost" + CRLF +
            "Connection: close" + CRLF +
            "Range: bytes=0-100" + CRLF + CRLF });
    client.connect();
    client.processRequest();
    Assert.assertTrue(client.isResponse404());
    Assert.assertEquals("It is 404.html", client.getResponseBody());
}
 
Example 14
Source File: TestStandardContextValve.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
@Test
public void testBug51653a() throws Exception {
    // Set up a container
    Tomcat tomcat = getTomcatInstance();

    // No file system docBase required
    Context ctx = tomcat.addContext("", null);

    // Traces order of events across multiple components
    StringBuilder trace = new StringBuilder();

    //Add the error page
    Tomcat.addServlet(ctx, "errorPage", new Bug51653ErrorPage(trace));
    ctx.addServletMapping("/error", "errorPage");
    // And the handling for 404 responses
    ErrorPage errorPage = new ErrorPage();
    errorPage.setErrorCode(Response.SC_NOT_FOUND);
    errorPage.setLocation("/error");
    ctx.addErrorPage(errorPage);

    // Add the request listener
    Bug51653RequestListener reqListener =
        new Bug51653RequestListener(trace);
    ((StandardContext) ctx).addApplicationEventListener(reqListener);

    tomcat.start();

    // Request a page that does not exist
    int rc = getUrl("http://localhost:" + getPort() + "/invalid",
            new ByteChunk(), null);

    // Need to allow time (but not too long in case the test fails) for
    // ServletRequestListener to complete
    int i = 20;
    while (i > 0) {
        if (trace.toString().endsWith("Destroy")) {
            break;
        }
        Thread.sleep(250);
        i--;
    }

    assertEquals(Response.SC_NOT_FOUND, rc);
    assertEquals("InitErrorDestroy", trace.toString());
}
 
Example 15
Source File: TestStandardContextValve.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
@Test
public void testBug51653b() throws Exception {
    // Set up a container
    Tomcat tomcat = getTomcatInstance();

    // No file system docBase required
    Context ctx = tomcat.addContext("", null);

    // Traces order of events across multiple components
    StringBuilder trace = new StringBuilder();

    // Add the page that generates the error
    Tomcat.addServlet(ctx, "test", new Bug51653ErrorTrigger());
    ctx.addServletMapping("/test", "test");

    // Add the error page
    Tomcat.addServlet(ctx, "errorPage", new Bug51653ErrorPage(trace));
    ctx.addServletMapping("/error", "errorPage");
    // And the handling for 404 responses
    ErrorPage errorPage = new ErrorPage();
    errorPage.setErrorCode(Response.SC_NOT_FOUND);
    errorPage.setLocation("/error");
    ctx.addErrorPage(errorPage);

    // Add the request listener
    Bug51653RequestListener reqListener =
        new Bug51653RequestListener(trace);
    ((StandardContext) ctx).addApplicationEventListener(reqListener);

    tomcat.start();

    // Request a page that does not exist
    int rc = getUrl("http://localhost:" + getPort() + "/test",
            new ByteChunk(), null);

    // Need to allow time (but not too long in case the test fails) for
    // ServletRequestListener to complete
    int i = 20;
    while (i > 0) {
        if (trace.toString().endsWith("Destroy")) {
            break;
        }
        Thread.sleep(250);
        i--;
    }

    assertEquals(Response.SC_NOT_FOUND, rc);
    assertEquals("InitErrorDestroy", trace.toString());
}
 
Example 16
Source File: TestAsyncContextImpl.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
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);
}
 
Example 17
Source File: TestStandardContextValve.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
@Test
public void testBug51653a() throws Exception {
    // Set up a container
    Tomcat tomcat = getTomcatInstance();

    // No file system docBase required
    Context ctx = tomcat.addContext("", null);

    // Traces order of events across multiple components
    StringBuilder trace = new StringBuilder();

    //Add the error page
    Tomcat.addServlet(ctx, "errorPage", new Bug51653ErrorPage(trace));
    ctx.addServletMapping("/error", "errorPage");
    // And the handling for 404 responses
    ErrorPage errorPage = new ErrorPage();
    errorPage.setErrorCode(Response.SC_NOT_FOUND);
    errorPage.setLocation("/error");
    ctx.addErrorPage(errorPage);

    // Add the request listener
    Bug51653RequestListener reqListener =
        new Bug51653RequestListener(trace);
    ((StandardContext) ctx).addApplicationEventListener(reqListener);

    tomcat.start();

    // Request a page that does not exist
    int rc = getUrl("http://localhost:" + getPort() + "/invalid",
            new ByteChunk(), null);

    // Need to allow time (but not too long in case the test fails) for
    // ServletRequestListener to complete
    int i = 20;
    while (i > 0) {
        if (trace.toString().endsWith("Destroy")) {
            break;
        }
        Thread.sleep(250);
        i--;
    }

    assertEquals(Response.SC_NOT_FOUND, rc);
    assertEquals("InitErrorDestroy", trace.toString());
}
 
Example 18
Source File: TestStandardContextValve.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
@Test
public void testBug51653b() throws Exception {
    // Set up a container
    Tomcat tomcat = getTomcatInstance();

    // No file system docBase required
    Context ctx = tomcat.addContext("", null);

    // Traces order of events across multiple components
    StringBuilder trace = new StringBuilder();

    // Add the page that generates the error
    Tomcat.addServlet(ctx, "test", new Bug51653ErrorTrigger());
    ctx.addServletMapping("/test", "test");

    // Add the error page
    Tomcat.addServlet(ctx, "errorPage", new Bug51653ErrorPage(trace));
    ctx.addServletMapping("/error", "errorPage");
    // And the handling for 404 responses
    ErrorPage errorPage = new ErrorPage();
    errorPage.setErrorCode(Response.SC_NOT_FOUND);
    errorPage.setLocation("/error");
    ctx.addErrorPage(errorPage);

    // Add the request listener
    Bug51653RequestListener reqListener =
        new Bug51653RequestListener(trace);
    ((StandardContext) ctx).addApplicationEventListener(reqListener);

    tomcat.start();

    // Request a page that does not exist
    int rc = getUrl("http://localhost:" + getPort() + "/test",
            new ByteChunk(), null);

    // Need to allow time (but not too long in case the test fails) for
    // ServletRequestListener to complete
    int i = 20;
    while (i > 0) {
        if (trace.toString().endsWith("Destroy")) {
            break;
        }
        Thread.sleep(250);
        i--;
    }

    assertEquals(Response.SC_NOT_FOUND, rc);
    assertEquals("InitErrorDestroy", trace.toString());
}
 
Example 19
Source File: TestStandardContextValve.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
@Test
public void testBug51653b() throws Exception {
    // Set up a container
    Tomcat tomcat = getTomcatInstance();

    // No file system docBase required
    Context ctx = tomcat.addContext("", null);

    // Traces order of events across multiple components
    StringBuilder trace = new StringBuilder();

    // Add the page that generates the error
    Tomcat.addServlet(ctx, "test", new Bug51653ErrorTrigger());
    ctx.addServletMappingDecoded("/test", "test");

    // Add the error page
    Tomcat.addServlet(ctx, "errorPage", new Bug51653ErrorPage(trace));
    ctx.addServletMappingDecoded("/error", "errorPage");
    // And the handling for 404 responses
    ErrorPage errorPage = new ErrorPage();
    errorPage.setErrorCode(Response.SC_NOT_FOUND);
    errorPage.setLocation("/error");
    ctx.addErrorPage(errorPage);

    // Add the request listener
    Bug51653RequestListener reqListener =
        new Bug51653RequestListener(trace);
    ((StandardContext) ctx).addApplicationEventListener(reqListener);

    tomcat.start();

    // Request a page that does not exist
    int rc = getUrl("http://localhost:" + getPort() + "/test",
            new ByteChunk(), null);

    // Need to allow time (but not too long in case the test fails) for
    // ServletRequestListener to complete
    int i = 20;
    while (i > 0) {
        if (trace.toString().endsWith("Destroy")) {
            break;
        }
        Thread.sleep(250);
        i--;
    }

    Assert.assertEquals(Response.SC_NOT_FOUND, rc);
    Assert.assertEquals("InitErrorDestroy", trace.toString());
}
 
Example 20
Source File: TestAsyncContextImpl.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
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);
}