Java Code Examples for org.apache.catalina.Wrapper#setAsyncSupported()

The following examples show how to use org.apache.catalina.Wrapper#setAsyncSupported() . 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 Tomcat8-Source-Read with MIT License 6 votes vote down vote up
private void doTestBug59219(String queryString, String expectedTrack) throws Exception {
    resetTracker();
    Tomcat tomcat = getTomcatInstance();

    Context ctx = tomcat.addContext("", null);
    Bug59219Servlet bug59219Servlet = new Bug59219Servlet();
    Wrapper w = tomcat.addServlet("", "async", bug59219Servlet);
    w.setAsyncSupported(true);
    ctx.addServletMappingDecoded("/async", "async");

    tomcat.start();

    getUrl("http://localhost:" + getPort() + "/async" + queryString);

    // Wait up to 5s for the response
    int count = 0;
    while(!expectedTrack.equals(getTrack()) && count < 100) {
        Thread.sleep(50);
        count++;
    }

    Assert.assertEquals(expectedTrack, getTrack());
}
 
Example 2
Source File: ExploreSpring5URLPatternUsingRouterFunctions.java    From tutorials with MIT License 6 votes vote down vote up
WebServer start() throws Exception {
    WebHandler webHandler = (WebHandler) toHttpHandler(routingFunction());
    HttpHandler httpHandler = WebHttpHandlerBuilder.webHandler(webHandler)
        .filter(new IndexRewriteFilter())
        .build();

    Tomcat tomcat = new Tomcat();
    tomcat.setHostname("localhost");
    tomcat.setPort(9090);
    Context rootContext = tomcat.addContext("", System.getProperty("java.io.tmpdir"));
    ServletHttpHandlerAdapter servlet = new ServletHttpHandlerAdapter(httpHandler);
    Wrapper servletWrapper = Tomcat.addServlet(rootContext, "httpHandlerServlet", servlet);
    servletWrapper.setAsyncSupported(true);
    rootContext.addServletMappingDecoded("/", "httpHandlerServlet");

    TomcatWebServer server = new TomcatWebServer(tomcat);
    server.start();
    return server;

}
 
Example 3
Source File: TestAsyncContextImpl.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
private void prepareApplicationWithGenericServlet(String contextPath)
        throws Exception {
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();

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

    DispatchingGenericServlet dispatch = new DispatchingGenericServlet();
    Wrapper wrapper = Tomcat.addServlet(ctx, "dispatch", dispatch);
    wrapper.setAsyncSupported(true);
    ctx.addServletMapping("/dispatch", "dispatch");

    CustomGenericServlet customGeneric = new CustomGenericServlet();
    Wrapper wrapper2 = Tomcat.addServlet(ctx, "customGeneric",
            customGeneric);
    wrapper2.setAsyncSupported(true);
    ctx.addServletMapping("/target", "customGeneric");

    tomcat.start();
}
 
Example 4
Source File: TestAsyncContextImpl.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
@Test
public void testCommitOnComplete() throws Exception {
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();

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

    AsyncStatusServlet asyncStatusServlet =
        new AsyncStatusServlet(HttpServletResponse.SC_BAD_REQUEST);
    Wrapper wrapper =
        Tomcat.addServlet(ctx, "asyncStatusServlet", asyncStatusServlet);
    wrapper.setAsyncSupported(true);
    ctx.addServletMapping("/asyncStatusServlet", "asyncStatusServlet");

    TesterAccessLogValve alv = new TesterAccessLogValve();
    ctx.getPipeline().addValve(alv);

    tomcat.start();

    StringBuilder url = new StringBuilder(48);
    url.append("http://localhost:");
    url.append(getPort());
    url.append("/asyncStatusServlet");

    int rc = getUrl(url.toString(), new ByteChunk(), null);

    assertEquals(HttpServletResponse.SC_BAD_REQUEST, rc);

    // 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 5
Source File: TestApplicationContextGetRequestDispatcherB.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Test
public void doTest() throws Exception {

    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();

    // No file system docBase required
    Context ctx = tomcat.addContext("/test", null);
    ctx.setDispatchersUseEncodedPaths(useEncodedDispatchPaths);
    ctx.addWelcomeFile("index.html");

    // Add a target servlet to dispatch to
    Tomcat.addServlet(ctx, "target", new Target());
    ctx.addServletMappingDecoded(targetMapping, "target");

    Wrapper w = Tomcat.addServlet(ctx, "rd", new Dispatch());
    w.setAsyncSupported(true);
    ctx.addServletMappingDecoded(startMapping, "rd");

    tomcat.start();

    StringBuilder url = new StringBuilder("http://localhost:");
    url.append(getPort());
    url.append("/test");
    url.append(startUri);

    ByteChunk bc = getUrl(url.toString());
    String body = bc.toString();

    Assert.assertEquals(expectedBody, body);
}
 
Example 6
Source File: TestAsyncContextImpl.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@Test
public void testBug53337() throws Exception {
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();

    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    Wrapper a = Tomcat.addServlet(ctx, "ServletA", new Bug53337ServletA());
    a.setAsyncSupported(true);
    Wrapper b = Tomcat.addServlet(ctx, "ServletB", new Bug53337ServletB());
    b.setAsyncSupported(true);
    Tomcat.addServlet(ctx, "ServletC", new Bug53337ServletC());
    ctx.addServletMapping("/ServletA", "ServletA");
    ctx.addServletMapping("/ServletB", "ServletB");
    ctx.addServletMapping("/ServletC", "ServletC");

    tomcat.start();

    StringBuilder url = new StringBuilder(48);
    url.append("http://localhost:");
    url.append(getPort());
    url.append("/ServletA");

    ByteChunk body = new ByteChunk();
    int rc = getUrl(url.toString(), body, null);

    assertEquals(HttpServletResponse.SC_OK, rc);
    assertEquals("OK", body.toString());
}
 
Example 7
Source File: TestApplicationMapping.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
private void doTestMappingAsync(String contextPath, String mapping, String requestPath,
        String matchValue, String matchType) throws Exception {
    Tomcat tomcat = getTomcatInstance();

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

    Wrapper w = Tomcat.addServlet(ctx, "Async", new AsyncServlet());
    w.setAsyncSupported(true);
    ctx.addServletMappingDecoded(mapping, "Async");
    Tomcat.addServlet(ctx, "Mapping", new MappingServlet());
    ctx.addServletMappingDecoded("/mapping", "Mapping");

    tomcat.start();

    ByteChunk bc = getUrl("http://localhost:" + getPort() + contextPath + requestPath);
    String body = bc.toString();

    Assert.assertTrue(body, body.contains("MatchValue=[mapping]"));
    Assert.assertTrue(body, body.contains("Pattern=[/mapping]"));
    Assert.assertTrue(body, body.contains("MatchType=[EXACT]"));
    Assert.assertTrue(body, body.contains("ServletName=[Mapping]"));

    Assert.assertTrue(body, body.contains("AsyncMatchValue=[" + matchValue + "]"));
    Assert.assertTrue(body, body.contains("AsyncPattern=[" + mapping + "]"));
    Assert.assertTrue(body, body.contains("AsyncMatchType=[" + matchType + "]"));
    Assert.assertTrue(body, body.contains("AsyncServletName=[Async]"));
}
 
Example 8
Source File: TestAsyncContextImpl.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@Test
public void testBug49567() throws Exception {
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();

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

    Bug49567Servlet servlet = new Bug49567Servlet();

    Wrapper wrapper = Tomcat.addServlet(ctx, "servlet", servlet);
    wrapper.setAsyncSupported(true);
    ctx.addServletMapping("/", "servlet");

    TesterAccessLogValve alv = new TesterAccessLogValve();
    ctx.getPipeline().addValve(alv);

    tomcat.start();

    // Call the servlet once
    ByteChunk bc = getUrl("http://localhost:" + getPort() + "/");
    assertEquals("OK", bc.toString());

    // Give the async thread a chance to finish (but not too long)
    int counter = 0;
    while (!servlet.isDone() && counter < 10) {
        Thread.sleep(1000);
        counter++;
    }

    assertEquals("1false2true3true4true5false", servlet.getResult());

    // Check the access log
    alv.validateAccessLog(1, 200, Bug49567Servlet.THREAD_SLEEP_TIME,
            Bug49567Servlet.THREAD_SLEEP_TIME + REQUEST_TIME);
}
 
Example 9
Source File: TestAsyncContextImpl.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@Test
public void testAsyncContextListenerClearing() throws Exception {
    resetTracker();

    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();

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

    Servlet stage1 = new DispatchingServletTracking("/stage2", true);
    Wrapper wrapper1 = Tomcat.addServlet(ctx, "stage1", stage1);
    wrapper1.setAsyncSupported(true);
    ctx.addServletMapping("/stage1", "stage1");

    Servlet stage2 = new DispatchingServletTracking("/stage3", false);
    Wrapper wrapper2 = Tomcat.addServlet(ctx, "stage2", stage2);
    wrapper2.setAsyncSupported(true);
    ctx.addServletMapping("/stage2", "stage2");

    Servlet stage3 = new NonAsyncServlet();
    Tomcat.addServlet(ctx, "stage3", stage3);
    ctx.addServletMapping("/stage3", "stage3");

    TesterAccessLogValve alv = new TesterAccessLogValve();
    ctx.getPipeline().addValve(alv);

    tomcat.start();

    getUrl("http://localhost:" + getPort()+ "/stage1");

    assertEquals("doGet-startAsync-doGet-startAsync-onStartAsync-NonAsyncServletGet-onComplete-", getTrack());

    // Check the access log
    alv.validateAccessLog(1, 200, 0, REQUEST_TIME);
}
 
Example 10
Source File: TestAsyncContextImpl.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
@Test
public void testAsyncStartNoComplete() throws Exception {
    resetTracker();
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();

    // Minimise pauses during test
    tomcat.getConnector().setAttribute(
            "connectionTimeout", Integer.valueOf(3000));

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

    AsyncStartNoCompleteServlet servlet =
        new AsyncStartNoCompleteServlet();

    Wrapper wrapper = Tomcat.addServlet(ctx, "servlet", servlet);
    wrapper.setAsyncSupported(true);
    ctx.addServletMapping("/", "servlet");

    TesterAccessLogValve alv = new TesterAccessLogValve();
    ctx.getPipeline().addValve(alv);

    tomcat.start();

    // Call the servlet the first time
    getUrl("http://localhost:" + getPort() + "/?echo=run1");
    Assert.assertEquals("OK-run1", getTrack());
    resetTracker();

    // Call the servlet the second time with a request parameter
    getUrl("http://localhost:" + getPort() + "/?echo=run2");
    Assert.assertEquals("OK-run2", getTrack());

    // Request may complete before listener has finished processing so wait
    // up to 5 seconds for the right response

    // Check the access log
    alv.validateAccessLog(2, 500,
            AsyncStartNoCompleteServlet.ASYNC_TIMEOUT,
            AsyncStartNoCompleteServlet.ASYNC_TIMEOUT + TIMEOUT_MARGIN +
                    REQUEST_TIME);
}
 
Example 11
Source File: TestAsyncFlush.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
@Test
public void testFlush() throws Exception {
    int blockCount = 2048;

    int targetSize = BLOCK_SIZE * blockCount;

    int totalWindow = ConnectionSettingsBase.DEFAULT_INITIAL_WINDOW_SIZE;

    enableHttp2();

    Tomcat tomcat = getTomcatInstance();

    Context ctxt = tomcat.addContext("", null);
    Tomcat.addServlet(ctxt, "simple", new SimpleServlet());
    ctxt.addServletMappingDecoded("/simple", "simple");
    Wrapper w = Tomcat.addServlet(ctxt, "async", new AsyncFlushServlet(blockCount));
    w.setAsyncSupported(true);
    ctxt.addServletMappingDecoded("/async", "async");
    tomcat.start();

    openClientConnection();
    doHttpUpgrade();
    sendClientPreface();
    validateHttp2InitialResponse();

    // Reset connection window size after intial response
    sendWindowUpdate(0, SimpleServlet.CONTENT_LENGTH);

    // Send request
    byte[] frameHeader = new byte[9];
    ByteBuffer headersPayload = ByteBuffer.allocate(128);
    buildGetRequest(frameHeader, headersPayload, null, 3, "/async");
    writeFrame(frameHeader, headersPayload);

    // Headers
    parser.readFrame(true);
    // Body

    while (output.getBytesRead() < targetSize ) {
        if (output.getBytesRead() == totalWindow) {
            sendWindowUpdate(3, ConnectionSettingsBase.DEFAULT_INITIAL_WINDOW_SIZE);
            sendWindowUpdate(0, ConnectionSettingsBase.DEFAULT_INITIAL_WINDOW_SIZE);
            totalWindow += ConnectionSettingsBase.DEFAULT_INITIAL_WINDOW_SIZE;
        }
        parser.readFrame(true);
    }

    // Check that the right number of bytes were received
    Assert.assertEquals(targetSize, output.getBytesRead());
}
 
Example 12
Source File: TestCoyoteAdapter.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
@Test
public void testBug54928() throws Exception {
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();

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

    AsyncServlet servlet = new AsyncServlet();
    Wrapper w = Tomcat.addServlet(ctx, "async", servlet);
    w.setAsyncSupported(true);
    ctx.addServletMapping("/async", "async");

    tomcat.start();

    SimpleHttpClient client = new SimpleHttpClient() {
        @Override
        public boolean isResponseBodyOK() {
            return true;
        }
    };

    String request = "GET /async HTTP/1.1" + SimpleHttpClient.CRLF +
            "Host: a" + SimpleHttpClient.CRLF + SimpleHttpClient.CRLF;

    client.setPort(getPort());
    client.setRequest(new String[] {request});

    client.connect();
    client.sendRequest();

    for (int i = 0; i < 10; i++) {
        String line = client.readLine();
        if (line != null && line.length() > 20) {
            log.info(line.subSequence(0, 20) + "...");
        }
    }

    client.disconnect();

    // Wait for server thread to stop
    Thread t = servlet.getThread();
    long startTime = System.nanoTime();
    t.join(5000);
    long endTime = System.nanoTime();
    log.info("Waited for servlet thread to stop for "
            + (endTime - startTime) / 1000000 + " ms");

    Assert.assertTrue(servlet.isCompleted());
}
 
Example 13
Source File: TestAsyncContextImpl.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
@Test
public void testDispatchFromOtherContainerThread() throws Exception {
    resetTracker();
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();

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

    NonAsyncServlet nonAsyncServlet = new NonAsyncServlet();
    Tomcat.addServlet(ctx, "nonAsyncServlet", nonAsyncServlet);
    ctx.addServletMappingDecoded("/target", "nonAsyncServlet");

    AsyncStashServlet asyncStashServlet = new AsyncStashServlet();
    Wrapper w1 = Tomcat.addServlet(ctx, "asyncStashServlet", asyncStashServlet);
    w1.setAsyncSupported(true);
    ctx.addServletMappingDecoded("/asyncStashServlet", "asyncStashServlet");

    AsyncRetrieveServlet asyncRetrieveServlet = new AsyncRetrieveServlet();
    Wrapper w2 = Tomcat.addServlet(ctx, "asyncRetrieveServlet", asyncRetrieveServlet);
    w2.setAsyncSupported(true);
    ctx.addServletMappingDecoded("/asyncRetrieveServlet", "asyncRetrieveServlet");

    tomcat.start();

    // First request in separate thread because the response won't be
    // written until after the second request has been made.
    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                getUrl("http://localhost:" + getPort() + "/asyncStashServlet");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });
    t.start();

    // Wait for first request to get as far as it can
    int count = 0;
    while (count < 100 && getTrack() != null &&
            !getTrack().startsWith("AsyncStashServletGet-")) {
        count++;
        Thread.sleep(100);
    }

    getUrl("http://localhost:" + getPort() + "/asyncRetrieveServlet");

    // Wait for second request to release first and allow it to complete
    String expectedTrack = "AsyncStashServletGet-AsyncRetrieveServletGet-NonAsyncServletGet-";
    count = 0;
    while (count < 100 && !getTrack().equals(expectedTrack)) {
        count++;
        Thread.sleep(100);
    }

    Assert.assertEquals(expectedTrack, getTrack());
}
 
Example 14
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);
}
 
Example 15
Source File: TestStandardWrapper.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
private void doTest(String servletClassName, boolean usePost,
        boolean useRole, boolean expect200, boolean denyUncovered)
        throws Exception {

    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();

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

    ctx.setDenyUncoveredHttpMethods(denyUncovered);

    Wrapper wrapper = Tomcat.addServlet(ctx, "servlet", servletClassName);
    wrapper.setAsyncSupported(true);
    ctx.addServletMappingDecoded("/", "servlet");

    if (useRole) {
        TesterMapRealm realm = new TesterMapRealm();
        realm.addUser("testUser", "testPwd");
        realm.addUserRole("testUser", "testRole");
        ctx.setRealm(realm);

        ctx.setLoginConfig(new LoginConfig("BASIC", null, null, null));
        ctx.getPipeline().addValve(new BasicAuthenticator());
    }

    tomcat.start();

    ByteChunk bc = new ByteChunk();
    Map<String,List<String>> reqHeaders = null;
    if (useRole) {
        reqHeaders = new HashMap<>();
        List<String> authHeaders = new ArrayList<>();
        // testUser, testPwd
        authHeaders.add("Basic dGVzdFVzZXI6dGVzdFB3ZA==");
        reqHeaders.put("Authorization", authHeaders);
    }

    int rc;
    if (usePost) {
        rc = postUrl(null, "http://localhost:" + getPort() + "/", bc,
                reqHeaders, null);
    } else {
        rc = getUrl("http://localhost:" + getPort() + "/", bc, reqHeaders,
                null);
    }

    if (expect200) {
        Assert.assertEquals("OK", bc.toString());
        Assert.assertEquals(200, rc);
    } else {
        Assert.assertTrue(bc.getLength() > 0);
        Assert.assertEquals(403, rc);
    }
}
 
Example 16
Source File: TestAsyncContextImpl.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
private void doTestDispatch(int iter, boolean useThread) throws Exception {
    resetTracker();
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();

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

    DispatchingServlet dispatch = new DispatchingServlet(false, false);
    Wrapper wrapper = Tomcat.addServlet(ctx, "dispatch", dispatch);
    wrapper.setAsyncSupported(true);
    ctx.addServletMapping("/stage1", "dispatch");

    NonAsyncServlet nonasync = new NonAsyncServlet();
    Wrapper wrapper2 = Tomcat.addServlet(ctx, "nonasync", nonasync);
    wrapper2.setAsyncSupported(true);
    ctx.addServletMapping("/stage2", "nonasync");

    ctx.addApplicationListener(TrackingRequestListener.class.getName());

    TesterAccessLogValve alv = new TesterAccessLogValve();
    ctx.getPipeline().addValve(alv);

    tomcat.start();

    StringBuilder url = new StringBuilder(48);
    url.append("http://localhost:");
    url.append(getPort());
    url.append("/stage1?iter=");
    url.append(iter);
    if (useThread) {
        url.append("&useThread=y");
    }
    getUrl(url.toString());

    StringBuilder expected = new StringBuilder("requestInitialized-");
    int loop = iter;
    while (loop > 0) {
        expected.append("DispatchingServletGet-");
        loop--;
    }
    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 ++;
    }
    assertEquals(expectedTrack, getTrack());

    // Check the access log
    alv.validateAccessLog(1, 200, 0, REQUEST_TIME);
}
 
Example 17
Source File: TestIoTimeouts.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
private Exception doRequest() {

            Tomcat tomcat = getTomcatInstance();

            Context root = tomcat.addContext("", TEMP_DIR);
            Wrapper w = Tomcat.addServlet(root, "Test", new NonBlockingEchoServlet());
            w.setAsyncSupported(true);
            root.addServletMappingDecoded("/test", "Test");

            try {
                tomcat.start();
                setPort(tomcat.getConnector().getLocalPort());

                // Open connection
                connect();

                int packetCount = 2;
                if (sendEndChunk) {
                    packetCount++;
                }

                String[] request = new String[packetCount];
                request[0] =
                    "POST /test HTTP/1.1" + CRLF +
                    "Host: localhost:8080" + CRLF +
                    "Transfer-Encoding: chunked" + CRLF +
                    "Connection: close" + CRLF +
                    CRLF;
                request[1] =
                        "b8" + CRLF +
                        "{" + CRLF +
                        "  \"tenantId\": \"dotCom\", "  + CRLF +
                        "  \"locale\": \"en-US\", "  + CRLF +
                        "  \"defaultZoneId\": \"25\", "  + CRLF +
                        "  \"itemIds\": [\"StaplesUSCAS/en-US/2/<EOF>/<EOF>\"] , "  + CRLF +
                        "  \"assetStoreId\": \"5051\", "  + CRLF +
                        "  \"zipCode\": \"98109\"" + CRLF +
                        "}" + CRLF;
                if (sendEndChunk) {
                    request[2] =
                            "0" + CRLF +
                            CRLF;
                }

                setRequest(request);
                processRequest(); // blocks until response has been read

                // Close the connection
                disconnect();
            } catch (Exception e) {
                return e;
            }
            return null;
        }
 
Example 18
Source File: TestAsyncContextImpl.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
@Test
public void testForbiddenDispatching() throws Exception {
    resetTracker();
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();

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

    NonAsyncServlet nonAsyncServlet = new NonAsyncServlet();
    Wrapper wrapper = Tomcat.addServlet(ctx, "nonAsyncServlet",
            nonAsyncServlet);
    wrapper.setAsyncSupported(true);
    ctx.addServletMapping("/target", "nonAsyncServlet");

    DispatchingGenericServlet forbiddenDispatchingServlet = new DispatchingGenericServlet();
    Wrapper wrapper1 = Tomcat.addServlet(ctx,
            "forbiddenDispatchingServlet", forbiddenDispatchingServlet);
    wrapper1.setAsyncSupported(true);
    ctx.addServletMapping("/forbiddenDispatchingServlet",
            "forbiddenDispatchingServlet");

    tomcat.start();

    try {
        getUrl("http://localhost:" + getPort()
                + "/forbiddenDispatchingServlet");
    } catch (IOException ioe) {
        // This may happen if test fails. Output the exception in case it is
        // useful and let asserts handle the failure
        ioe.printStackTrace();
    }

    // Request may complete before listener has finished processing so wait
    // up to 5 seconds for the right response
    String expectedTrack = "OKNonAsyncServletGet-";
    int count = 0;
    while (!expectedTrack.equals(getTrack()) && count < 100) {
        Thread.sleep(50);
        count ++;
    }
    Assert.assertEquals(expectedTrack, getTrack());
}
 
Example 19
Source File: TestAsyncContextImpl.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
@Test
public void testBug54178() throws Exception {
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();

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

    Bug54178ServletA bug54178ServletA = new Bug54178ServletA();
    Wrapper wrapper =
        Tomcat.addServlet(ctx, "bug54178ServletA", bug54178ServletA);
    wrapper.setAsyncSupported(true);
    ctx.addServletMapping("/bug54178ServletA", "bug54178ServletA");

    Bug54178ServletB bug54178ServletB = new Bug54178ServletB();
    Tomcat.addServlet(ctx, "bug54178ServletB", bug54178ServletB);
    ctx.addServletMapping("/bug54178ServletB", "bug54178ServletB");

    tomcat.start();

    ByteChunk body = new ByteChunk();
    int rc = -1;

    try {
        rc = getUrl("http://localhost:" + getPort() + "/bug54178ServletA?" +
                Bug54178ServletA.PARAM_NAME + "=bar",
                body, null);
    } catch (IOException ioe) {
        // This may happen if test fails. Output the exception in case it is
        // useful and let asserts handle the failure
        ioe.printStackTrace();
    }

    assertEquals(HttpServletResponse.SC_OK, rc);

    body.recycle();

    rc = getUrl("http://localhost:" + getPort() + "/bug54178ServletB",
            body, null);

    assertEquals(HttpServletResponse.SC_OK, rc);
    assertEquals("OK", body.toString());
}
 
Example 20
Source File: TestAsyncContextImpl.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
private void doTestDispatchError(int iter, boolean useThread,
        boolean completeOnError)
        throws Exception {
    resetTracker();
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();

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

    DispatchingServlet dispatch =
        new DispatchingServlet(true, completeOnError);
    Wrapper wrapper = Tomcat.addServlet(ctx, "dispatch", dispatch);
    wrapper.setAsyncSupported(true);
    ctx.addServletMapping("/stage1", "dispatch");

    ErrorServlet error = new ErrorServlet();
    Tomcat.addServlet(ctx, "error", error);
    ctx.addServletMapping("/stage2", "error");

    ctx.addApplicationListener(TrackingRequestListener.class.getName());

    TesterAccessLogValve alv = new TesterAccessLogValve();
    ctx.getPipeline().addValve(alv);

    tomcat.start();

    StringBuilder url = new StringBuilder(48);
    url.append("http://localhost:");
    url.append(getPort());
    url.append("/stage1?iter=");
    url.append(iter);
    if (useThread) {
        url.append("&useThread=y");
    }
    getUrl(url.toString());

    StringBuilder expected = new StringBuilder("requestInitialized-");
    int loop = iter;
    while (loop > 0) {
        expected.append("DispatchingServletGet-");
        if (loop != iter) {
            expected.append("onStartAsync-");
        }
        loop--;
    }
    expected.append("ErrorServletGet-onError-onComplete-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 ++;
    }
    assertEquals(expectedTrack, getTrack());

    // Check the access log
    alv.validateAccessLog(1, 500, 0, REQUEST_TIME);
}