@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();
  }
    @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();
    }
Esempio n. 3
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
      public void onWritePossible() throws IOException {
        if (!written) {
          written = true;
          response.setContentLength(5);
          servletOutputStream.write("data\n".getBytes());
        }

        if (servletOutputStream.isReady()) {
          asyncContext.complete();
        }
      }
Esempio n. 5
0
 synchronized void processPendingResponses(HttpServletRequest req, HttpServletResponse resp)
     throws IOException {
   JSONArray responses = new JSONArray();
   JSONStreamAware pendingResponse;
   while ((pendingResponse = pendingResponses.poll()) != null) {
     responses.add(pendingResponse);
   }
   if (responses.size() > 0) {
     JSONObject combinedResponse = new JSONObject();
     combinedResponse.put("responses", responses);
     if (asyncContext != null) {
       asyncContext.getResponse().setContentType("text/plain; charset=UTF-8");
       try (Writer writer = asyncContext.getResponse().getWriter()) {
         combinedResponse.writeJSONString(writer);
       }
       asyncContext.complete();
       asyncContext = req.startAsync();
       asyncContext.addListener(new UserAsyncListener());
       asyncContext.setTimeout(5000);
     } else {
       resp.setContentType("text/plain; charset=UTF-8");
       try (Writer writer = resp.getWriter()) {
         combinedResponse.writeJSONString(writer);
       }
     }
   } else {
     if (asyncContext != null) {
       asyncContext.getResponse().setContentType("text/plain; charset=UTF-8");
       try (Writer writer = asyncContext.getResponse().getWriter()) {
         JSON.emptyJSON.writeJSONString(writer);
       }
       asyncContext.complete();
     }
     asyncContext = req.startAsync();
     asyncContext.addListener(new UserAsyncListener());
     asyncContext.setTimeout(5000);
   }
 }
Esempio n. 6
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) {

    }
  }
Esempio n. 7
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);
    }
  }
Esempio n. 8
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();
  }
Esempio n. 9
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);
  }
Esempio n. 11
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;
    }
  }
 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 */
     }
   }
 }
Esempio n. 13
0
  /*
   * (non-Javadoc)
   *
   * @see java.lang.Runnable#run()
   */
  @Override
  public void run() {
    try {
      if (timerValue > 0) {
        // Simulate long running operation
        Timer.startNew(timerValue);
      }
    } catch (InterruptedException e) {
      throw new IllegalStateException("Interrupted");
    }

    // Dispatch or complete
    if (useDispatch) {
      if (dispatchPath != null) {
        actx.dispatch(dispatchPath);
      } else {
        actx.dispatch();
      }
    } else {
      actx.complete();
    }
    logger.log("Async processing finished");
  }
Esempio n. 14
0
  public static int processNotification(String queueArn, String remoteAddress) {

    int messageCount = 0;

    long ts1 = System.currentTimeMillis();
    CMBControllerServlet.valueAccumulator.initializeAllCounters();

    contextQueues.putIfAbsent(queueArn, new ConcurrentLinkedQueue<AsyncContext>());
    ConcurrentLinkedQueue<AsyncContext> contextQueue = contextQueues.get(queueArn);

    AsyncContext asyncContext = contextQueue.poll();

    if (asyncContext == null) {
      logger.debug(
          "event=no_pending_receive queue_arn=" + queueArn + " remote_address=" + remoteAddress);
      return messageCount;
    }

    if (asyncContext.getRequest() == null) {
      logger.info(
          "event=skipping_invalid_context queue_arn="
              + queueArn
              + " remote_address="
              + remoteAddress);
      return messageCount;
    }

    if (!(asyncContext.getRequest() instanceof CQSHttpServletRequest)) {
      logger.info(
          "event=skipping_invalid_request queue_arn="
              + queueArn
              + " remote_address="
              + remoteAddress);
      return messageCount;
    }

    CQSHttpServletRequest request = (CQSHttpServletRequest) asyncContext.getRequest();

    // skip if request is already finished or outdated

    if (!request.isActive()
        || System.currentTimeMillis() - request.getRequestReceivedTimestamp()
            > request.getWaitTime()) {
      logger.info(
          "event=skipping_outdated_context queue_arn="
              + queueArn
              + " remote_address="
              + remoteAddress);
      return messageCount;
    }

    logger.debug(
        "event=notification_received queue_arn=" + queueArn + " remote_address=" + remoteAddress);

    try {

      CQSQueue queue = request.getQueue();
      List<CQSMessage> messageList =
          PersistenceFactory.getCQSMessagePersistence()
              .receiveMessage(queue, request.getReceiveAttributes());

      if (messageList.size() > 0) {

        messageCount = messageList.size();

        List<String> receiptHandles = new ArrayList<String>();

        for (CQSMessage message : messageList) {
          receiptHandles.add(message.getReceiptHandle());
        }

        request.setReceiptHandles(receiptHandles);
        request.setAttribute("lp", "yy"); // found lp call with messages
        CQSMonitor.getInstance()
            .addNumberOfMessagesReturned(queue.getRelativeUrl(), messageList.size());
        String out =
            CQSMessagePopulator.getReceiveMessageResponseAfterSerializing(
                messageList, request.getFilterAttributes(), request.getFilterMessageAttributes());
        Action.writeResponse(out, (HttpServletResponse) asyncContext.getResponse());
        long lp_ms = System.currentTimeMillis() - ts1;
        request.setAttribute("lp_ms", lp_ms);
        String cass_msString =
            String.valueOf(
                CQSControllerServlet.valueAccumulator.getCounter(AccumulatorName.CassandraTime));
        request.setAttribute("cass_ms", cass_msString);
        request.setAttribute(
            "cass_num_rd",
            CQSControllerServlet.valueAccumulator.getCounter(AccumulatorName.CassandraRead));
        request.setAttribute(
            "cass_num_wr",
            CQSControllerServlet.valueAccumulator.getCounter(AccumulatorName.CassandraWrite));
        request.setAttribute(
            "redis_ms",
            CQSControllerServlet.valueAccumulator.getCounter(AccumulatorName.RedisTime));
        request.setAttribute(
            "io_ms", CQSControllerServlet.valueAccumulator.getCounter(AccumulatorName.IOTime));

        asyncContext.complete();

      } else {

        // if there's longpoll time left, put back on queue

        if (request.getWaitTime()
                - System.currentTimeMillis()
                + request.getRequestReceivedTimestamp()
            > 0) {
          logger.info(
              "event=no_messages_found_for_longpoll_receive action=re_queueing time_left_ms="
                  + (request.getWaitTime()
                      - System.currentTimeMillis()
                      + request.getRequestReceivedTimestamp())
                  + " queue_arn="
                  + queueArn
                  + " remote_address="
                  + remoteAddress);
          contextQueue.offer(asyncContext);
        }
      }

    } catch (Exception ex) {
      logger.error("event=longpoll_queue_error queue_arn=" + queueArn, ex);
    } finally {
      CMBControllerServlet.valueAccumulator.deleteAllCounters();
    }

    return messageCount;
  }
 @Override
 public void onError(final AsyncEvent event) throws IOException {
   asyncContext.complete();
 }
Esempio n. 16
0
  /**
   * Processes the Issues related to my code request.
   *
   * @param request
   * @param response
   * @throws IOException
   * @throws ServletException
   * @throws JMSException
   * @throws SOAPException
   */
  private void processRelatedMyCodeRq(
      final HttpServletRequest request, HttpServletResponse response)
      throws IOException, JMSException, SOAPException, ServletException {
    final AsyncContext context = request.startAsync();

    // first check if the user is authenticated
    HttpSession session = request.getSession();

    boolean isAuthenticated =
        AuthenticatorService.authenticateUser(
            session.getAttribute(Configuration.USER_PRINCIPAL) != null
                ? (UserPrincipal) session.getAttribute(Configuration.USER_PRINCIPAL)
                : null);

    if (isAuthenticated) {
      UserPrincipal user = (UserPrincipal) session.getAttribute(Configuration.USER_PRINCIPAL);

      // send a message to Recommender to get the IDs of issues
      String uuid = user.getUuid();
      final Integer offset = Utils.parseInt(request.getParameter("offset"));
      final Integer limit = Utils.parseInt(request.getParameter("limit"));

      // first call API to get a list of issue URIs
      String requestId1 = Utils.genRequestID();
      String apiRq = MessageUtils.genAPIIssuesForUserMsg(uuid, requestId1);

      getAPIResponse(
          apiRq,
          requestId1,
          new MsgCallbackImpl(context) {
            @Override
            public void onSuccess(String apiResponse) throws Exception {
              List<Long> issueIds = MessageParser.parseAPIIssuesResponse(apiResponse);
              Properties props = createRequestProps(request);

              // now that I have the URIs, I have to call KEUI, to get the actual items
              String requestId2 = Utils.genRequestID();
              String keuiRq =
                  MessageUtils.genKEUIIssueListByIdMsg(issueIds, props, offset, limit, requestId2);

              getKEUIResponse(
                  keuiRq,
                  requestId2,
                  new MsgCallbackImpl(context) {
                    @Override
                    public void onSuccess(String keuiResp) throws Exception {
                      JSONObject result = MessageParser.parseKEUIItemsResponse(keuiResp);

                      Writer out = context.getResponse().getWriter();
                      result.writeJSONString(out);
                      out.flush();
                      out.close();
                      context.complete();
                    }
                  });
            }
          });
    } else {
      // if no user => send unauthorized
      if (log.isDebugEnabled())
        log.debug(
            "User with no session searching for issues related to their code, sending code 401!");

      response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
      context.complete();
    }
  }
Esempio n. 17
0
 /* ------------------------------------------------------------ */
 @Override
 public void complete() {
   AsyncContext context = _context;
   if (context == null) throw new IllegalStateException();
   _context.complete();
 }
  public void sendMessageOnChannel(
      HttpServletRequest request,
      final String message,
      final String channel,
      final 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

    //		final AsyncContext publisherAsyncCtx = request.startAsync();
    ServletContext appScope = request.getServletContext();
    @SuppressWarnings("unchecked")
    final Map<String, List<Subscriber>> clients =
        (Map<String, List<Subscriber>>) appScope.getAttribute(Keys.CLIENTS);
    final List<Subscriber> subscribers = new ArrayList<Subscriber>(clients.get(channel));

    // here is the logic for publishing - it will be passed to the container
    // for execution sometime in the future
    //		Runnable r = new Runnable() {
    //			@Override
    //			public void run() {
    System.out.println("updating games channel for " + subscribers.size() + " subscribers...");
    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 (null != excludeUsers
          && excludeUsers.length > 0
          && Arrays.asList(excludeUsers).contains(s.getUser().getUserName())) {
        continue;
      }
      synchronized (s) {
        AsyncContext aCtx = s.getaCtx();
        try {
          aCtx.getResponse().getOutputStream().print(message);
          aCtx.complete();
        } catch (Exception e) {
          System.err.println(
              "failed to send to client - removing from list of subscribers on this channel");
          toRemove.add(s);
        }
      }
    }

    // remove the failed subscribers from the model in app scope,
    // not our copy of them
    synchronized (clients) {
      clients.get(channel).removeAll(toRemove);
    }

    // log success
    long ms = System.currentTimeMillis() - start;
    String ok = "finished updating games channel " + channel + " in " + ms + " ms.";
    System.out.println(ok);

    //				publisherAsyncCtx.complete(); // we are done, the connection can
    //												// be closed now
    //			}
    //		};
    //
    //		// start the async processing (using a pool controlled by the container)
    //		publisherAsyncCtx.start(r);
  }
  private void process(HttpServletRequest request, HttpServletResponse resp) {

    AsyncContext asyncContext = request.startAsync();

    if (request.getRequestURL().toString().endsWith("/CORS")) {
      resp.addHeader("Access-Control-Allow-Origin", "*");
      resp.addHeader("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE");
      resp.addHeader(
          "Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    }

    // Just ACCEPT and REPLY OK if OPTIONS
    if (request.getMethod().equals("OPTIONS")) {
      resp.setStatus(HttpServletResponse.SC_OK);
    }

    String fullPath = request.getRequestURI();
    fullPath = (fullPath.substring(fullPath.indexOf("/service/") + 9));

    String parts[] = fullPath.split("/");

    String beanName = parts[0];
    String method = parts[1];

    String params = request.getParameter("params");

    if (request.getMethod().equals("POST")) {
      try {
        StringBuilder buffer = new StringBuilder();
        BufferedReader reader;

        reader = request.getReader();

        String line;

        while ((line = reader.readLine()) != null) {
          buffer.append(line);
        }

        params = buffer.toString();

      } catch (Exception e) {
        // TODO: handle exception
      }
    }

    JsonObject paramsObj = CommonUtils.parse(params).getAsJsonObject();

    String UID = session.getId(); // (paramsObj.get("sessionUID")).getAsString();

    NGSessionScopeContext.setCurrentContext(UID);

    receiveEvents.fire(new HalfDuplexDataReceivedEvent(paramsObj));

    Object result = remoteInvoker.invoke(locator.lookup(beanName, UID), method, paramsObj, UID);

    try {
      PrintWriter writer = asyncContext.getResponse().getWriter();
      writer.write(util.getJson(result));
      writer.flush();
      asyncContext.complete();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
 @Override
 public void onError(final Throwable t) {
   t.printStackTrace();
   asyncContext.complete();
 }