Java Code Examples for javax.servlet.http.httpservletrequest#isAsyncStarted()

The following examples show how to use javax.servlet.http.httpservletrequest#isAsyncStarted() . 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: AsyncStockServlet.java    From Tomcat8-Source-Read with MIT License 6 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 3
Source File: SockJsServlet.java    From AngularBeans with GNU Lesser General Public License v3.0 6 votes vote down vote up
@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);
	}
}
 
Example 4
Source File: AsyncStockServlet.java    From tomcatsrc with Apache License 2.0 6 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) {
            ticker.addTickListener(this);
        }
    } else {
        new Exception("Async Not Supported").printStackTrace();
        resp.sendError(400,"Async is not supported.");
    }
}
 
Example 5
Source File: ServletWebResponse.java    From onedev with MIT License 6 votes vote down vote up
@Override
public void flush()
{
	try
	{
		HttpServletRequest httpServletRequest = webRequest.getContainerRequest();
		if (httpServletRequest.isAsyncStarted() == false)
		{
			httpServletResponse.flushBuffer();
		}
	}
	catch (IOException e)
	{
		throw new ResponseIOException(e);
	}
}
 
Example 6
Source File: OcHttpServletFilter.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@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);
  }
}
 
Example 7
Source File: MultipartController.java    From nio-multipart with Apache License 2.0 5 votes vote down vote up
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();
    }
}
 
Example 8
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 {

    // 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 9
Source File: AsyncStockServlet.java    From tomcatsrc with Apache License 2.0 5 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) {
            ticker.addTickListener(this);
        }
    } else {
        new Exception("Async Not Supported").printStackTrace();
        resp.sendError(400,"Async is not supported.");
    }
}
 
Example 10
Source File: RequestLoggingFilter.java    From cf-java-logging-support with Apache License 2.0 5 votes vote down vote up
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();
	}
}
 
Example 11
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 12
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 {

    // 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 13
Source File: AsyncDoubleCompleteServlet.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@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();
    }
}
 
Example 14
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();
}
 
Example 15
Source File: ServletRuntime.java    From wingtips with Apache License 2.0 4 votes vote down vote up
@Override
public boolean isAsyncRequest(HttpServletRequest request) {
    return request.isAsyncStarted();
}
 
Example 16
Source File: Servlet3ApiHelper.java    From pinpoint with Apache License 2.0 4 votes vote down vote up
@Override
public boolean isAsyncDispatcherBefore(HttpServletRequest request) {
    return request.isAsyncStarted() || request.getDispatcherType() == DispatcherType.ASYNC;
}
 
Example 17
Source File: MonitoringFilter.java    From javamelody with Apache License 2.0 4 votes vote down vote up
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();
		}
	}
}
 
Example 18
Source File: ServletApiV3.java    From java-specialagent with Apache License 2.0 4 votes vote down vote up
public static boolean isAsyncStarted(final HttpServletRequest request) {
  return isApiV3 && request.isAsyncStarted();
}
 
Example 19
Source File: ServletRuntime.java    From brave with Apache License 2.0 4 votes vote down vote up
@Override public boolean isAsync(HttpServletRequest request) {
  return request.isAsyncStarted();
}
 
Example 20
Source File: PortletContainerImpl.java    From portals-pluto with Apache License 2.0 4 votes vote down vote up
/**
 * 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());
}