javax.servlet.AsyncContext Java Examples

The following examples show how to use javax.servlet.AsyncContext. 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: AsyncStockServlet.java    From Tomcat8-Source-Read with MIT License 7 votes vote down vote up
@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) {
            Stockticker ticker = (Stockticker) req.getServletContext().getAttribute(
                    AsyncStockContextListener.STOCK_TICKER_KEY);
            ticker.addTickListener(this);
        }
    } else {
        new Exception("Async Not Supported").printStackTrace();
        resp.sendError(400,"Async is not supported.");
    }
}
 
Example #2
Source File: PortletAsyncContextImpl.java    From portals-pluto with Apache License 2.0 6 votes vote down vote up
public PortletAsyncContextImpl(AsyncContext actx, PortletResourceRequestContext prctx, ResourceRequest resreq, ResourceResponse resresp, boolean origReqResp) {
   this.actx = actx;
   this.prctx = prctx;
   this.resreq = resreq;
   this.resresp = resresp;
   this.hasOriginalReqResp = origReqResp;

   this.hreq = (HttpServletRequest) actx.getRequest();
   this.beanmgr = prctx.getBeanManager();

   // get the original container req & resp to pass to listener for resource releasing

   HttpServletRequest creq = prctx.getContainerRequest();
   HttpServletResponse cresp = prctx.getContainerResponse();

   pal = new PortletAsyncContextListener(this);
   actx.addListener(pal, creq, cresp);
}
 
Example #3
Source File: AsyncStockServlet.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
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 */}
    }
}
 
Example #4
Source File: HttpServletRequestImplInterceptor.java    From pinpoint with Apache License 2.0 6 votes vote down vote up
private boolean validate(final Object target, final Object result, final Throwable throwable) {
    if (throwable != null || result == null) {
        return false;
    }

    if (!(target instanceof HttpServletRequest)) {
        if (isDebug) {
            logger.debug("Invalid target object, The javax.servlet.http.HttpServletRequest interface is not implemented. target={}", target);
        }
        return false;
    }

    if (!(result instanceof AsyncContext)) {
        if (isDebug) {
            logger.debug("Invalid result object, The javax.servlet.AsyncContext interface is not implemented. result={}.", result);
        }
        return false;
    }
    return true;
}
 
Example #5
Source File: MainHandler.java    From Web-API with MIT License 6 votes vote down vote up
public MainHandler(LinkServer link) {
    this.link = link;
    link.onResponse((ResponseMessage res) -> {
        AsyncContext ctx = contexts.get(res.getId());
        if (ctx == null) {
            System.out.println("ERROR: Could not find context for " + res.getId());
            return;
        }

        HttpServletResponse resp = (HttpServletResponse)ctx.getResponse();
        if (resp == null) {
            System.out.println("ERROR: Could not find response object for " + res.getId());
            return;
        }

        try {
            resp.setStatus(res.getStatus() != 0 ? res.getStatus() : HttpServletResponse.SC_OK);
            res.getHeaders().forEach(resp::setHeader);
            resp.getWriter().write(res.getMessage());
            ctx.complete();
        } catch (IOException e) {
            e.printStackTrace();
        }
    });
}
 
Example #6
Source File: FlowRouter.java    From flower with Apache License 2.0 6 votes vote down vote up
/**
 * 异步调用
 * 
 * @param message message
 * @param ctx {@link AsyncContext}
 */
public <T> void asyncCallService(T message, AsyncContext ctx) {
  ServiceContext serviceContext = null;
  if (ctx != null) {
    Web web = new Web(ctx);
    serviceContext = ServiceContextUtil.context(message, web);
    ServiceContextUtil.record(serviceContext);
  } else {
    serviceContext = ServiceContextUtil.context(message);
  }
  serviceContext.setFlowName(headerServiceConfig.getFlowName());
  if (StringUtil.isBlank(serviceContext.getCurrentServiceName())) {
    serviceContext.setCurrentServiceName(headerServiceConfig.getServiceName());
  }
  serviceContext.addAttachment(Constant.ServiceContextOriginURL,
      headerServiceConfig.getAddresses().iterator().next());
  getServiceRouter().asyncCallService(serviceContext, ActorRef.noSender());
}
 
Example #7
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 #8
Source File: RequestStartAsyncInterceptor.java    From pinpoint with Apache License 2.0 6 votes vote down vote up
private boolean validate(final Object target, final Object result, final Throwable throwable) {
    if (throwable != null || result == null) {
        return false;
    }

    if (!(target instanceof HttpServletRequest)) {
        logger.debug("Invalid target object. {}", target);
        return false;
    }


    if (!(result instanceof AsyncContext)) {
        logger.debug("Invalid result object. {}.", result);
        return false;
    }

    return true;
}
 
Example #9
Source File: AsyncServlet.java    From training with MIT License 6 votes vote down vote up
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

	final AsyncContext asyncContext = req.startAsync();

	// DON'T TRY THIS AT HOME: Working with threads in a Container !!
	new Timer().schedule(new TimerTask() {
		@Override
		public void run() {
			try {
				asyncContext.getResponse().getWriter().println(new Date() + ": Asynchronous Response");
				System.out.println("Release pending HTTP connection");
				asyncContext.complete();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}, 10 * 1000);
	resp.getWriter().println(new Date() + ": Async Servlet returns leaving the connection open");
}
 
Example #10
Source File: TestAbstractHttp11Processor.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
@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 #11
Source File: ConcurrencyServlet.java    From tomee with Apache License 2.0 6 votes vote down vote up
@Override
protected void service(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
    final AsyncContext asyncCtx = req.startAsync();
    execService.execute(new Runnable() {
        @Override
        public void run() {
            try {
                req.login("test", "secret");
                resp.getWriter().println(user.getUser());
            } catch (final Exception e) {
                try {
                    e.printStackTrace(resp.getWriter());
                } catch (final IOException e1) {
                    throw new IllegalStateException(e);
                }
            } finally {
                asyncCtx.complete();
            }
        }
    });
}
 
Example #12
Source File: TestAsyncContextImpl.java    From Tomcat7.0.67 with Apache License 2.0 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 #13
Source File: ServletServerHttpResponse.java    From java-technology-stack with MIT License 6 votes vote down vote up
public ServletServerHttpResponse(HttpHeaders headers, HttpServletResponse response, AsyncContext asyncContext,
		DataBufferFactory bufferFactory, int bufferSize, ServletServerHttpRequest request) throws IOException {

	super(bufferFactory, headers);

	Assert.notNull(response, "HttpServletResponse must not be null");
	Assert.notNull(bufferFactory, "DataBufferFactory must not be null");
	Assert.isTrue(bufferSize > 0, "Buffer size must be greater than 0");

	this.response = response;
	this.outputStream = response.getOutputStream();
	this.bufferSize = bufferSize;
	this.request = request;

	asyncContext.addListener(new ResponseAsyncListener());

	// Tomcat expects WriteListener registration on initial thread
	response.getOutputStream().setWriteListener(new ResponseBodyWriteListener());
}
 
Example #14
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 #15
Source File: TestAsyncContextImpl.java    From tomcatsrc with Apache License 2.0 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 #16
Source File: AbstractJettyTest.java    From java-web-servlet-filter with Apache License 2.0 6 votes vote down vote up
@Override
public void doGet(final HttpServletRequest request, final HttpServletResponse response)
    throws ServletException, IOException {

    // avoid retries on timeout
    if (request.getAttribute("timedOut") != null) {
        return;
    }
    request.setAttribute("timedOut", true);

    final AsyncContext asyncContext = request.startAsync(request, response);
    asyncContext.setTimeout(10);
    asyncContext.start(new Runnable() {
        @Override
        public void run() {
            try {
                TimeUnit.MILLISECONDS.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                asyncContext.complete();
            }
        }
    });
}
 
Example #17
Source File: AsyncContextAdviceHelperImpl.java    From apm-agent-java with Apache License 2.0 6 votes vote down vote up
@Override
public void onExitStartAsync(AsyncContext asyncContext) {
    final ServletRequest request = asyncContext.getRequest();
    if (request.getAttribute(ASYNC_LISTENER_ADDED) != null) {
        return;
    }
    final Transaction transaction = tracer.currentTransaction();
    if (transaction != null && transaction.isSampled() && request.getAttribute(ASYNC_LISTENER_ADDED) == null) {
        // makes sure that the listener is only added once, even if the request is wrapped
        // which leads to multiple invocations of startAsync for the same underlying request
        request.setAttribute(ASYNC_LISTENER_ADDED, Boolean.TRUE);
        // specifying the request and response is important
        // otherwise AsyncEvent.getSuppliedRequest returns null per spec
        // however, only some application server like WebSphere actually implement it that way
        asyncContext.addListener(asyncListenerObjectPool.createInstance().withTransaction(transaction),
            asyncContext.getRequest(), asyncContext.getResponse());

        request.setAttribute(ASYNC_ATTRIBUTE, Boolean.TRUE);
        request.setAttribute(TRANSACTION_ATTRIBUTE, transaction);
    }
}
 
Example #18
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 #19
Source File: TestAsyncContextImpl.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 {

    AsyncContext actxt = req.startAsync();
    resp.setStatus(status);
    actxt.complete();
}
 
Example #20
Source File: JettyHttpHandlerAdapter.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
protected ServletServerHttpResponse createResponse(HttpServletResponse response,
		AsyncContext context, ServletServerHttpRequest request) throws IOException {

	return new JettyServerHttpResponse(
			response, context, getDataBufferFactory(), getBufferSize(), request);
}
 
Example #21
Source File: AsyncServletTest.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    final AsyncContext asyncContext = req.startAsync();
    asyncContext.setTimeout(1);
    try {
        Thread.sleep(10L);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
}
 
Example #22
Source File: OpenshiftServlet.java    From hawkular-metrics with Apache License 2.0 5 votes vote down vote up
private AsyncContext getAsyncContext(HttpServletRequest req) {
    if(req.isAsyncStarted()) {
        return req.getAsyncContext();
    } else {
        return req.startAsync();
    }
}
 
Example #23
Source File: FlowerController.java    From flower with Apache License 2.0 5 votes vote down vote up
protected void doProcess(Object param, HttpServletRequest req) {
  AsyncContext context = null;
  if (req != null) {
    context = req.startAsync();
  }
  this.flowRouter.asyncCallService(param, context);
}
 
Example #24
Source File: FlowServlet.java    From flower with Apache License 2.0 5 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	resp.setContentType("text/html;charset=UTF-8");
	PrintWriter out = resp.getWriter();
	out.println("begin:" + System.currentTimeMillis());
	out.flush();

	AsyncContext ctx = req.startAsync();
	sr.asyncCallService(" Hello, Flow World! ", ctx);
}
 
Example #25
Source File: ServletHttpHandlerAdapter.java    From java-technology-stack with MIT License 5 votes vote down vote up
protected ServletServerHttpRequest createRequest(HttpServletRequest request, AsyncContext context)
		throws IOException, URISyntaxException {

	Assert.notNull(this.servletPath, "Servlet path is not initialized");
	return new ServletServerHttpRequest(
			request, context, this.servletPath, getDataBufferFactory(), getBufferSize());
}
 
Example #26
Source File: TomcatHttpHandlerAdapter.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
protected ServletServerHttpRequest createRequest(HttpServletRequest request, AsyncContext asyncContext)
		throws IOException, URISyntaxException {

	Assert.notNull(getServletPath(), "Servlet path is not initialized");
	return new TomcatServerHttpRequest(
			request, asyncContext, getServletPath(), getDataBufferFactory(), getBufferSize());
}
 
Example #27
Source File: TestAsyncContextImpl.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
@Override
public void service(ServletRequest req, ServletResponse resp)
        throws ServletException, IOException {
    if (DispatcherType.ASYNC != req.getDispatcherType()) {
        AsyncContext asyncContext;
        if ("y".equals(req.getParameter(CUSTOM_REQ_RESP))) {
            asyncContext = req.startAsync(
                    new ServletRequestWrapper(req),
                    new ServletResponseWrapper(resp));
        } else {
            asyncContext = req.startAsync();
        }
        if ("y".equals(req.getParameter(EMPTY_DISPATCH))) {
            asyncContext.dispatch();
        } else {
            asyncContext.dispatch("/target");
        }
        try {
            asyncContext.dispatch("/nonExistingServlet");
            TestAsyncContextImpl.track("FAIL");
        } catch (IllegalStateException e) {
            TestAsyncContextImpl.track("OK");
        }
    } else {
        TestAsyncContextImpl.track("DispatchingGenericServletGet-");
    }
}
 
Example #28
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 #29
Source File: TestAsyncContextImpl.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 {

    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 #30
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 {

    // 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();
}