Ejemplo n.º 1
1
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    resp.getWriter().write(super.getServletName());

    AsyncContext asyncContext = req.startAsync();
    asyncContext.setTimeout(0);

    /*
     * O metodo createListener() cria um listener da classe informada que
     * deve extender AsyncListener. Este metodo adiciona suporte para a
     * notacoes e injecao de dependencias dentro do listener criado, deste
     * modo, objetos sao injetados dentro desse listener depois que ele é
     * criado.
     */
    MyAsyncListener myAsyncListener = asyncContext.createListener(MyAsyncListener.class);

    /*
     * O metodo addListener(AsyncListener) registra o listener informado ao
     * AsyncContext em questao.
     */
    asyncContext.addListener(myAsyncListener);

    /*
     * O metodo addListener() é sobrecarregado para receber um
     * ServletRequest e um ServletResponse, que podem ser recuperados mais
     * tarde dentro do listener atraves dos metodos getSuppliedRequest() e
     * getSuppliedResponse() de AsyncEvent.
     */
    // asyncContext.addListener(myAsyncListener, null, null);

    AsyncTask task = new AsyncTask(asyncContext);
    asyncContext.start(task);
  }
Ejemplo n.º 2
0
  @Override
  public void run() {
    // TODO Auto-generated method stub
    CloseableHttpClient httpClient =
        (CloseableHttpClient) asyncContext.getRequest().getAttribute("httpClient");
    HttpGet get = new HttpGet(URL);
    @SuppressWarnings("unchecked")
    ResponseHandler<String> responseHandler =
        (ResponseHandler<String>) asyncContext.getRequest().getAttribute("responseHandler");
    String response = "";
    try {
      response = httpClient.execute(get, responseHandler);
    } catch (ClientProtocolException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    String userID = asyncContext.getRequest().getParameter("userID");
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("response", response);
    params.put("patterns", patternMap);
    params.put("userID", userID);
    Transaction transaction = new GetUserBasicInfoTransaction();
    try {
      transaction.execute(params);
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    asyncContext.complete();
  }
Ejemplo n.º 3
0
 public static void publishToActiveClients(String message) throws IOException {
   message = "data: {\"msg\": \"" + message + "\"}\n\n";
   for (AsyncContext ac : activeClients) {
     ac.getResponse().getWriter().write(message);
     ac.getResponse().getWriter().flush();
   }
 }
 @Override
 protected void doGet(HttpServletRequest req, HttpServletResponse resp)
     throws ServletException, IOException {
   resp.getWriter().write("DispatchingServletGet-");
   resp.flushBuffer();
   final int iter = Integer.parseInt(req.getParameter(ITER_PARAM)) - 1;
   final AsyncContext ctxt = req.startAsync();
   if (addTrackingListener) {
     TrackingListener listener = new TrackingListener(completeOnError, true, null);
     ctxt.addListener(listener);
   }
   Runnable run =
       new Runnable() {
         @Override
         public void run() {
           if (iter > 0) {
             ctxt.dispatch("/stage1?" + ITER_PARAM + "=" + iter);
           } else {
             ctxt.dispatch("/stage2");
           }
         }
       };
   if ("y".equals(req.getParameter("useThread"))) {
     new Thread(run).start();
   } else {
     run.run();
   }
 }
Ejemplo n.º 5
0
    @Override
    public void onEvent(byte[] data, long seq, boolean endOfBatch) throws Exception {
      crc32.update(data);
      long crc = crc32.getValue();

      byte[] md5 = md5Digest.digest(data);
      byte[] sha1 = sha1Digest.digest(data);

      Data d = new Data(String.valueOf(crc), toHex(md5), toHex(sha1));
      int size = contexts.size();

      for (int i = 0; i < size; i++) {
        AsyncContext context = contexts.poll();
        if (null != context) {
          context.getRequest().setAttribute("data", d);
          try {
            context.dispatch();
          } catch (Exception e) {
          }
        } else {
          break;
        }
      }

      crc32.reset();
      md5Digest.reset();
      sha1Digest.reset();
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
      resp.getWriter().write("DispatchingServletGet-");
      resp.flushBuffer();

      final boolean first = TrackingServlet.first;
      TrackingServlet.first = false;

      final AsyncContext ctxt = req.startAsync();
      TrackingListener listener = new TrackingListener(false, true, null);
      ctxt.addListener(listener);
      ctxt.setTimeout(3000);

      Runnable run =
          new Runnable() {
            @Override
            public void run() {
              if (first) {
                ctxt.dispatch("/stage1");
              } else {
                ctxt.dispatch("/stage2");
              }
            }
          };
      if ("y".equals(req.getParameter("useThread"))) {
        new Thread(run).start();
      } else {
        run.run();
      }
    }
Ejemplo n.º 7
0
 @Override
 public void onTimeout(AsyncEvent event) throws IOException {
   // Remove before it's redispatched, so it won't be
   // redispatched again at the end of the filtering.
   AsyncContext asyncContext = event.getAsyncContext();
   _queues[priority].remove(asyncContext);
   asyncContext.dispatch();
 }
 SampleAsycListener(HttpServletRequest request, HttpServletResponse response)
     throws IOException {
   asyncContext = request.startAsync();
   asyncContext.setTimeout(10000L);
   asyncContext.addListener(this);
   servletOutputStream = response.getOutputStream();
   servletOutputStream.setWriteListener(this);
   this.response = response;
 }
Ejemplo n.º 9
0
  /* ------------------------------------------------------------ */
  @Override
  public void suspend() {
    _resumed = false;
    _expired = false;
    _context = _request.startAsync();
    _context.setTimeout(_timeoutMs);

    for (AsyncListener listener : _listeners) _context.addListener(listener);
    _listeners.clear();
  }
    @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();
    }
Ejemplo n.º 11
0
 @Override
 protected void doGet(HttpServletRequest req, HttpServletResponse resp)
     throws ServletException, IOException {
   // Only set the status on the first call (the dispatch will trigger
   // another call to this Servlet)
   if (resp.getStatus() != HttpServletResponse.SC_BAD_REQUEST) {
     resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
     AsyncContext ac = req.startAsync();
     ac.dispatch();
   }
 }
Ejemplo n.º 12
0
 @Override
 public void onTimeout(AsyncEvent event) throws IOException {
   AsyncContext async = _async.get();
   if (async != null && _async.compareAndSet(async, null)) {
     HttpServletResponse response = (HttpServletResponse) async.getResponse();
     response.setContentType("text/json;charset=utf-8");
     PrintWriter out = response.getWriter();
     out.print("{action:\"poll\"}");
     async.complete();
   }
 }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
      if (req.isAsyncSupported()) {
        resp.getWriter().print("TimeoutServletGet-");
        final AsyncContext ac = req.startAsync();
        ac.setTimeout(3000);

        ac.addListener(new TrackingListener(false, completeOnTimeout, dispatchUrl));
      } else resp.getWriter().print("FAIL: Async unsupported");
    }
Ejemplo n.º 14
0
  /* ------------------------------------------------------------ */
  @Override
  public void suspend(ServletResponse response) {
    _response = response;
    _responseWrapped = response instanceof ServletResponseWrapper;
    _resumed = false;
    _expired = false;
    _context = _request.startAsync();
    _context.setTimeout(_timeoutMs);

    for (AsyncListener listener : _listeners) _context.addListener(listener);
    _listeners.clear();
  }
Ejemplo n.º 15
0
  /**
   * Caso o response ja esteja fechado ou o metodo startAsync() ja tenha sido chamado, uma nova
   * invocacao resultara em uma IllegalStateException.
   */
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    PrintWriter writer = resp.getWriter();

    writer.println("Antes de iniciar a tarefa assincrona");

    /*
     * Para iniciar uma requisicao assincrona, basta chamar o metodo
     * startAsync de ServletRequest. O metodo startAsync é sobrecarregado
     * para receber um ServletRequest e um ServletResponse, desta forma é
     * possivel passar wrappers para ele. Caso o metodo startAsync seja
     * chamado, os objetos ServletRequest e Response originais serao
     * utilizados.
     */
    AsyncContext asyncContext = req.startAsync();

    MyAsyncTask asyncTask = new MyAsyncTask(asyncContext, writer);

    /*
     * O tempo padrao de time out depende do container, geralmente está
     * entre 5 e 10 segundos. Para desabilitar o time out basta informar um
     * valor negativo ou 0. Esse metodo pode ser chamado antes ou depois do
     * metodo start().
     */
    asyncContext.setTimeout(-1);

    /*
     * A Interface AsyncContext possui metodos para configurar a tarefa
     * assincrona e inicializar a mesma. O metodo estart recebe um runnable
     * que sera responsavel por realizar o processamento da tarefa
     * assincrona. Quando esse metodo é chamado, o processamento é realizado
     * por outra Thread do pool de Threads do servidor.
     */
    asyncContext.start(asyncTask);

    /*
     * Depois do start() da tarefa assincrona, o fluxo continua normalmente,
     * e quando o metodo service() é encerrado, a resposta nao é commitada
     * enquanto o metodo complete() de AsyncContext não for chamado. Desta
     * forma, o container processa a tarefa assincrona um background em
     * outra Thread.
     */
    writer.println("Depois de iniciar a tarefa assincrona");

    /*
     * Retorna o AsyncContext inicializado para esse request. Caso o metodo
     * startAsync() ainda nao tenha sido chamado, uma IllegalStateException
     * ocorrera.
     */
    req.getAsyncContext();
  }
Ejemplo n.º 16
0
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/event-stream");
    response.setCharacterEncoding("UTF-8");

    AsyncContext ac = request.startAsync();
    ac.setTimeout(300000);
    ac.addListener(
        new AsyncListener() {
          @Override
          public void onTimeout(AsyncEvent ae) throws IOException {
            activeClients.remove(ae.getAsyncContext());
            publishToActiveClients(
                ae.getAsyncContext().getRequest().getRemoteHost()
                    + ":"
                    + ae.getAsyncContext().getRequest().getRemotePort()
                    + " has timedout...");
          }

          @Override
          public void onError(AsyncEvent ae) throws IOException {
            activeClients.remove(ae.getAsyncContext());
            publishToActiveClients(
                ae.getAsyncContext().getRequest().getRemoteHost()
                    + ":"
                    + ae.getAsyncContext().getRequest().getRemotePort()
                    + " has errors...");
          }

          @Override
          public void onComplete(AsyncEvent ae) throws IOException {
            activeClients.remove(ae.getAsyncContext());
            publishToActiveClients(
                ae.getAsyncContext().getRequest().getRemoteHost()
                    + ":"
                    + ae.getAsyncContext().getRequest().getRemotePort()
                    + " completed...");
          }

          @Override
          public void onStartAsync(AsyncEvent ae) throws IOException {
            publishToActiveClients(
                ae.getAsyncContext().getRequest().getRemoteHost()
                    + ":"
                    + ae.getAsyncContext().getRequest().getRemotePort()
                    + " started...");
          }
        });
    activeClients.add(ac);
    ac.getResponse().getWriter().flush();
    publishToActiveClients(getRequestDescription(request) + " joined...");
  }
Ejemplo n.º 17
0
 @Override
 protected void service(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   AsyncContext asyncContext = (AsyncContext) request.getAttribute(AsyncContext.class.getName());
   if (asyncContext == null) {
     AsyncContext context = request.startAsync();
     context.setTimeout(0);
     request.setAttribute(AsyncContext.class.getName(), context);
     context.addListener(this);
   } else {
     throw new ServletException();
   }
 }
    @Override
    protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {

      String echo = req.getParameter("echo");
      AsyncContext actxt = req.startAsync();
      resp.setContentType("text/plain");
      resp.getWriter().print("OK");
      if (echo != null) {
        resp.getWriter().print("-" + echo);
      }
      // Speed up the test by reducing the timeout
      actxt.setTimeout(1000);
    }
Ejemplo n.º 19
0
  /**
   * The use of {@link Asynchronous} causes this EJB method to be executed asynchronously, by a
   * different thread from a dedicated, container managed thread pool.
   *
   * @param asyncContext the context for a suspended Servlet request that this EJB will complete
   *     later.
   */
  @Asynchronous
  public void readData(AsyncContext asyncContext) {
    try {
      // This is just to simulate a long running operation.
      Thread.sleep(5000);

      PrintWriter writer = asyncContext.getResponse().getWriter();
      writer.println(new SimpleDateFormat("HH:mm:ss").format(new Date()));
      writer.close();

      asyncContext.complete();
    } catch (Exception e) {
      logger.log(Level.SEVERE, e.getMessage(), e);
    }
  }
Ejemplo n.º 20
0
  @Override
  public void run() {
    try {
      Thread.sleep(20000); // 让线程休眠2s钟模拟超时操作
      PrintWriter wirter = context.getResponse().getWriter();
      wirter.println("延迟输出");
      System.out.println("延迟输出");
      wirter.flush();
      context.complete();
    } catch (InterruptedException e) {

    } catch (IOException e) {

    }
  }
Ejemplo n.º 21
0
  @Override
  public void run() {

    boolean done = false;
    int count = 0;
    while (!Thread.currentThread().isInterrupted() && !done) {
      logger.debug("Thread running...");

      if (count > 10) {
        done = true;
        try {
          sendStreamClose((HttpServletResponse) asyncContext.getResponse());
        } catch (IOException e) {
          e.printStackTrace();
        }
        continue;
      }

      String msg = "Sending from server the count -  " + count;

      try {
        HttpServletResponse response = (HttpServletResponse) asyncContext.getResponse();
        if (response != null) {
          logger.debug("writing..." + count);

          response.setContentType("text/event-stream");
          PrintWriter acWriter = response.getWriter();

          acWriter.write("data:" + msg + "\n\n");
          acWriter.flush();
        } else logger.error("response is null");

      } catch (IOException ex) {
        logger.error("failure in writing to response", ex);
        done = true;
      }

      count++;

      try {
        Thread.sleep(1000);
      } catch (InterruptedException e) {
        done = true;
      }
    }

    asyncContext.complete();
  }
Ejemplo n.º 22
0
 /* ------------------------------------------------------------ */
 @Override
 public void resume() {
   AsyncContext context = _context;
   if (context == null) throw new IllegalStateException();
   _resumed = true;
   _context.dispatch();
 }
Ejemplo n.º 23
0
  /* ------------------------------------------------------------ */
  @Override
  public void addContinuationListener(final ContinuationListener listener) {
    AsyncListener wrapped =
        new AsyncListener() {
          @Override
          public void onComplete(final AsyncEvent event) throws IOException {
            listener.onComplete(Servlet3Continuation.this);
          }

          @Override
          public void onError(AsyncEvent event) throws IOException {
            listener.onComplete(Servlet3Continuation.this);
          }

          @Override
          public void onStartAsync(AsyncEvent event) throws IOException {
            event.getAsyncContext().addListener(this);
          }

          @Override
          public void onTimeout(AsyncEvent event) throws IOException {
            _expired = true;
            listener.onTimeout(Servlet3Continuation.this);
          }
        };

    if (_context != null) _context.addListener(wrapped);
    else _listeners.add(wrapped);
  }
Ejemplo n.º 24
0
 @Override
 protected void doGet(HttpServletRequest req, HttpServletResponse resp)
     throws ServletException, IOException {
   PrintWriter out = resp.getWriter();
   logger.info(req.getDispatcherType());
   out.println("success async2");
   // 非法调用,此时Async的状态是DISPATCHED,complete在startAsync调用之后,dispatch之前进行调用是合法的;否则抛出IllegalState
   // 此时分派尚未返回到容器,在service返回后,容器将执行complete
   //        asyncContext.complete();
   AsyncContext asyncContext = req.startAsync();
   asyncContext.start(
       () -> {
         System.out.println("Start!");
         asyncContext.complete(); // 完成,进行响应
       });
 }
  public void sendMessageOnChannel(
      HttpServletRequest request, String message, String channel, String... excludeUsers) {

    // get the application scoped model, and copy the list of subscribers,
    // so that the long running task of publishing doesnt interfere with new logins
    List<Subscriber> subscribersForChannel = subscriberRegistry.getSubscribersForChannel(channel);
    final List<Subscriber> subscribers = new ArrayList<Subscriber>(subscribersForChannel);

    String[] excludeUsersArray = excludeUsers;
    if (excludeUsers == null) excludeUsersArray = new String[0];
    List<String> excludeUserList = Arrays.asList(excludeUsersArray);

    logger.info("Updating channel {} for {} subscribers...", channel, subscribers.size());
    long start = System.currentTimeMillis();

    // keep a list of failed subscribers so we can remove them at
    // the end
    List<Subscriber> toRemove = new ArrayList<Subscriber>();
    for (Subscriber s : subscribers) {

      if (excludeUserList.size() > 0 && excludeUserList.contains(s.getUser())) {
        continue;
      }
      synchronized (s) {
        AsyncContext aCtx = s.getaCtx();
        try {
          aCtx.getResponse().getOutputStream().print(message);
          aCtx.complete();
        } catch (Exception e) {
          e.printStackTrace();
          logger.warn(
              "Failed to send to client {} - removing from list of subscribers on channel {}",
              s.getUser(),
              channel);
          toRemove.add(s);
        }
      }
    }

    // remove the failed subscribers from the model in app scope,
    // not our copy of them
    subscribers.removeAll(toRemove);

    // log success
    long end = System.currentTimeMillis() - start;
    logger.info("Finished updating channel {} in {} milliseconds.", channel, end);
  }
Ejemplo n.º 26
0
  synchronized void send(JSONStreamAware response) {
    if (asyncContext == null) {

      if (isInactive) {
        // user not seen recently, no responses should be collected
        return;
      }
      if (pendingResponses.size() > 1000) {
        pendingResponses.clear();
        // stop collecting responses for this user
        isInactive = true;
        if (secretPhrase == null) {
          // but only completely remove users that don't have unlocked accounts
          Users.remove(this);
        }
        return;
      }

      pendingResponses.offer(response);

    } else {

      JSONArray responses = new JSONArray();
      JSONStreamAware pendingResponse;
      while ((pendingResponse = pendingResponses.poll()) != null) {

        responses.add(pendingResponse);
      }
      responses.add(response);

      JSONObject combinedResponse = new JSONObject();
      combinedResponse.put("responses", responses);

      asyncContext.getResponse().setContentType("text/plain; charset=UTF-8");

      try (Writer writer = asyncContext.getResponse().getWriter()) {
        combinedResponse.writeJSONString(writer);
      } catch (IOException e) {
        Logger.logMessage("Error sending response to user", e);
      }

      asyncContext.complete();
      asyncContext = null;
    }
  }
Ejemplo n.º 27
0
  private synchronized void poll(
      HttpServletRequest request, HttpServletResponse response, String username)
      throws IOException {
    Map<String, Member> room = _rooms.get(request.getPathInfo());
    if (room == null) {
      response.sendError(503);
      return;
    }
    final Member member = room.get(username);
    if (member == null) {
      response.sendError(503);
      return;
    }

    synchronized (member) {
      if (member._queue.size() > 0) {
        // Send one chat message
        response.setContentType("text/json;charset=utf-8");
        StringBuilder buf = new StringBuilder();

        buf.append("{\"action\":\"poll\",");
        buf.append("\"from\":\"");
        buf.append(member._queue.poll());
        buf.append("\",");

        String message = member._queue.poll();
        int quote = message.indexOf('"');
        while (quote >= 0) {
          message = message.substring(0, quote) + '\\' + message.substring(quote);
          quote = message.indexOf('"', quote + 2);
        }
        buf.append("\"chat\":\"");
        buf.append(message);
        buf.append("\"}");
        byte[] bytes = buf.toString().getBytes("utf-8");
        response.setContentLength(bytes.length);
        response.getOutputStream().write(bytes);
      } else {
        AsyncContext async = request.startAsync();
        async.setTimeout(10000);
        async.addListener(member);
        if (!member._async.compareAndSet(null, async)) throw new IllegalStateException();
      }
    }
  }
 @Override
 protected void service(HttpServletRequest req, HttpServletResponse resp)
     throws ServletException, IOException {
   if (req.isAsyncStarted()) {
     req.getAsyncContext().complete();
   } else if (req.isAsyncSupported()) {
     AsyncContext actx = req.startAsync();
     actx.addListener(this);
     resp.setContentType("text/plain");
     clients.add(actx);
     if (clientcount.incrementAndGet() == 1) {
       ticker.addTickListener(this);
     }
   } else {
     new Exception("Async Not Supported").printStackTrace();
     resp.sendError(400, "Async is not supported.");
   }
 }
Ejemplo n.º 29
0
  /* (non-Javadoc)
   * @see javax.servlet.http.HttpServlet#service(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
   */
  @Override
  protected void service(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    resp.setContentType("text/html;charset=UTF-8");
    PrintWriter out = resp.getWriter();
    String str1 = "进入Servlet的时间:" + new Date() + ".";
    out.write(str1);
    System.out.println(str1);
    out.flush();

    // 在子线程中执行业务调用,并由其负责输出响应,主线程退出
    final AsyncContext ctx = req.startAsync();
    ctx.setTimeout(200000);
    new Work(ctx).start();
    ctx.addListener(new AsynServletListener());
    String str2 = "结束Servlet的时间:" + new Date() + ".";
    out.println(str2);
    out.flush();
    System.out.println(str2);
  }
Ejemplo n.º 30
-1
 public void doGet(HttpServletRequest req, HttpServletResponse res)
     throws ServletException, IOException {
   final AsyncContext asyncCtx = req.startAsync(req, res);
   AsyncAction asyncAction = new AsyncAction();
   asyncCtx.addListener(new MyAsyncListener());
   asyncCtx.start(asyncAction.f.service(asyncCtx));
 }