Package javax.servlet

Examples of javax.servlet.AsyncContext


    @Override
    protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {

        if(req.getAttribute("ok") == null) {
            System.out.println("===before start async:" + req.isAsyncStarted());
            final AsyncContext asyncContext = req.startAsync();
            System.out.println("===after start async:" + req.isAsyncStarted());

            asyncContext.setTimeout(10L * 1000);
            asyncContext.addListener(new AsyncListener() {
                @Override
                public void onComplete(final AsyncEvent event) throws IOException {
                    System.out.println("=====async complete");
                }

                @Override
                public void onTimeout(final AsyncEvent event) throws IOException {
                    System.out.println("=====async timeout");
                }

                @Override
                public void onError(final AsyncEvent event) throws IOException {
                    System.out.println("=====async error");
                }

                @Override
                public void onStartAsync(final AsyncEvent event) throws IOException {
                }
            });

            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(3L * 1000);
                    } catch (InterruptedException e) {
                    }
                    req.setAttribute("ok", "true");
                    req.setAttribute("msg", "success");
                    asyncContext.dispatch();
                    System.out.println("===after dispatch before handle:" + req.isAsyncStarted());
                }
            }).start();

            return;

        } else {
            //可以继续开启异步并分派,在分派到的servlet中还可以继续开启异步流程
            AsyncContext asyncContext = req.startAsync();
            asyncContext.setTimeout(10L * 1000);
            asyncContext.addListener(new AsyncListener() {
                @Override
                public void onComplete(final AsyncEvent event) throws IOException {
                    System.out.println("=====async complete");
                }

                @Override
                public void onTimeout(final AsyncEvent event) throws IOException {
                    System.out.println("=====async timeout");
                }

                @Override
                public void onError(final AsyncEvent event) throws IOException {
                    System.out.println("=====async error");
                }

                @Override
                public void onStartAsync(final AsyncEvent event) throws IOException {
                }
            });

            resp.getWriter().write("hello ");
            //dispatch不会丢失之前的响应流,即保留这个响应流,接着在下一个servlet继续写入,这个不同于forward转发
            asyncContext.dispatch("/dispatch5");
         }


    }
View Full Code Here


    @Override
    protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {

        if(req.getAttribute("ok") == null) {
            System.out.println("===before start async:" + req.isAsyncStarted());
            final AsyncContext asyncContext = req.startAsync();
            System.out.println("===after start async:" + req.isAsyncStarted());

            asyncContext.setTimeout(10L * 1000);
            asyncContext.addListener(new AsyncListener() {
                @Override
                public void onComplete(final AsyncEvent event) throws IOException {
                    System.out.println("=====async complete");
                }

                @Override
                public void onTimeout(final AsyncEvent event) throws IOException {
                    System.out.println("=====async timeout");
                }

                @Override
                public void onError(final AsyncEvent event) throws IOException {
                    System.out.println("=====async error");
                }

                @Override
                public void onStartAsync(final AsyncEvent event) throws IOException {
                }
            });

            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(3L * 1000);
                    } catch (InterruptedException e) {
                    }
                    req.setAttribute("ok", "true");
                    req.setAttribute("msg", "success");
                    asyncContext.dispatch();
                    System.out.println("===after dispatch before handle:" + req.isAsyncStarted());
                }
            }).start();

            return;
View Full Code Here

    @Override
    protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {


        System.out.println("===before start async:" + req.isAsyncStarted());
        final AsyncContext asyncContext = req.startAsync();
        System.out.println("===after start async:" + req.isAsyncStarted());

        asyncContext.setTimeout(10L * 1000);
        asyncContext.addListener(new AsyncListener() {
            @Override
            public void onComplete(final AsyncEvent event) throws IOException {
                System.out.println("=====async complete");
            }

            @Override
            public void onTimeout(final AsyncEvent event) throws IOException {
            }

            @Override
            public void onError(final AsyncEvent event) throws IOException {
            }

            @Override
            public void onStartAsync(final AsyncEvent event) throws IOException {
            }
        });


        req.setAttribute("ok1", "true");
        req.setAttribute("msg", "success");
        asyncContext.dispatch();
        //多次调用dispatch,会抛出java.lang.IllegalStateException: REDISPATCHING,initial,resumed
        //目前jetty会死循环,建议try-catch 自己complete 或者实际一定要避免这么用
        asyncContext.dispatch();
        System.out.println("===after dispatch before handle:" + req.isAsyncStarted());


    }
View Full Code Here

        public boolean trySend(HttpResponse message) {
            final HttpServletRequest request = ((ServletHttpRequest) message.getRequest()).request;
            if (!request.isAsyncStarted())
                return false;

            final AsyncContext ctx = request.getAsyncContext();
            final HttpServletResponse response = (HttpServletResponse) ctx.getResponse();
            try {
                if (message instanceof HttpResponse) {
                    final HttpResponse msg = (HttpResponse) message;
                    if (!response.isCommitted()) {
                        if (msg.getCookies() != null) {
                            for (Cookie wc : msg.getCookies())
                                response.addCookie(getServletCookie(wc));
                        }
                        if (msg.getHeaders() != null) {
                            for (Map.Entry<String, String> h : msg.getHeaders().entries())
                                response.addHeader(h.getKey(), h.getValue());
                        }
                    }

                    if (msg.getStatus() >= 400 && msg.getStatus() < 600) {
                        response.sendError(msg.getStatus(), msg.getError() != null ? msg.getError().toString() : null);
                        close();
                        return true;
                    }

                    if (msg.getRedirectPath() != null) {
                        response.sendRedirect(msg.getRedirectPath());
                        close();
                        return true;
                    }

                    if (!response.isCommitted()) {
                        response.setStatus(msg.getStatus());

                        if (msg.getContentType() != null)
                            response.setContentType(msg.getContentType());
                        if (msg.getCharacterEncoding() != null)
                            response.setCharacterEncoding(msg.getCharacterEncoding().name());
                    }
                }
                ServletOutputStream out = writeBody(message, response, !message.shouldStartActor());
                out.flush(); // commits the response

                if (message.shouldStartActor()) {
                    try {
                        message.getFrom().send(new HttpStreamOpened(new HttpStreamActor(request, response).ref(), message));
                    } catch (SuspendExecution e) {
                        throw new AssertionError(e);
                    }
                } else {
                    out.close();
                    ctx.complete();
                }
                return true;
            } catch (IOException ex) {
                request.getServletContext().log("IOException", ex);
                ctx.complete();
                this.exception = ex;
                return false;
            }
        }
View Full Code Here

        }

        request = (HttpServletRequest) req;
        response = (HttpServletResponse) res;
        req.setAttribute("org.apache.catalina.ASYNC_SUPPORTED", true);
        final AsyncContext ac = req.startAsync();
        ac.setTimeout(120000);
        final FiberHttpServletRequest srad = new FiberHttpServletRequest(request);
        new Fiber(null, stackSize, new SuspendableRunnable() {
            @Override
            public void run() throws SuspendExecution, InterruptedException {
                try {
                    // TODO: check if ac has expired
                    currentAsyncContext.set(ac);
                    service(srad, response); //To change body of generated methods, choose Tools | Templates.
//                    suspendableService(srad, res);
                } catch (Exception ex) {
                    log("Exception in fiber servlet", ex);
                } finally {
                    if (req.isAsyncStarted())
                        ac.complete();
                    currentAsyncContext.set(null);
                }
            }
        }).start();
    }
View Full Code Here

     * {@link #suspendableService} to service the request.
     */
    @Override
    public final void service(final ServletRequest req, final ServletResponse res) {
        req.setAttribute("org.apache.catalina.ASYNC_SUPPORTED", true);
        final AsyncContext ac = req.startAsync();
        ac.setTimeout(120000);
        final FiberServletRequest srad = wrapRequest(req);
        new Fiber(null, stackSize, new SuspendableRunnable() {
            @Override
            public void run() throws SuspendExecution, InterruptedException {
                try {
                    // TODO: check if ac has expired
                    currentAsyncContext.set(ac);
                    suspendableService(srad, res);
                } catch (Exception ex) {
                    log("Exception in fiber servlet", ex);
                } finally {
                    if (req.isAsyncStarted())
                        ac.complete();
                    currentAsyncContext.set(null);
                }
            }
        }).start();
    }
View Full Code Here

    }

    queue.heartBeat();

    final OutputStreamWriteAdapter writer;
    final AsyncContext asyncContext = request.startAsync();
    asyncContext.setTimeout(60000);
    queue.setTimeout(65000);
    writer = new OutputStreamWriteAdapter(asyncContext.getResponse().getOutputStream());

    asyncContext.addListener(new AsyncListener() {
        @Override
        public void onComplete(final AsyncEvent event) throws IOException {
          synchronized (queue.getActivationLock()) {
            queue.setActivationCallback(null);
            asyncContext.complete();
          }
        }

        @Override
        public void onTimeout(final AsyncEvent event) throws IOException {
          onComplete(event);
        }

        @Override
        public void onError(final AsyncEvent event) throws IOException {
          queue.setActivationCallback(null);
        }

        @Override
        public void onStartAsync(final AsyncEvent event) throws IOException {
        }
      });

    synchronized (queue.getActivationLock()) {
      if (queue.messagesWaiting()) {
        queue.poll(writer);
        asyncContext.complete();
        return;
      }

      queue.setActivationCallback(new QueueActivationCallback() {
        @Override
        public void activate(final MessageQueue queue) {
          try {
            queue.poll(writer);
            queue.setActivationCallback(null);

            queue.heartBeat();
            writer.flush();
          }
          catch (IOException e) {
            log.debug("Closing queue with id: " + queue.getSession().getSessionId() + " due to IOException", e);
           
          }
          catch (final Throwable t) {
            try {
              writeExceptionToOutputStream((HttpServletResponse) asyncContext.getResponse(), t);
            }
            catch (Throwable t2) {
              log.debug("Failed to write exception to dead client", t2);
            }
          }
          finally {
            asyncContext.complete();
          }
        }
      });
      writer.flush();
    }
View Full Code Here

    if (queue.messagesWaiting()) {
      queue.poll(false, response.getOutputStream());
      return;
    }
   
    final AsyncContext asyncContext = request.startAsync();
    asyncContext.addListener(new AsyncListener() {
      @Override
      public void onTimeout(AsyncEvent event) throws IOException {
        poll(queue, asyncContext);
        asyncContext.complete();
      }
     
      @Override
      public void onComplete(AsyncEvent event) throws IOException {}
     
      @Override
      public void onError(AsyncEvent event) throws IOException {}
     
      @Override
      public void onStartAsync(AsyncEvent event) throws IOException {}
    });

    queue.setActivationCallback(new QueueActivationCallback() {
      @Override
      public void activate(MessageQueue queue) {
        try {
          poll(queue, asyncContext);
        }
        catch (final Throwable t) {
          try {
            writeExceptionToOutputStream((HttpServletResponse)asyncContext.getResponse(), t);
          }
          catch (IOException e) {
            throw new RuntimeException("Failed to write exception to output stream", e);
          }
        }
        finally {
          asyncContext.complete();
        }
      }
    });
  }
View Full Code Here

    if (queue.messagesWaiting()) {
      queue.poll(false, response.getOutputStream());
      return;
    }

    final AsyncContext asyncContext = request.startAsync();
    asyncContext.addListener(new AsyncListener() {
      @Override
      public void onTimeout(AsyncEvent event) throws IOException {
        poll(queue, asyncContext);
        asyncContext.complete();
      }

      @Override
      public void onComplete(AsyncEvent event) throws IOException {}

      @Override
      public void onError(AsyncEvent event) throws IOException {}

      @Override
      public void onStartAsync(AsyncEvent event) throws IOException {}
    });

    queue.setActivationCallback(new QueueActivationCallback() {
      @Override
      public void activate(MessageQueue queue) {
        try {
          poll(queue, asyncContext);
        }
        catch (final Throwable t) {
          try {
            writeExceptionToOutputStream((HttpServletResponse)asyncContext.getResponse(), t);
          }
          catch (IOException e) {
            throw new RuntimeException("Failed to write exception to output stream", e);
          }
        }
        finally {
          asyncContext.complete();
        }
      }
    });
  }
View Full Code Here

      response.reset();
    } catch (IllegalStateException e1) {
    }

    if (req.isAsyncStarted()) {
      AsyncContext async = req.getAsyncContext();

      if (async != null)
        async.complete();
    }

    if (response instanceof HttpServletResponseImpl) {
      HttpServletResponseImpl resFacade = (HttpServletResponseImpl) response;
      resFacade.killCache();
View Full Code Here

TOP

Related Classes of javax.servlet.AsyncContext

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.