javax.servlet.http.HttpServletRequest#isAsyncStarted()源码实例Demo

下面列出了javax.servlet.http.HttpServletRequest#isAsyncStarted() 实例代码,或者点击链接到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 项目: 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.");
    }
}
 
源代码3 项目: onedev   文件: ServletWebResponse.java
@Override
public void flush()
{
	try
	{
		HttpServletRequest httpServletRequest = webRequest.getContainerRequest();
		if (httpServletRequest.isAsyncStarted() == false)
		{
			httpServletResponse.flushBuffer();
		}
	}
	catch (IOException e)
	{
		throw new ResponseIOException(e);
	}
}
 
源代码4 项目: tomcatsrc   文件: 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) {
            ticker.addTickListener(this);
        }
    } else {
        new Exception("Async Not Supported").printStackTrace();
        resp.sendError(400,"Async is not supported.");
    }
}
 
源代码5 项目: tomcatsrc   文件: 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) {
            ticker.addTickListener(this);
        }
    } else {
        new Exception("Async Not Supported").printStackTrace();
        resp.sendError(400,"Async is not supported.");
    }
}
 
源代码6 项目: AngularBeans   文件: SockJsServlet.java
@Override
protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

	res.setHeader("Access-Control-Allow-Origin", "true");

	log.log(Level.FINE, "SockJsServlet#service for {0} {1}", new Object[]{ req.getMethod(), req.getPathInfo() });
	AsyncContext asyncContext = req.startAsync();
	asyncContext.setTimeout(0); // no timeout
	SockJsServletRequest sockJsReq = new SockJsServletRequest(req);
	SockJsServletResponse sockJsRes = new SockJsServletResponse(res, asyncContext);
	try {
		sockJsServer.dispatch(sockJsReq, sockJsRes);
	} catch (SockJsException ex) {
		throw new ServletException("Error during SockJS request:", ex);
	}
	if ("application/x-www-form-urlencoded".equals(req.getHeader("Content-Type"))) {
		// Let the servlet parse data and just pretend like we did
		sockJsReq.onAllDataRead();
	} else if (req.isAsyncStarted()) {
		req.getInputStream().setReadListener(sockJsReq);
	}
}
 
@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();
}
 
源代码8 项目: quarkus-http   文件: AsyncDoubleCompleteServlet.java
@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
    req.startAsync();
    resp.getWriter().write(SimpleAsyncTestCase.HELLO_WORLD);
    if (req.isAsyncStarted()) {
        req.getAsyncContext().complete();
    }
    if (req.isAsyncStarted()) {
        req.getAsyncContext().complete();
    }
}
 
源代码9 项目: 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();
}
 
源代码10 项目: hawkular-metrics   文件: OpenshiftServlet.java
private AsyncContext getAsyncContext(HttpServletRequest req) {
    if(req.isAsyncStarted()) {
        return req.getAsyncContext();
    } else {
        return req.startAsync();
    }
}
 
源代码11 项目: opencensus-java   文件: OcHttpServletFilter.java
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
    throws IOException, ServletException {
  // only interested in http requests
  if ((request instanceof HttpServletRequest) && (response instanceof HttpServletResponse)) {
    HttpServletRequest httpReq = (HttpServletRequest) request;
    HttpServletResponse httpResp = (HttpServletResponse) response;

    HttpRequestContext context = handler.handleStart(httpReq, httpReq);
    OcHttpServletListener listener = new OcHttpServletListener(handler, context);
    httpReq.setAttribute(OcHttpServletUtil.OPENCENSUS_SERVLET_LISTENER, listener);

    int length = httpReq.getContentLength();
    if (length > 0) {
      handler.handleMessageReceived(context, length);
    }

    Scope scope = Tracing.getTracer().withSpan(handler.getSpanFromContext(context));
    try {
      chain.doFilter(httpReq, httpResp);
    } finally {
      scope.close();
    }

    if (httpReq.isAsyncStarted()) {
      AsyncContext async = httpReq.getAsyncContext();
      async.addListener(listener, httpReq, httpResp);
    } else {
      OcHttpServletUtil.recordMessageSentEvent(handler, context, httpResp);
      handler.handleEnd(context, httpReq, httpResp, null);
    }
  } else {
    // pass request through unchanged
    chain.doFilter(request, response);
  }
}
 
private void doFilterRequest(HttpServletRequest httpRequest, HttpServletResponse httpResponse, FilterChain chain)
		throws IOException, ServletException {
	if (httpRequest.getHeader(dynLogEnvironment.getDynLogHeaderKey()) != null && dynamicLogLevelProcessor != null) {
		dynamicLogLevelProcessor.copyDynamicLogLevelToMDC(httpRequest);
	}
	/*
	 * -- make sure correlation id is read from headers
	 */
	LogContext.initializeContext(HttpHeaderUtilities.getHeaderValue(httpRequest, HttpHeaders.CORRELATION_ID));

	try {

		RequestRecord rr = requestRecordFactory.create(httpRequest);
		httpRequest.setAttribute(MDC.class.getName(), MDC.getCopyOfContextMap());
		
		if (!httpResponse.isCommitted() && httpResponse.getHeader(HttpHeaders.CORRELATION_ID.getName()) == null) {
			httpResponse.setHeader(HttpHeaders.CORRELATION_ID.getName(), LogContext.getCorrelationId());
		}

		/*
		 * If request logging is disabled skip request instrumentation and continue the
		 * filter chain immediately.
		 */
		if (!RequestLogger.isRequestLoggingEnabled()) {
			doFilter(chain, httpRequest, httpResponse);
			return;
		}

		/*
		 * -- we essentially do three things here: -- a) we create a log
		 * record using our library and log it via STDOUT -- b) keep track
		 * of certain header fields so that they are available in later
		 * processing steps -- b) inject a response wrapper to keep track of
		 * content length (hopefully)
		 */
		if (wrapResponse) {
			httpResponse = new ContentLengthTrackingResponseWrapper(httpResponse);
		}

		if (wrapRequest) {
			httpRequest = new ContentLengthTrackingRequestWrapper(httpRequest);
		}

		RequestLogger loggingVisitor = new RequestLogger(rr, httpRequest, httpResponse);
		httpRequest = new LoggingContextRequestWrapper(httpRequest, loggingVisitor);



		/* -- start measuring right before calling up the filter chain -- */
		rr.start();
		doFilter(chain, httpRequest, httpResponse);

		if (!httpRequest.isAsyncStarted()) {
			loggingVisitor.logRequest();
		}
		/*
		 * -- close this
		 */
	} finally {
		if (dynamicLogLevelProcessor != null) {
			dynamicLogLevelProcessor.removeDynamicLogLevelFromMDC();
		}
		LogContext.resetContextFields();
	}
}
 
源代码13 项目: tomcatsrc   文件: 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();
}
 
源代码14 项目: nio-multipart   文件: MultipartController.java
static AsyncContext switchRequestToAsyncIfNeeded(final HttpServletRequest request){
    if (request.isAsyncStarted()){
        if (log.isDebugEnabled()) log.debug("Async context already started. Return it");
        return request.getAsyncContext();
    }else{
        if (log.isDebugEnabled()) log.info("Start async context and return it.");
        return request.startAsync();
    }
}
 
源代码15 项目: java-specialagent   文件: ServletApiV3.java
public static boolean isAsyncStarted(final HttpServletRequest request) {
  return isApiV3 && request.isAsyncStarted();
}
 
源代码16 项目: javamelody   文件: MonitoringFilter.java
private void doFilter(FilterChain chain, HttpServletRequest httpRequest,
		HttpServletResponse httpResponse) throws IOException, ServletException {
	final long start = System.currentTimeMillis();
	final long startCpuTime = ThreadInformations.getCurrentThreadCpuTime();
	final long startAllocatedBytes = ThreadInformations.getCurrentThreadAllocatedBytes();
	final CounterServletResponseWrapper wrappedResponse = createResponseWrapper(httpRequest,
			httpResponse);
	final HttpServletRequest wrappedRequest = createRequestWrapper(httpRequest,
			wrappedResponse);
	boolean systemError = false;
	Throwable systemException = null;
	String requestName = getRequestName(wrappedRequest);
	final String completeRequestName = getCompleteRequestName(wrappedRequest, true);
	try {
		JdbcWrapper.ACTIVE_THREAD_COUNT.incrementAndGet();
		// on binde le contexte de la requête http pour les requêtes sql
		httpCounter.bindContext(requestName, completeRequestName, httpRequest, startCpuTime,
				startAllocatedBytes);
		// on binde la requête http (utilisateur courant et requête complète) pour les derniers logs d'erreurs
		httpRequest.setAttribute(CounterError.REQUEST_KEY, completeRequestName);
		CounterError.bindRequest(httpRequest);
		chain.doFilter(wrappedRequest, wrappedResponse);
		if (servletApi2 || !httpRequest.isAsyncStarted()) {
			wrappedResponse.flushStream();
		}
	} catch (final Throwable t) { // NOPMD
		// on catche Throwable pour avoir tous les cas d'erreur système
		systemException = t;
		throwException(t);
	} finally {
		if (httpCounter == null) {
			// "the destroy method is only called once all threads within the filter's doFilter method have exited
			// or after a timeout period has passed"
			// si timeout, alors on évite ici une NPE (cf  issue 262)
			return; // NOPMD
		}
		try {
			// Si la durée est négative (arrive bien que rarement en cas de synchronisation d'horloge système),
			// alors on considère que la durée est 0.
			// Rq : sous Windows XP, currentTimeMillis a une résolution de 16ms environ
			// (discrètisation de la durée en 0, 16 ou 32 ms, etc ...)
			// et sous linux ou Windows Vista la résolution est bien meilleure.
			// On n'utilise pas nanoTime car il peut être un peu plus lent (mesuré à 2 microsecondes,
			// voir aussi http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6440250)
			// et car des millisecondes suffisent pour une requête http
			final long duration = Math.max(System.currentTimeMillis() - start, 0);
			final int cpuUsedMillis = (int) ((ThreadInformations.getCurrentThreadCpuTime()
					- startCpuTime) / 1000000L);
			final int allocatedKBytes;
			if (startAllocatedBytes >= 0) {
				allocatedKBytes = (int) ((ThreadInformations.getCurrentThreadAllocatedBytes()
						- startAllocatedBytes) / 1024L);
			} else {
				allocatedKBytes = -1;
			}
			JdbcWrapper.ACTIVE_THREAD_COUNT.decrementAndGet();
			putUserInfoInSession(httpRequest);
			if (systemException != null) {
				systemError = true;
				final StringWriter stackTrace = new StringWriter(200);
				systemException.printStackTrace(new PrintWriter(stackTrace));
				errorCounter.addRequestForSystemError(systemException.toString(), duration,
						cpuUsedMillis, allocatedKBytes, stackTrace.toString());
			} else if (wrappedResponse.getCurrentStatus() >= HttpServletResponse.SC_BAD_REQUEST
					&& wrappedResponse
							.getCurrentStatus() != HttpServletResponse.SC_UNAUTHORIZED) {
				// SC_UNAUTHORIZED (401) is not an error, it is the first handshake of a Basic (or Digest) Auth (issue 455)
				systemError = true;
				errorCounter.addRequestForSystemError(
						"Error" + wrappedResponse.getCurrentStatus(), duration, cpuUsedMillis,
						allocatedKBytes, null);
			}
			// prise en compte de Spring bestMatchingPattern s'il y a
			requestName = CounterRequestContext.getHttpRequestName(httpRequest, requestName);
			// taille du flux sortant
			final long responseSize = wrappedResponse.getDataLength();
			// nom identifiant la requête
			if (wrappedResponse.getCurrentStatus() == HttpServletResponse.SC_NOT_FOUND) {
				// Sécurité : si status http est 404, alors requestName est Error404
				// pour éviter de saturer la mémoire avec potentiellement beaucoup d'url différentes
				requestName = "Error404";
			}

			// on enregistre la requête dans les statistiques
			httpCounter.addRequest(requestName, duration, cpuUsedMillis, allocatedKBytes,
					systemError, responseSize);
			// on log sur Log4J ou java.util.logging dans la catégorie correspond au nom du filtre dans web.xml
			log(httpRequest, requestName, duration, systemError,
					wrappedResponse.getCurrentStatus(), responseSize);
		} finally {
			// normalement le unbind du contexte a été fait dans httpCounter.addRequest
			// mais pour être sûr au cas où il y ait une exception comme OutOfMemoryError
			// on le refait ici pour éviter des erreurs par la suite,
			// car il ne doit pas y avoir de contexte restant au delà de la requête http
			httpCounter.unbindContext();
			// et unbind de la requête http
			CounterError.unbindRequest();
		}
	}
}
 
源代码17 项目: wingtips   文件: ServletRuntime.java
@Override
public boolean isAsyncRequest(HttpServletRequest request) {
    return request.isAsyncStarted();
}
 
源代码18 项目: pinpoint   文件: Servlet3ApiHelper.java
@Override
public boolean isAsyncDispatcherBefore(HttpServletRequest request) {
    return request.isAsyncStarted() || request.getDispatcherType() == DispatcherType.ASYNC;
}
 
源代码19 项目: brave   文件: ServletRuntime.java
@Override public boolean isAsync(HttpServletRequest request) {
  return request.isAsyncStarted();
}
 
源代码20 项目: portals-pluto   文件: PortletContainerImpl.java
/**
 * Indicates that a portlet resource Serving occured in the current request and calls
 * the processServeResource method of this portlet.
 * @param portletWindow the portlet Window
 * @param request               the servlet request
 * @param response              the servlet response
 * @throws PortletException          if one portlet has trouble fulfilling
 *                                   the request
 * @throws PortletContainerException if the portlet container implementation
 *                                   has trouble fulfilling the request
 */
public void doServeResource(PortletWindow portletWindow,
        HttpServletRequest request,
        HttpServletResponse response)
throws PortletException, IOException, PortletContainerException
{
    ensureInitialized();

    debugWithName("Resource request received for portlet: "
            + portletWindow.getPortletDefinition().getPortletName());

    PortletRequestContextService rcService = getContainerServices().getPortletRequestContextService();
    PortletEnvironmentService envService = getContainerServices().getPortletEnvironmentService();
    PortletInvokerService invoker = getContainerServices().getPortletInvokerService();

    PortletResourceRequestContext requestContext = rcService.getPortletResourceRequestContext(this, request, response, portletWindow);
    PortletResourceResponseContext responseContext = rcService.getPortletResourceResponseContext(this, request, response, portletWindow, requestContext);
    responseContext.setPropsAllowed(true);
    ResourceRequest portletRequest = envService.createResourceRequest(requestContext, responseContext);
    ResourceResponse portletResponse = envService.createResourceResponse(responseContext, requestContext.getCacheability());
    requestContext.setResponse(portletResponse);     // for async support

    FilterManager filterManager = filterInitialisation(portletWindow,PortletRequest.RESOURCE_PHASE);
    
    try
    {
       invoker.serveResource(requestContext, portletRequest, portletResponse, filterManager);
    }
    finally
    {
        if (!request.isAsyncSupported() || !request.isAsyncStarted()) {
            // Mark portlet interaction is completed: backend implementation can flush response state now
            responseContext.close();
            responseContext.release();
        } else {
           LOG.debug("Async started for resource request. responseContext not released.");
        }
    }

    debugWithName("Portlet resource done for: " + portletWindow.getPortletDefinition().getPortletName());
}