Java Code Examples for javax.servlet.http.HttpServletRequest.startAsync()

The following are Jave code examples for showing how to use startAsync() of the javax.servlet.http.HttpServletRequest class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: incubator-servicecomb-java-chassis   File: ServletRestDispatcher.java   View Source Code Vote up 6 votes
public void service(HttpServletRequest request, HttpServletResponse response) {
  if (transport == null) {
    transport = CseContext.getInstance().getTransportManager().findTransport(Const.RESTFUL);
  }

  // 异步场景
  final AsyncContext asyncCtx = request.startAsync();
  asyncCtx.addListener(restAsyncListener);
  asyncCtx.setTimeout(ServletConfig.getServerTimeout());

  HttpServletRequestEx requestEx = new StandardHttpServletRequestEx(request);
  HttpServletResponseEx responseEx = new StandardHttpServletResponseEx(response);

  RestServletProducerInvocation restProducerInvocation = new RestServletProducerInvocation();
  restProducerInvocation.invoke(transport, requestEx, responseEx, httpServerFilters);
}
 
Example 2
Project: Mastering-Java-EE-Development-with-WildFly   File: ReadingServlet.java   View Source Code Vote up 6 votes
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
	response.setContentType("text/html;charset=UTF-8");
	try (PrintWriter output = response.getWriter()) {
		output.println("<html>");
		output.println("<head>");
		output.println("<title>Reading asynchronously</title>");
		output.println("</head>");
		output.println("<body>");
		output.println("<h1>Reading asynchronously</h1>");

		AsyncContext context = request.startAsync();
		ServletInputStream input = request.getInputStream();
		input.setReadListener(new ReadingListener(input, context));

		output.println("</body>");
		output.println("</html>");
	}
}
 
Example 3
Project: lams   File: ServletServerHttpAsyncRequestControl.java   View Source Code Vote up 6 votes
@Override
public void start(long timeout) {

	Assert.state(!isCompleted(), "Async processing has already completed");

	if (isStarted()) {
		return;
	}

	HttpServletRequest servletRequest = this.request.getServletRequest();
	HttpServletResponse servletResponse = this.response.getServletResponse();

	this.asyncContext = servletRequest.startAsync(servletRequest, servletResponse);
	this.asyncContext.addListener(this);

	if (timeout != NO_TIMEOUT_VALUE) {
		this.asyncContext.setTimeout(timeout);
	}
}
 
Example 4
Project: apache-tomcat-7.0.73-with-comment   File: AsyncStockServlet.java   View Source Code Vote up 6 votes
@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.");
    }
}
 
Example 5
Project: apache-tomcat-7.0.73-with-comment   File: TestAbstractHttp11Processor.java   View Source Code Vote up 6 votes
@Override
protected void doPut(HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    final AsyncContext ac = req.startAsync();
    ac.start(new Runnable() {
        @Override
        public void run() {
            resp.setContentType("text/plain");
            resp.setCharacterEncoding("UTF-8");
            try {
                resp.getWriter().print("OK");
            } catch (IOException e) {
                // Should never happen. Test will fail if it does.
            }
            ac.complete();
        }
    });
}
 
Example 6
Project: tomcat7   File: TestAsyncContextImpl.java   View Source Code Vote up 6 votes
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    if (req.isAsyncSupported()) {
        TestAsyncContextImpl.track("TimeoutServletGet-");
        final AsyncContext ac = req.startAsync();
        ac.setTimeout(ASYNC_TIMEOUT);

        if (completeOnTimeout != null) {
            ac.addListener(new TrackingListener(false,
                    completeOnTimeout.booleanValue(), dispatchUrl));
        }
    } else {
        resp.getWriter().print("FAIL: Async unsupported");
    }
}
 
Example 7
Project: Spring-Security-Third-Edition   File: AsyncDispatcherServlet.java   View Source Code Vote up 6 votes
@Override
protected void doDispatch(final HttpServletRequest request, final HttpServletResponse response) throws Exception {

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

    ac.setTimeout(TIME_OUT);

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

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

    ac.addListener(new AsyncDispatcherServletListener(task));
    exececutor.execute(task);
}
 
Example 8
Project: JInsight   File: AsyncServlet.java   View Source Code Vote up 6 votes
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
  final String uuid = request.getParameter(UUID_PARAM);
  final AsyncContext acontext = request.startAsync();
  acontext.start(() -> {
    HttpServletResponse httpServletResponse = (HttpServletResponse) acontext.getResponse();
    try {
      System.out.println("Sleeping");
      Thread.sleep(5000);
      System.out.println("DONE Sleeping");
      httpServletResponse.getOutputStream().write(uuid.getBytes());
    } catch (InterruptedException | IOException | RuntimeException e) {
      try {
        httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
      } catch (IOException e1) {
        e1.printStackTrace();
      }
    }
    System.out.println("completing");
    acontext.complete();
  });
}
 
Example 9
Project: apache-tomcat-7.0.73-with-comment   File: AsyncStockServlet.java   View Source Code Vote up 6 votes
@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.");
    }
}
 
Example 10
Project: apache-tomcat-7.0.73-with-comment   File: TestErrorReportValve.java   View Source Code Vote up 6 votes
@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();
    }
}
 
Example 11
Project: Mastering-Java-EE-Development-with-WildFly   File: WritingServlet.java   View Source Code Vote up 5 votes
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
	response.setContentType("text/html;charset=UTF-8");

	AsyncContext context = request.startAsync();
	ServletOutputStream output = response.getOutputStream();
	output.setWriteListener(new WritingListener(output, context));
}
 
Example 12
Project: apache-tomcat-7.0.73-with-comment   File: TestAsyncContextImpl.java   View Source Code Vote up 5 votes
@Override
protected void doGet(final HttpServletRequest req,
        final HttpServletResponse resp)
        throws ServletException, IOException {

    String echo = req.getParameter("echo");
    AsyncContext actxt = req.startAsync();
    TestAsyncContextImpl.track("OK");
    if (echo != null) {
        TestAsyncContextImpl.track("-" + echo);
    }
    // Speed up the test by reducing the timeout
    actxt.setTimeout(ASYNC_TIMEOUT);
}
 
Example 13
Project: tomcat7   File: TestAsyncContextImpl.java   View Source Code Vote up 5 votes
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    track("doGet-startAsync-");
    AsyncContext ac = req.startAsync();
    if (addTrackingListener) {
        ac.addListener(new StickyTrackingListener(false, false, null));
    }
    ac.dispatch(target);
 }
 
Example 14
Project: tomcat7   File: TestAsyncContextImpl.java   View Source Code Vote up 5 votes
@Override
protected void doGet(final HttpServletRequest req,
        final HttpServletResponse resp)
        throws ServletException, IOException {

    AsyncContext actxt = req.startAsync();
    actxt.setTimeout(3000);
    resp.setContentType("text/plain");
    resp.getWriter().print("OK");
    actxt.complete();
}
 
Example 15
Project: tomcat7   File: TestAsyncContextImpl.java   View Source Code Vote up 5 votes
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    if ("y".equals(req.getParameter(DISPATCH_CHECK))) {
        if (req.getDispatcherType() != DispatcherType.ASYNC) {
            track("WrongDispatcherType-");
        }
    }
    track("DispatchingServletGet-");
    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 +
                        "&" + DISPATCH_CHECK + "=y");
            } else {
                ctxt.dispatch("/stage2");
            }
        }
    };
    if ("y".equals(req.getParameter("useThread"))) {
        new Thread(run).start();
    } else {
        run.run();
    }
}
 
Example 16
Project: apache-tomcat-7.0.73-with-comment   File: TestAsyncContextImpl.java   View Source Code Vote up 5 votes
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    TestAsyncContextImpl.track("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();
    }
}
 
Example 17
Project: apache-tomcat-7.0.73-with-comment   File: TestAsyncContextImpl.java   View Source Code Vote up 5 votes
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    Integer countObj = (Integer) req.getAttribute("count");
    int count = 0;
    if (countObj != null) {
        count = countObj.intValue();
    }
    count++;
    req.setAttribute("count", Integer.valueOf(count));

    String encodedUri = req.getRequestURI();
    UDecoder uDecoder = new UDecoder();
    String decodedUri = uDecoder.convert(encodedUri, false);

    try {
        // Just here to trigger the error
        @SuppressWarnings("unused")
        URI u = new URI(encodedUri);
    } catch (URISyntaxException e) {
        throw new ServletException(e);
    }

    if (count > 3) {
        resp.setContentType("text/plain");
        resp.getWriter().print("OK");
    } else {
        AsyncContext ac = req.startAsync();
        ac.dispatch(decodedUri);
    }
}
 
Example 18
Project: tomcat7   File: TestAsyncContextImpl.java   View Source Code Vote up 5 votes
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    // Should not be async at this point
    isAsyncWhenExpected = isAsyncWhenExpected && !req.isAsyncStarted();

    final AsyncContext async = req.startAsync();

    // Should be async at this point
    isAsyncWhenExpected = isAsyncWhenExpected && req.isAsyncStarted();

    async.start(new Runnable() {

        @Override
        public void run() {
            // This should be delayed until the original container
            // thread exists
            async.dispatch("/ServletB");
        }
    });

    try {
        Thread.sleep(3000);
    } catch (InterruptedException e) {
        throw new ServletException(e);
    }

    // Should be async at this point
    isAsyncWhenExpected = isAsyncWhenExpected && req.isAsyncStarted();
}
 
Example 19
Project: tomcat7   File: TestAsyncContextImpl.java   View Source Code Vote up 5 votes
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    Integer countObj = (Integer) req.getAttribute("count");
    int count = 0;
    if (countObj != null) {
        count = countObj.intValue();
    }
    count++;
    req.setAttribute("count", Integer.valueOf(count));

    String encodedUri = req.getRequestURI();
    UDecoder uDecoder = new UDecoder();
    String decodedUri = uDecoder.convert(encodedUri, false);

    try {
        // Just here to trigger the error
        @SuppressWarnings("unused")
        URI u = new URI(encodedUri);
    } catch (URISyntaxException e) {
        throw new ServletException(e);
    }

    if (count > 3) {
        resp.setContentType("text/plain");
        resp.getWriter().print("OK");
    } else {
        AsyncContext ac = req.startAsync();
        ac.dispatch(decodedUri);
    }
}
 
Example 20
Project: apache-tomcat-7.0.73-with-comment   File: TestAsyncContextImpl.java   View Source Code Vote up 5 votes
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    track("doGet-startAsync-");
    AsyncContext ac = req.startAsync();
    if (addTrackingListener) {
        ac.addListener(new StickyTrackingListener(false, false, null));
    }
    ac.dispatch(target);
 }