javax.servlet.ServletResponseWrapper#javax.servlet.AsyncContext源码实例Demo

下面列出了javax.servlet.ServletResponseWrapper#javax.servlet.AsyncContext 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: Tomcat8-Source-Read   文件: AsyncStockServlet.java
@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.");
    }
}
 
源代码2 项目: pinpoint   文件: RequestStartAsyncInterceptor.java
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;
}
 
源代码3 项目: portals-pluto   文件: PortletAsyncContextImpl.java
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);
}
 
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;
}
 
@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();
        }
    });
}
 
源代码6 项目: tomee   文件: ConcurrencyServlet.java
@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();
            }
        }
    });
}
 
源代码7 项目: training   文件: AsyncServlet.java
@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");
}
 
源代码8 项目: tomcatsrc   文件: TestAsyncContextImpl.java
@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();
}
 
@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();
    }
}
 
@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);
    }
}
 
@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();
            }
        }
    });
}
 
源代码12 项目: Tomcat8-Source-Read   文件: TestAsyncContextImpl.java
@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();
    }
}
 
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());
}
 
源代码14 项目: Tomcat7.0.67   文件: TestAsyncContextImpl.java
@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();
    }
}
 
源代码15 项目: Web-API   文件: MainHandler.java
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();
        }
    });
}
 
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);
}
 
源代码17 项目: tomcatsrc   文件: AsyncStockServlet.java
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 */}
    }
}
 
源代码18 项目: flower   文件: FlowRouter.java
/**
 * 异步调用
 * 
 * @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());
}
 
源代码19 项目: Tomcat8-Source-Read   文件: NumberWriter.java
private NumberWriterListener(AsyncContext ac, ServletInputStream sis,
        ServletOutputStream sos) {
    this.ac = ac;
    this.sis = sis;
    this.sos = sos;

    // In Tomcat, the order the listeners are set controls the order
    // that the first calls are made. In this case, the read listener
    // will be called before the write listener.
    sis.setReadListener(this);
    sos.setWriteListener(this);
}
 
源代码20 项目: Tomcat8-Source-Read   文件: AsyncStockServlet.java
@Override
public void tick(Stock stock) {
    Iterator<AsyncContext> it = clients.iterator();
    while (it.hasNext()) {
        AsyncContext actx = it.next();
        try {
            writeStock(actx, stock);
        } catch (Exception e) {
            // Ignore. The async error handling will deal with this.
        }
    }
}
 
源代码21 项目: Tomcat8-Source-Read   文件: AsyncStockServlet.java
@Override
public void shutdown() {
    // The web application is shutting down. Complete any AsyncContexts
    // associated with an active client.
    Iterator<AsyncContext> it = clients.iterator();
    while (it.hasNext()) {
        AsyncContext actx = it.next();
        try {
            actx.complete();
        } catch (Exception e) {
            // Ignore. The async error handling will deal with this.
        }
    }
}
 
源代码22 项目: Tomcat8-Source-Read   文件: Request.java
@Override
public AsyncContext getAsyncContext() {
    if (!isAsyncStarted()) {
        throw new IllegalStateException(sm.getString("request.notAsync"));
    }
    return asyncContext;
}
 
源代码23 项目: bamboobsc   文件: WebMessagePublishServlet.java
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	AsyncContext context = request.startAsync();
	synchronized (asyncContexts) {
		asyncContexts.add(context);
	}
}
 
源代码24 项目: javamelody   文件: JspWrapper.java
@Override
public AsyncContext startAsync() {
	// issue 217: after MonitoringFilter.doFilter, response is instance of CounterServletResponseWrapper,
	// and if response.getWriter() has been called before calling request.startAsync(),
	// then asyncContext.getResponse() should return the instance of CounterServletResponseWrapper
	// and not the initial response without the wrapper,
	// otherwise asyncContext.getResponse().getWriter() will throw something like
	// "IllegalStateException: getOutputStream() has already been called for this response"
	return super.startAsync(this, response);
}
 
源代码25 项目: flower   文件: Web.java
public Web(AsyncContext context) {
  this.asyncContext = context;
  this.servletRequest = context.getRequest();
  this.servletResponse = context.getResponse();
  servletResponse.setCharacterEncoding(Constant.ENCODING_UTF_8);
  try {
    this.writer = servletResponse.getWriter();
  } catch (IOException e) {
    logger.error("", e);
  }
}
 
源代码26 项目: Tomcat7.0.67   文件: TestAsyncContextImpl.java
@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();
}
 
源代码27 项目: vespa   文件: JDiscFilterInvokerFilter.java
@Override
public AsyncContext startAsync(
        final ServletRequest wrappedRequest,
        final ServletResponse wrappedResponse) {
    // According to the documentation, the passed request/response parameters here must either
    // _be_ or _wrap_ the original request/response objects passed to the servlet - which are
    // our wrappers, so no need to wrap again - we can use the user-supplied objects.
    final AsyncContext asyncContext = super.startAsync(wrappedRequest, wrappedResponse);
    return new FilterInvokingAsyncContext(asyncContext, filterInvoker, this, wrappedResponse);
}
 
源代码28 项目: emodb   文件: DatabusResourcePoller.java
DatabusPollRunnable(AsyncContext asyncContext, KeepAliveRunnable keepAliveRunnable, Subject subject, SubjectDatabus databus,
                    Duration claimTtl, int limit, String subscription, PeekOrPollResponseHelper helper,
                    long longPollStopTime, Timer.Context timerContext) {
    _asyncContext = asyncContext;
    _keepAliveRunnable = keepAliveRunnable;
    _subject = subject;
    _databus = databus;
    _claimTtl = claimTtl;
    _limit = limit;
    _subscription = subscription;
    _helper = helper;
    _longPollStopTime = longPollStopTime;
    _timerContext = timerContext;
}
 
public void doGet(HttpServletRequest request, HttpServletResponse response) {
    final AsyncContext asyncContext = request.startAsync(request, response);

    executor.execute(() -> {
        sleepThread(SLEEP_TIME_MILLIS);
        asyncContext.dispatch(ASYNC_PATH);
    });
}
 
源代码30 项目: flower   文件: AsyncServlet.java
private void asyncExe(AsyncContext ctx) {
  try {
    sr.asyncCallService(null, ctx);
  } catch (Exception e) {
    e.printStackTrace();
  }
}