Java Code Examples for javax.servlet.AsyncContext#setTimeout()

The following examples show how to use javax.servlet.AsyncContext#setTimeout() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ITServlet3Container.java    From brave with Apache License 2.0 6 votes vote down vote up
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
  if (DispatcherType.ERROR.equals(req.getDispatcherType())) return; // don't loop

  AsyncContext ctx = req.startAsync();
  ctx.setTimeout(1 /* ms */);
  ctx.start(
    () -> {
      resp.setStatus(504);
      try {
        Thread.sleep(10L);
      } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
      } finally {
        ctx.complete();
      }
    });
}
 
Example 2
Source File: WebLogicRequestUpgradeStrategy.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
protected void handleSuccess(HttpServletRequest request, HttpServletResponse response,
		UpgradeInfo upgradeInfo, TyrusUpgradeResponse upgradeResponse) throws IOException, ServletException {

	response.setStatus(upgradeResponse.getStatus());
	upgradeResponse.getHeaders().forEach((key, value) -> response.addHeader(key, Utils.getHeaderFromList(value)));

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

	Object nativeRequest = getNativeRequest(request);
	BeanWrapper beanWrapper = new BeanWrapperImpl(nativeRequest);
	Object httpSocket = beanWrapper.getPropertyValue("connection.connectionHandler.rawConnection");
	Object webSocket = webSocketHelper.newInstance(request, httpSocket);
	webSocketHelper.upgrade(webSocket, httpSocket, request.getServletContext());

	response.flushBuffer();

	boolean isProtected = request.getUserPrincipal() != null;
	Writer servletWriter = servletWriterHelper.newInstance(webSocket, isProtected);
	Connection connection = upgradeInfo.createConnection(servletWriter, noOpCloseListener);
	new BeanWrapperImpl(webSocket).setPropertyValue("connection", connection);
	new BeanWrapperImpl(servletWriter).setPropertyValue("connection", connection);
	webSocketHelper.registerForReadEvent(webSocket);
}
 
Example 3
Source File: ProxyServlet.java    From openwebbeans-meecrowave with Apache License 2.0 6 votes vote down vote up
protected CompletionStage<HttpServletResponse> doExecute(final Routes.Route route,
                                                         final HttpServletRequest req, final HttpServletResponse resp,
                                                         final String prefix) throws IOException {
    final AsyncContext asyncContext = req.startAsync();
    asyncContext.setTimeout(route.clientConfiguration.timeouts.execution);

    return doRequest(route, req, resp, prefix)
            .thenAccept(response -> {
                try {
                    forwardResponse(route, response, req, resp, identity());
                } catch (final IOException e) {
                    onError(route, req, resp, e);
                }
    }).exceptionally(error -> onError(route, req, resp, error)).whenComplete((a, b) -> asyncContext.complete())
            .thenApply(i -> resp);
}
 
Example 4
Source File: TestAsyncContextImpl.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Override
protected void doGet(final HttpServletRequest req,
        final HttpServletResponse resp)
        throws ServletException, IOException {

    final AsyncContext async = req.startAsync();
    // Just for debugging
    async.setTimeout(100000);

    ExecutorService executor = Executors.newSingleThreadExecutor();
    executor.submit(new Runnable() {

        @Override
        public void run() {
            async.dispatch("/ServletC");
        }
    });
    executor.shutdown();
}
 
Example 5
Source File: TestAsyncContextImpl.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {

    final AsyncContext actxt = req.startAsync();
    actxt.setTimeout(TIMEOUT);
    if (threaded) {
        actxt.start(new Runnable() {
            @Override
            public void run() {
                try {
                    resp.sendError(status, ERROR_MESSAGE);
                    actxt.complete();
                } catch (IOException e) {
                    // Ignore
                }
            }
        });
    } else {
        resp.sendError(status, ERROR_MESSAGE);
        actxt.complete();
    }
}
 
Example 6
Source File: ServletRestDispatcher.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
public void service(HttpServletRequest request, HttpServletResponse response) {
  if (transport == null) {
    transport = SCBEngine.getInstance().getTransportManager().findTransport(Const.RESTFUL);
    microserviceMeta = SCBEngine.getInstance().getProducerMicroserviceMeta();
  }

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

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

  if (SCBEngine.getInstance().isFilterChainEnabled()) {
    ((StandardHttpServletRequestEx) requestEx).setCacheRequest(true);
    InvocationCreator creator = new RestServletProducerInvocationCreator(microserviceMeta, transport.getEndpoint(),
        requestEx, responseEx);
    new RestProducerInvocationFlow(creator, requestEx, responseEx)
        .run();
    return;
  }

  RestServletProducerInvocation restProducerInvocation = new RestServletProducerInvocation();
  restProducerInvocation.invoke(transport, requestEx, responseEx, httpServerFilters);
}
 
Example 7
Source File: TestCoyoteOutputStream.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    resp.setContentType("text/plain");
    resp.setCharacterEncoding("UTF-8");
    ServletOutputStream sos = resp.getOutputStream();


    AsyncContext asyncCtxt = req.startAsync();
    asyncCtxt.setTimeout(5);
    Runnable task = new AsyncTask(asyncCtxt, sos);
    if (useContainerThreadToSetListener) {
        asyncCtxt.start(task);
    } else {
        Thread t = new Thread(task);
        t.start();
    }
}
 
Example 8
Source File: TestAsyncContextImpl.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
@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 9
Source File: AsyncZuulServlet.java    From s2g-zuul with MIT License 6 votes vote down vote up
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	Transaction tran = Cat.getProducer().newTransaction("AsyncZuulServlet", req.getRequestURL().toString());
    req.setAttribute("org.apache.catalina.ASYNC_SUPPORTED", true);
    AsyncContext asyncContext = req.startAsync();
    asyncContext.setTimeout(asyncTimeout.get());
    asyncContext.addListener(new AsyncZuulListener());
    try {
    	Context ctx = new CatContext();
    	Cat.logRemoteCallClient(ctx);
        poolExecutorRef.get().submit(new ZuulCallable(ctx,asyncContext, zuulRunner,req));            
        tran.setStatus(Transaction.SUCCESS);
    } catch (RuntimeException e) {
        Cat.logError(e);
        tran.setStatus(e);
        rejectedRequests.incrementAndGet();
        throw e;
    }finally{
    	tran.complete();
    }
}
 
Example 10
Source File: TestAsyncContextImpl.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@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 11
Source File: TestAsyncContextImpl.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@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(trackingListener);
        }
    } else {
        resp.getWriter().print("FAIL: Async unsupported");
    }
}
 
Example 12
Source File: RequestTracingFilterComponentTest.java    From wingtips with Apache License 2.0 5 votes vote down vote up
public void doGet(HttpServletRequest request, final HttpServletResponse response) {
    if (DispatcherType.ERROR.equals(request.getDispatcherType())) {
        return;
    }

    final AsyncContext asyncContext = request.startAsync(request, response);
    asyncContext.setTimeout(SLEEP_TIME_MILLIS);
}
 
Example 13
Source File: HttpAsyncClient.java    From uavstack with Apache License 2.0 5 votes vote down vote up
/**
 * buildProcCallback
 * 
 * @param callBack
 * @param request
 * @return
 */
private AsyncReqProcWithHttpClientCallback buildProcCallback(HttpClientCallback callBack,
        HttpServletRequest request) {

    AsyncContext ac = request.startAsync();

    AsyncReqProcWithHttpClientCallback proc = new AsyncReqProcWithHttpClientCallback(ac, callBack);

    ac.addListener(proc);
    ac.setTimeout(2500);
    return proc;
}
 
Example 14
Source File: TestAbstractHttp11Processor.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    if (bug55772IsSecondRequest) {
        Cookie[] cookies = req.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : req.getCookies()) {
                if (cookie.getName().equalsIgnoreCase("something.that.should.not.leak")) {
                    bug55772RequestStateLeaked = true;
                }
            }
        }
        bug55772Latch3.countDown();
    } else {
        req.getCookies(); // We have to do this so Tomcat will actually parse the cookies from the request
    }

    req.setAttribute("org.apache.catalina.ASYNC_SUPPORTED", Boolean.TRUE);
    AsyncContext asyncContext = req.startAsync();
    asyncContext.setTimeout(5000);

    bug55772Latch1.countDown();

    PrintWriter writer = asyncContext.getResponse().getWriter();
    writer.print('\n');
    writer.flush();

    bug55772Latch2.countDown();
}
 
Example 15
Source File: TestHttp11Processor.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    if (bug55772IsSecondRequest) {
        Cookie[] cookies = req.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : req.getCookies()) {
                if (cookie.getName().equalsIgnoreCase("something.that.should.not.leak")) {
                    bug55772RequestStateLeaked = true;
                }
            }
        }
        bug55772Latch3.countDown();
    } else {
        req.getCookies(); // We have to do this so Tomcat will actually parse the cookies from the request
    }

    req.setAttribute("org.apache.catalina.ASYNC_SUPPORTED", Boolean.TRUE);
    AsyncContext asyncContext = req.startAsync();
    asyncContext.setTimeout(5000);

    bug55772Latch1.countDown();

    PrintWriter writer = asyncContext.getResponse().getWriter();
    writer.print('\n');
    writer.flush();

    bug55772Latch2.countDown();
}
 
Example 16
Source File: TestAsyncContextImpl.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@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 17
Source File: TestAsyncContextImpl.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
@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 18
Source File: TestAbstractHttp11Processor.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    if (bug55772IsSecondRequest) {
        Cookie[] cookies = req.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : req.getCookies()) {
                if (cookie.getName().equalsIgnoreCase("something.that.should.not.leak")) {
                    bug55772RequestStateLeaked = true;
                }
            }
        }
        bug55772Latch3.countDown();
    } else {
        req.getCookies(); // We have to do this so Tomcat will actually parse the cookies from the request
    }

    req.setAttribute("org.apache.catalina.ASYNC_SUPPORTED", Boolean.TRUE);
    AsyncContext asyncContext = req.startAsync();
    asyncContext.setTimeout(5000);

    bug55772Latch1.countDown();

    PrintWriter writer = asyncContext.getResponse().getWriter();
    writer.print('\n');
    writer.flush();

    bug55772Latch2.countDown();
}
 
Example 19
Source File: LongPollingProcessServiceImpl.java    From qconfig with MIT License 5 votes vote down vote up
@Override
public void process(AsyncContext context, List<CheckRequest> requests) {
    IpAndPort address = new IpAndPort(clientInfoService.getIp(), clientInfoService.getPort());
    AsyncContextHolder contextHolder = new AsyncContextHolder(context, address);
    context.setTimeout(timeout);
    context.addListener(new TimeoutServletListener(contextHolder));
    processCheckRequests(requests, clientInfoService.getIp(), contextHolder);
}
 
Example 20
Source File: AsyncCrnkServlet.java    From crnk-framework with Apache License 2.0 4 votes vote down vote up
@Override
public void service(ServletRequest req, ServletResponse res) throws IOException {
	PreconditionUtil
			.assertTrue("only http supported, ", req instanceof HttpServletRequest && res instanceof HttpServletResponse);

	HttpServletResponse httpResponse = (HttpServletResponse) res;

	ServletContext servletContext = getServletContext();
	ServletRequestContext context = new ServletRequestContext(servletContext, (HttpServletRequest) req,
			httpResponse, boot.getWebPathPrefix());
	RequestDispatcher requestDispatcher = boot.getRequestDispatcher();

	long startTime = System.currentTimeMillis();
	LOGGER.debug("setting up request");

	Optional<Result<HttpResponse>> optResponse = requestDispatcher.process(context);
	if (optResponse.isPresent()) {
		Result<HttpResponse> response = optResponse.get();
		response = response.setTimeout(timeout);

		AsyncContext asyncCtx = req.startAsync();

		// timeout fallback on http layer
		asyncCtx.setTimeout(timeout.toMillis() + 2000);

		asyncCtx.addListener(new AsyncAdapter() {

			@Override
			public void onTimeout(AsyncEvent event) {
				LOGGER.error("timeout for request {}", event);
				httpResponse.setStatus(HttpStatus.GATEWAY_TIMEOUT_504);

			}

		});
		response.subscribe(it -> {
					LOGGER.debug("writing response");
					it.getHeaders().entrySet().forEach(entry -> httpResponse.setHeader(entry.getKey(), entry.getValue()));
					httpResponse.setStatus(it.getStatusCode());
					try (ServletOutputStream outputStream = httpResponse.getOutputStream()) {
						byte[] body = it.getBody();
						if (body != null) {
							LOGGER.debug("response bodyLength={}", body.length);
							outputStream.write(body);
						}
					} catch (Exception e) {
						LOGGER.error("failed to process request", e);
					} finally {
						asyncCtx.complete();
						LOGGER.debug("response completed");
					}
				}, exception -> {
					LOGGER.error("failed to process request", exception);
					if (exception instanceof TimeoutException) {
						httpResponse.setStatus(HttpStatus.GATEWAY_TIMEOUT_504);
					} else {
						httpResponse.setStatus(HttpStatus.INTERNAL_SERVER_ERROR_500);
					}
					asyncCtx.complete();
				}
		);
	} else {
		httpResponse.setStatus(HttpStatus.NOT_FOUND_404);
	}

	long endTime = System.currentTimeMillis();
	LOGGER.debug("prepared request in in {}ms", endTime - startTime);
}