コード例 #1
1
ファイル: AsyncServlet.java プロジェクト: matheusgg/OCEJWCD
  @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);
  }
コード例 #2
0
 @Override
 protected void service(HttpServletRequest req, HttpServletResponse res)
     throws ServletException, IOException {
   Data data = (Data) req.getAttribute("data");
   if (null == data) {
     contexts.add(req.startAsync(req, res));
   } else {
     PrintWriter writer = res.getWriter();
     data.print(writer);
     writer.flush();
     contexts.add(req.startAsync(req, res));
   }
 }
コード例 #3
0
 @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();
   }
 }
コード例 #4
0
  /**
   * Processes the clients commit details request.
   *
   * @param request
   * @param response
   * @throws Exception
   */
  private void processCommitDetailsRq(HttpServletRequest request, HttpServletResponse response)
      throws Exception {
    final AsyncContext context = request.startAsync();

    String itemId = request.getParameter(QUERY_PARAM);
    String requestId = Utils.genRequestID();

    String requestMsg = MessageUtils.genAPICommitDetailsMsg(itemId, requestId);

    getAPIResponse(
        requestMsg,
        requestId,
        new MsgCallbackImpl(context) {
          @Override
          public void onSuccess(String msg) throws Exception {
            JSONObject result = MessageParser.parseAPICommitDetailsMessage(msg);

            Writer out = context.getResponse().getWriter();
            result.writeJSONString(out);
            out.flush();
            out.close();
            context.complete();
          }
        });
  }
コード例 #5
0
    @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();
      }
    }
コード例 #6
0
  /**
   * Processes the clients Duplicate issue detection request.
   *
   * @param request
   * @param response
   * @throws Exception
   */
  private void processDuplicateIssueRq(HttpServletRequest request, HttpServletResponse response)
      throws Exception {
    final AsyncContext context = request.startAsync();

    Properties props = createRequestProps(request);

    String requestId = Utils.genRequestID();
    String requestMsg = MessageUtils.genKEUIDuplicateIssueMsg(props, requestId);

    getKEUIResponse(
        requestMsg,
        requestId,
        new MsgCallbackImpl(context) {
          @Override
          public void onSuccess(String msg) throws Exception {
            JSONObject result = MessageParser.parseKEUIDuplicateResponse(msg);

            Writer out = context.getResponse().getWriter();
            result.writeJSONString(out);
            out.flush();
            out.close();
            context.complete();
          }
        });
  }
コード例 #7
0
  /**
   * Processes the request for suggesting developers who can fix an issue
   *
   * @param request
   * @param response
   * @throws JMSException
   * @throws ServletException
   * @throws IOException
   */
  private void processSuggestDevelopersRq(HttpServletRequest request, HttpServletResponse response)
      throws JMSException, ServletException, IOException {
    final AsyncContext context = request.startAsync();

    Long issueId = Long.parseLong(request.getParameter("issueId"));

    String requestId = Utils.genRequestID();
    String requestMsg =
        MessageUtils.genRecommenderIdentityMsg(Arrays.asList(new Long[] {issueId}), requestId);

    getRecommenderIdentityResponse(
        requestMsg,
        requestId,
        new MsgCallbackImpl(context) {
          @Override
          public void onSuccess(String msg) throws Exception {
            JSONObject result = MessageParser.parseRecommenderIdentitiesMsg(msg);

            Writer out = context.getResponse().getWriter();
            result.writeJSONString(out);
            out.flush();
            out.close();
            context.complete();
          }
        });
  }
コード例 #8
0
 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;
 }
コード例 #9
0
    @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();
    }
コード例 #10
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();
   }
 }
コード例 #11
0
    @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");
    }
コード例 #12
0
ファイル: ScreenController.java プロジェクト: headmap/tetris
 @Override
 public void handleRequest(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   AsyncContext asyncContext = request.startAsync();
   if ("true".equals(request.getParameter("allPlayersScreen"))) {
     screenSender.scheduleUpdate(new UpdateRequest(asyncContext, true, null));
   } else {
     Set<String> playersToUpdate = request.getParameterMap().keySet();
     screenSender.scheduleUpdate(new UpdateRequest(asyncContext, false, playersToUpdate));
   }
 }
コード例 #13
0
ファイル: MyAsyncServlet.java プロジェクト: matheusgg/OCEJWCD
  /**
   * 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();
  }
コード例 #14
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...");
  }
コード例 #15
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();
   }
 }
コード例 #16
0
ファイル: User.java プロジェクト: Rongmasihai/risecoin
 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);
   }
 }
コード例 #17
0
    @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);
    }
コード例 #18
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(); // 完成,进行响应
       });
 }
コード例 #19
0
    @Override
    protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {

      result = new StringBuilder();
      result.append('1');
      result.append(req.isAsyncStarted());
      req.startAsync();
      result.append('2');
      result.append(req.isAsyncStarted());

      req.getAsyncContext()
          .start(
              new Runnable() {
                @Override
                public void run() {
                  Thread t =
                      new Thread(
                          new Runnable() {
                            @Override
                            public void run() {
                              try {
                                result.append('3');
                                result.append(req.isAsyncStarted());
                                Thread.sleep(1000);
                                result.append('4');
                                result.append(req.isAsyncStarted());
                                resp.setContentType("text/plain");
                                resp.getWriter().print("OK");
                                req.getAsyncContext().complete();
                                result.append('5');
                                result.append(req.isAsyncStarted());
                                done = true;
                              } catch (InterruptedException e) {
                                result.append(e);
                              } catch (IOException e) {
                                result.append(e);
                              }
                            }
                          });
                  t.start();
                }
              });
      // Pointless method call so there is somewhere to put a break point
      // when debugging
      req.getMethod();
    }
コード例 #20
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.");
   }
 }
コード例 #22
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);
  }
コード例 #23
0
  @Override
  protected void service(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    AsyncContext context = request.startAsync();
    AsyncContextSynchronizer synchronizer = new AsyncContextSynchronizer(context);

    RequestBodyPublisher requestPublisher = new RequestBodyPublisher(synchronizer, BUFFER_SIZE);
    request.getInputStream().setReadListener(requestPublisher);
    ServletServerHttpRequest httpRequest = new ServletServerHttpRequest(request, requestPublisher);

    ResponseBodySubscriber responseSubscriber = new ResponseBodySubscriber(synchronizer);
    response.getOutputStream().setWriteListener(responseSubscriber);
    ServletServerHttpResponse httpResponse =
        new ServletServerHttpResponse(response, responseSubscriber);

    HandlerResultSubscriber resultSubscriber =
        new HandlerResultSubscriber(synchronizer, httpResponse);
    this.handler.handle(httpRequest, httpResponse).subscribe(resultSubscriber);
  }
コード例 #24
0
 @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();
 }
コード例 #25
0
  private void doLongPollConnect(
      HttpServletRequest request, HttpServletResponse response, String transport) {
    response.setCharacterEncoding("utf-8");
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setContentType("text/" + (transport.equals("longpolljsonp") ? "javascript" : "plain"));

    final String id = request.getParameter("id");
    final int count = Integer.parseInt(request.getParameter("count"));
    final int lastEventId = Integer.parseInt(request.getParameter("lastEventId"));

    AsyncContext aCtx = request.startAsync(request, response);
    aCtx.addListener(
        new AsyncListener() {
          @Override
          public void onTimeout(AsyncEvent event) throws IOException {
            LOGGER.debug("onTimeout {}: {}", id, event);
            cleanup(event);
          }

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

          @Override
          public void onError(AsyncEvent event) throws IOException {
            LOGGER.debug("onError {}: {}", id, event);
            cleanup(event);
          }

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

          private void cleanup(AsyncEvent event) {
            connections.removeClient(id, count);
          }
        });

    connections.clientRequest(id, count, lastEventId, aCtx, Security.getUserDetails());
  }
コード例 #26
0
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

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

      asyncContext.addListener(new TrackingListener(false, false, null));

      asyncContext.start(
          new Runnable() {

            @Override
            public void run() {
              try {
                Thread.sleep(3 * 1000);
                asyncContext.getResponse().getWriter().write("Runnable-");
                asyncContext.complete();
              } catch (Exception e) {
                e.printStackTrace();
              }
            }
          });
    }
コード例 #27
0
  @RequestMapping("/log")
  @NeedLogin
  public void log(HttpServletRequest request, HttpServletResponse response) {

    /*String filename = request.getParameter("filename");
    File file = new File(filename);
    if(!file.exists()){
        return "file.not.exist";
    }*/

    final AsyncContext asyncContext = request.startAsync();
    asyncContext.setTimeout(-1);

    Thread thread =
        new Thread() {

          boolean flag = true;

          public void run() {
            while (flag) {
              try {
                Thread.sleep(1000);
                asyncContext
                    .getResponse()
                    .getWriter()
                    .println("currentTIme == " + System.currentTimeMillis());
              } catch (Exception e) {
                e.printStackTrace();
                flag = false;
              }
            }
          }
        };

    thread.start();
  }
コード例 #28
0
  /**
   * Processes the request for recommending developers to fix an issue.
   *
   * @param request
   * @param response
   * @throws IOException
   * @throws ServletException
   * @throws JMSException
   */
  @SuppressWarnings("unchecked")
  private void processSuggestForPeopleRq(
      final HttpServletRequest request, HttpServletResponse response)
      throws IOException, JMSException, ServletException {
    final AsyncContext context = request.startAsync();

    final List<String> uuidList = Arrays.asList(new String[] {request.getParameter("person")});

    final Integer offset = Utils.parseInt(request.getParameter("offset"));
    final Integer limit = Utils.parseInt(request.getParameter("limit"));

    // send messages to Recommender to get the IDs
    final String requestId1 = Utils.genRequestID();

    String recommenderIssueRq = MessageUtils.genRecommenderIssuesMsg(uuidList, requestId1);
    getRecommenderIssueResponse(
        recommenderIssueRq,
        requestId1,
        new MsgCallbackImpl(context) {
          @Override
          public void onSuccess(String recommenderIssueResp) throws Exception {
            List<Long> issueIds = MessageParser.parseRecommenderIssueIdsMsg(recommenderIssueResp);
            Properties props = createRequestProps(request);

            // now that I have the issueIDs I have to send them to the KEUI component
            final 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 {
                    final JSONObject result = MessageParser.parseKEUIItemsResponse(keuiResp);

                    // on the first page also show the modules
                    if (offset == 0) {
                      final String requestId3 = Utils.genRequestID();
                      String recommenderModuleRq =
                          MessageUtils.genRecommenderModulesMsg(uuidList, requestId3);

                      getRecommenderModuleResponse(
                          recommenderModuleRq,
                          requestId3,
                          new MsgCallbackImpl(context) {
                            @Override
                            public void onSuccess(String recommenderModuleResp) throws Exception {
                              List<String> moduleIds =
                                  MessageParser.parseRecommenderModuleIdsMsg(recommenderModuleResp);

                              JSONArray modulesJSon = new JSONArray();
                              modulesJSon.addAll(moduleIds);
                              result.put("modules", modulesJSon);

                              Writer out = context.getResponse().getWriter();
                              result.writeJSONString(out);
                              out.flush();
                              out.close();
                              context.complete();
                            }
                          });
                    } else {
                      Writer out = context.getResponse().getWriter();
                      result.writeJSONString(out);
                      out.flush();
                      out.close();
                      context.complete();
                    }
                  }
                });
          }
        });
  }
コード例 #29
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();
    }
  }
コード例 #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));
 }