Java Code Examples for javax.servlet.AsyncContext#complete()

The following examples show how to use javax.servlet.AsyncContext#complete() . 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
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    TestAsyncContextImpl.track("AsyncErrorPageGet-");

    final AsyncContext ctxt = req.getAsyncContext();

    switch(mode) {
        case COMPLETE:
            TestAsyncContextImpl.track("Complete-");
            ctxt.complete();
            break;
        case DISPATCH:
            TestAsyncContextImpl.track("Dispatch-");
            ctxt.dispatch("/error/nonasync");
            break;
        case NO_COMPLETE:
            TestAsyncContextImpl.track("NoOp-");
            break;
        default:
            // Impossible
            break;
    }
}
 
Example 2
Source File: AsyncStockServlet.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
public void writeStock(AsyncContext actx, Stock stock) {
    HttpServletResponse response = (HttpServletResponse)actx.getResponse();
    try {
        PrintWriter writer = response.getWriter();
        writer.write("STOCK#");//make client parsing easier
        writer.write(stock.getSymbol());
        writer.write("#");
        writer.write(stock.getValueAsString());
        writer.write("#");
        writer.write(stock.getLastChangeAsString());
        writer.write("#");
        writer.write(String.valueOf(stock.getCnt()));
        writer.write("\n");
        writer.flush();
        response.flushBuffer();
    }catch (IOException x) {
        try {actx.complete();}catch (Exception ignore){/* Ignore */}
    }
}
 
Example 3
Source File: QueryMessageServlet.java    From qmq with Apache License 2.0 6 votes vote down vote up
@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) {
    resp.setStatus(HttpServletResponse.SC_OK);
    final String queryJson = req.getParameter("backupQuery");
    if (Strings.isNullOrEmpty(queryJson)) return;
    final AsyncContext context = req.startAsync();
    RemoteMessageQuery query = deserialize(queryJson);
    if (query == null) {
        context.complete();
        return;
    }

    final ServletResponse response = context.getResponse();
    final CompletableFuture<Boolean> future = query(query, response);
    future.exceptionally(throwable -> {
        LOG.error("Failed to query messages. {}", query, throwable);
        return true;
    }).thenAccept(aBoolean -> context.complete());
}
 
Example 4
Source File: TestApplicationContextGetRequestDispatcher.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    AsyncContext ac = req.startAsync();
    // Quick and dirty. Sufficient for this test but ignores lots of
    // edge cases.
    String target = null;
    if (dispatchPath != null) {
        target = req.getServletPath();
        int lastSlash = target.lastIndexOf('/');
        target = target.substring(0, lastSlash + 1);
        if (encodePath) {
            target = URLEncoder.DEFAULT.encode(target, StandardCharsets.UTF_8);
        }
        target += dispatchPath;
    }
    try {
        ac.dispatch(target);
    } catch (UnsupportedOperationException uoe) {
        ac.complete();
        resp.setContentType("text/plain");
        resp.setCharacterEncoding("UTF-8");
        resp.getWriter().print(NULL);
    }
}
 
Example 5
Source File: TestAsyncContextImpl.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {

    final AsyncContext actxt = req.startAsync();
    actxt.setTimeout(TIMEOUT);
    if (threaded) {
        actxt.start(new Runnable() {
            @Override
            public void run() {
                try {
                    resp.sendError(status, ERROR_MESSAGE);
                    actxt.complete();
                } catch (IOException e) {
                    // Ignore
                }
            }
        });
    } else {
        resp.sendError(status, ERROR_MESSAGE);
        actxt.complete();
    }
}
 
Example 6
Source File: TestAsyncContextImpl.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    TestAsyncContextImpl.track("AsyncErrorPageGet-");

    final AsyncContext ctxt = req.getAsyncContext();

    switch(mode) {
        case COMPLETE:
            TestAsyncContextImpl.track("Complete-");
            ctxt.complete();
            break;
        case DISPATCH:
            TestAsyncContextImpl.track("Dispatch-");
            ctxt.dispatch("/error/nonasync");
            break;
        case NO_COMPLETE:
            TestAsyncContextImpl.track("NoOp-");
            break;
        default:
            // Impossible
            break;
    }
}
 
Example 7
Source File: PingServlet30Async.java    From sample.daytrader7 with Apache License 2.0 6 votes vote down vote up
/**
 * forwards post requests to the doGet method Creation date: (11/6/2000
 * 10:52:39 AM)
 *
 * @param res
 *            javax.servlet.http.HttpServletRequest
 * @param res2
 *            javax.servlet.http.HttpServletResponse
 */
@Override
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    res.setContentType("text/html");
                    
    AsyncContext ac = req.startAsync();
    StringBuilder sb = new StringBuilder();
    
    ServletInputStream input = req.getInputStream();
    byte[] b = new byte[1024];
    int len = -1;
    while ((len = input.read(b)) != -1) {
        String data = new String(b, 0, len);
        sb.append(data);
    }

    ServletOutputStream output = res.getOutputStream();
    
    output.println("<html><head><title>Ping Servlet 3.0 Async</title></head>"
            + "<body><hr/><br/><font size=\"+2\" color=\"#000066\">Ping Servlet 3.0 Async</font><br/>"
            + "<font size=\"+1\" color=\"#000066\">Init time : " + initTime
            + "</font><br/><br/><b>Hit Count: " + ++hitCount + "</b><br/>Data Received: "+ sb.toString() + "</body></html>");
    
    ac.complete();
}
 
Example 8
Source File: AsyncDispatcherServlet.java    From Spring-Security-Third-Edition with MIT License 6 votes vote down vote up
@Override
protected void doDispatch(final HttpServletRequest request, final HttpServletResponse response) throws Exception {

    final AsyncContext ac = request.startAsync(request, response);

    ac.setTimeout(TIME_OUT);

    // FIXME: convert to Lambda
    FutureTask task = new FutureTask(new Runnable() {

        @Override
        public void run() {
            try {
                logger.debug("Dispatching request " + request);
                AsyncDispatcherServlet.super.doDispatch(request, response);
                logger.debug("doDispatch returned from processing request " + request);
                ac.complete();
            } catch (Exception ex) {
                logger.error("Error in async request", ex);
            }
        }
    }, null);

    ac.addListener(new AsyncDispatcherServletListener(task));
    exececutor.execute(task);
}
 
Example 9
Source File: AnotherAsyncServlet.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
    final AsyncContext ctx = req.startAsync();
    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Thread.sleep(100);
                resp.setContentType("text/plain");
                resp.getWriter().write(AnotherAsyncServlet.class.getSimpleName());
                ctx.complete();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    });
    t.start();
}
 
Example 10
Source File: TestAsyncContextImpl.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    req.getParameter(PARAM_NAME);
    AsyncContext actxt = req.startAsync();
    actxt.addListener(new Bug54178AsyncListener());
    actxt.complete();
}
 
Example 11
Source File: SendServlet.java    From qmq with Apache License 2.0 5 votes vote down vote up
private void asyncSuccess(AsyncContext asyncContext, Message message) {
    try {
        Map<String, Object> result = new HashMap<>();
        result.put("status", 0);
        result.put("message", message.getMessageId());
        ServletResponse response = asyncContext.getResponse();
        response.setContentType("application/json");
        MAPPER.writeValue(response.getWriter(), result);
    } catch (Exception e) {
        logger.error("return message error {} - {}", message.getSubject(), message.getMessageId());
    } finally {
        asyncContext.complete();
    }
}
 
Example 12
Source File: TestAsyncContextImpl.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    req.getParameter(PARAM_NAME);
    AsyncContext actxt = req.startAsync();
    actxt.addListener(new Bug54178AsyncListener());
    actxt.complete();
}
 
Example 13
Source File: TestAsyncContextImpl.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    req.getParameter(PARAM_NAME);
    AsyncContext actxt = req.startAsync();
    actxt.addListener(new Bug54178AsyncListener());
    actxt.complete();
}
 
Example 14
Source File: AsyncStockServlet.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
public void shutdown() {
    // The web application is shutting down. Complete any AsyncContexts
    // associated with an active client.
    Iterator<AsyncContext> it = clients.iterator();
    while (it.hasNext()) {
        AsyncContext actx = it.next();
        try {
            actx.complete();
        } catch (Exception e) {
            // Ignore. The async error handling will deal with this.
        }
    }
}
 
Example 15
Source File: AbstractJettyTest.java    From java-web-servlet-filter with Apache License 2.0 5 votes vote down vote up
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    final AsyncContext asyncContext = request.startAsync(request, response);
    response.setStatus(204);
    asyncContext.complete();
}
 
Example 16
Source File: TestAsyncContextImpl.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    AsyncContext actxt = req.startAsync();
    resp.setStatus(status);
    actxt.complete();
}
 
Example 17
Source File: TestAsyncContextImpl.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
protected void doGet(final HttpServletRequest req,
        final HttpServletResponse resp)
        throws ServletException, IOException {

    AsyncContext actxt = req.startAsync();
    actxt.setTimeout(3000);
    resp.setContentType("text/plain");
    resp.getWriter().print("OK");
    actxt.complete();
}
 
Example 18
Source File: TestAsyncContextImplDispatch.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    if (start) {
        AsyncContext ac = req.startAsync();
        ac.complete();
    }

    resp.setContentType("text/plain");
    resp.setCharacterEncoding("UTF-8");
    resp.getWriter().write("OK");
}
 
Example 19
Source File: TestAsyncContextImpl.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@Override
protected void doGet(final HttpServletRequest req,
        final HttpServletResponse resp)
        throws ServletException, IOException {

    AsyncContext actxt = req.startAsync();
    actxt.setTimeout(3000);
    resp.setContentType("text/plain");
    resp.getWriter().print("OK");
    actxt.complete();
}
 
Example 20
Source File: TestCoyoteAdapter.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    resp.setContentType("text/plain");
    resp.setCharacterEncoding("UTF-8");

    final OutputStream os = resp.getOutputStream();

    final AsyncContext asyncCtxt = req.startAsync();
    asyncCtxt.setTimeout(3000);

    t = new Thread(new Runnable() {

        @Override
        public void run() {
            for (int i = 0; i < 20; i++) {
                try {
                    // Some tests depend on this write failing (e.g.
                    // because the client has gone away). In some cases
                    // there may be a large (ish) buffer to fill before
                    // the write fails.
                    for (int j = 0 ; j < 8; j++) {
                        os.write(BYTES_8K);
                    }
                    os.flush();
                    Thread.sleep(1000);
                } catch (Exception e) {
                    log.info("Exception caught " + e);
                    try {
                        // Note if request times out before this
                        // exception is thrown and the complete call
                        // below is made, the complete call below will
                        // fail since the timeout will have completed
                        // the request.
                        asyncCtxt.complete();
                        break;
                    } finally {
                        completed = true;
                    }
                }
            }
        }
    });
    t.setName("testBug54928");
    t.start();
}