Example usage for javax.servlet.http HttpServletRequest isAsyncStarted

List of usage examples for javax.servlet.http HttpServletRequest isAsyncStarted

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest isAsyncStarted.

Prototype

public boolean isAsyncStarted();

Source Link

Document

Checks if this request has been put into asynchronous mode.

Usage

From source file:org.synchronoss.cloud.nio.multipart.example.web.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 {/*from   www  .ja  v  a 2  s  . com*/
        if (log.isDebugEnabled())
            log.info("Start async context and return it.");
        return request.startAsync();
    }
}

From source file:com.boylesoftware.web.impl.view.DispatchViewSender.java

@Override
public void send(final String viewId, final HttpServletRequest request, final HttpServletResponse response)
        throws IOException, ServletException {

    if (request.isAsyncStarted()) {
        if (this.log.isDebugEnabled())
            this.log.debug("dispatching to " + viewId + " using async context");
        request.getAsyncContext().dispatch(viewId);
    } else {//  www .ja v a 2  s . c  o m
        if (this.log.isDebugEnabled())
            this.log.debug("dispatching to " + viewId + " using request dispatcher");
        request.getRequestDispatcher(viewId).forward(request, response);
    }
}

From source file:com.jsmartframework.web.manager.ServletControl.java

private boolean doAsync(String path, HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    try {// www.  ja va2  s.co m
        // Only proceed if the AsyncContext was not started to avoid looping whe dispatch is called
        if (!request.isAsyncStarted()) {
            WebAsyncListener bean = (WebAsyncListener) HANDLER.instantiateAsyncBean(path);

            if (bean != null) {
                AsyncContext asyncContext = request.startAsync();
                bean.asyncContextCreated(asyncContext);
                asyncContext.addListener(new WebServletAsyncListener(path, bean));
                return true;
            }
        }
    } catch (Exception ex) {
        LOGGER.log(Level.SEVERE,
                "AsyncBean on path [" + path + "] could not be instantiated: " + ex.getMessage());
        throw new ServletException(ex);
    }
    return false;
}

From source file:com.yoho.core.trace.instrument.web.TraceInterceptor.java

@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
        Exception ex) throws Exception {

    //------get something from request-----
    Span spanFromRequest = (Span) request.getAttribute("SPAN-FROM-REQUEST");
    boolean skip = (Boolean) request.getAttribute("SPAN-SKIP");

    //??/*from   w w  w. j  a va  2 s .c o m*/
    if (request.isAsyncStarted()) {
        this.tracer.detach(spanFromRequest);
        // TODO: how to deal with response annotations and async?
        return;
    }

    addToResponseIfNotPresent(response, Span.SAMPLED_NAME, skip ? Span.SPAN_NOT_SAMPLED : Span.SPAN_SAMPLED);
    if (spanFromRequest != null) {
        addResponseTags(response, ex);
        if (spanFromRequest.hasSavedSpan()) {
            Span parent = spanFromRequest.getSavedSpan();
            if (parent != null && parent.isRemote()) {
                parent.logEvent(Span.SERVER_SEND);
                this.spanReporter.report(parent);
            }
        }
        // Double close to clean up the parent (remote span as well)
        this.tracer.close(spanFromRequest);
    }
}

From source file:com.jsmartframework.web.manager.FilterControl.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;

    httpRequest.setCharacterEncoding(ENCODING);
    httpResponse.setCharacterEncoding(ENCODING);

    // Initiate bean context based on current thread instance
    WebContext.initCurrentInstance(httpRequest, httpResponse);

    // Instantiate request scoped authentication bean
    HANDLER.instantiateAuthBean(httpRequest);

    // Instantiate web security for request extra validation
    HANDLER.instantiateWebSecurity(httpRequest);

    // Anonymous subclass to wrap HTTP response to print output
    WebFilterResponseWrapper responseWrapper = new WebFilterResponseWrapper(httpResponse);

    Throwable throwable = null;/*from w ww .ja va 2s.c o  m*/
    try {
        filterChain.doFilter(request, responseWrapper);
    } catch (Throwable thrown) {
        throwable = thrown;
        thrown.printStackTrace();
    }

    // Finalize request scoped web and auth beans
    HANDLER.finalizeBeans(httpRequest, responseWrapper);

    // Check if response was written before closing the WebContext
    boolean responseWritten = WebContext.isResponseWritten();

    // Close bean context based on current thread instance
    WebContext.closeCurrentInstance();

    // Case AsyncBean or RequestPath process was started it cannot proceed because it will not provide HTML via framework
    if (httpRequest.isAsyncStarted() || responseWritten) {

        // Generate response value after flushing the response wrapper buffer
        responseWrapper.flushBuffer();
        String responseVal = responseWrapper.toString();

        // Close current outputStream on responseWrapper
        responseWrapper.close();

        // Write the response value on real response object
        if (!httpResponse.isCommitted()) {
            httpResponse.getWriter().write(responseVal);
        }

        // Case internal server error
        if (throwable != null) {
            if (throwable instanceof IOException) {
                throw new IOException(throwable);
            }
            throw new ServletException(throwable);
        }
        return;
    }

    // Add Ajax headers to control redirect and reset
    addAjaxHeaders(httpRequest, responseWrapper);

    // Generate HTML after flushing the response wrapper buffer
    responseWrapper.flushBuffer();
    String html = completeHtml(httpRequest, responseWrapper);

    // Close current outputStream on responseWrapper
    responseWrapper.close();

    // Case internal server error
    if (throwable != null) {
        responseWrapper.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

        if (throwable instanceof IOException) {
            throw new IOException(throwable);
        }
        throw new ServletException(throwable);
    }

    if (StringUtils.isBlank(html)) {
        return;
    }

    if (CONFIG.getContent().isPrintHtml()) {
        LOGGER.log(Level.INFO, html);
    }

    // Compress html to better load performance
    HtmlCompress compressHtml = CONFIG.getContent().getCompressHtml();
    if (compressHtml.isCompressHtml()) {
        HtmlCompressor compressor = new HtmlCompressor();
        compressor.setRemoveComments(!compressHtml.isSkipComments());
        html = compressor.compress(html);
    }

    // Write our modified text to the real response
    if (!httpResponse.isCommitted()) {
        httpResponse.setContentLength(html.getBytes().length);
        httpResponse.getWriter().write(html);
    }
}

From source file:org.springframework.boot.actuate.autoconfigure.MetricsFilter.java

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
        throws ServletException, IOException {
    StopWatch stopWatch = createStopWatchIfNecessary(request);
    String path = new UrlPathHelper().getPathWithinApplication(request);
    int status = HttpStatus.INTERNAL_SERVER_ERROR.value();
    try {/* w  w  w  . j a  v  a2 s.c  o m*/
        chain.doFilter(request, response);
        status = getStatus(response);
    } finally {
        if (!request.isAsyncStarted()) {
            stopWatch.stop();
            request.removeAttribute(ATTRIBUTE_STOP_WATCH);
            recordMetrics(request, path, status, stopWatch.getTotalTimeMillis());
        }
    }
}

From source file:org.springframework.boot.actuate.metrics.web.servlet.MetricsFilter.java

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
        throws ServletException, IOException {
    StopWatch stopWatch = createStopWatchIfNecessary(request);
    String path = new UrlPathHelper().getPathWithinApplication(request);
    int status = HttpStatus.INTERNAL_SERVER_ERROR.value();
    try {/*from w  ww. jav  a2 s .c o  m*/
        chain.doFilter(request, response);
        status = getStatus(response);
    } finally {
        if (!request.isAsyncStarted()) {
            if (response.isCommitted()) {
                status = getStatus(response);
            }
            stopWatch.stop();
            request.removeAttribute(ATTRIBUTE_STOP_WATCH);
            recordMetrics(request, path, status, stopWatch.getTotalTimeMillis());
        }
    }
}

From source file:org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.java

private void filterAndRecordMetrics(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain, Object handler) throws IOException, ServletException {
    TimingContext timingContext = TimingContext.get(request);
    if (timingContext == null) {
        timingContext = startAndAttachTimingContext(request, handler);
    }/*from  www.j a  v a  2 s.c o m*/
    try {
        filterChain.doFilter(request, response);
        if (!request.isAsyncStarted()) {
            // Only record when async processing has finished or never been started.
            // If async was started by something further down the chain we wait
            // until the second filter invocation (but we'll be using the
            // TimingContext that was attached to the first)
            Throwable exception = (Throwable) request.getAttribute(DispatcherServlet.EXCEPTION_ATTRIBUTE);
            record(timingContext, response, request, handler, exception);
        }
    } catch (NestedServletException ex) {
        response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        record(timingContext, response, request, handler, ex.getCause());
        throw ex;
    }
}

From source file:org.springframework.boot.context.web.ErrorPageFilter.java

private void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    ErrorWrapperResponse wrapped = new ErrorWrapperResponse(response);
    try {//ww  w .j av a2 s  .co m
        chain.doFilter(request, wrapped);
        if (wrapped.hasErrorToSend()) {
            handleErrorStatus(request, response, wrapped.getStatus(), wrapped.getMessage());
            response.flushBuffer();
        } else if (!request.isAsyncStarted() && !response.isCommitted()) {
            response.flushBuffer();
        }
    } catch (Throwable ex) {
        Throwable exceptionToHandle = ex;
        if (ex instanceof NestedServletException) {
            exceptionToHandle = ((NestedServletException) ex).getRootCause();
        }
        handleException(request, response, wrapped, exceptionToHandle);
        response.flushBuffer();
    }
}

From source file:org.springframework.cloud.sleuth.instrument.web.TraceFilter.java

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
        throws IOException, ServletException {
    if (!(servletRequest instanceof HttpServletRequest) || !(servletResponse instanceof HttpServletResponse)) {
        throw new ServletException("Filter just supports HTTP requests");
    }// w w w  . ja va 2  s  .c om
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpServletResponse response = (HttpServletResponse) servletResponse;
    String uri = this.urlPathHelper.getPathWithinApplication(request);
    boolean skip = this.skipPattern.matcher(uri).matches()
            || Span.SPAN_NOT_SAMPLED.equals(ServletUtils.getHeader(request, response, Span.SAMPLED_NAME));
    Span spanFromRequest = getSpanFromAttribute(request);
    if (spanFromRequest != null) {
        continueSpan(request, spanFromRequest);
    }
    if (log.isDebugEnabled()) {
        log.debug("Received a request to uri [" + uri + "] that should not be sampled [" + skip + "]");
    }
    // in case of a response with exception status a exception controller will close the span
    if (!httpStatusSuccessful(response) && isSpanContinued(request)) {
        processErrorRequest(filterChain, request, response, spanFromRequest);
        return;
    }
    String name = HTTP_COMPONENT + ":" + uri;
    Throwable exception = null;
    try {
        spanFromRequest = createSpan(request, skip, spanFromRequest, name);
        filterChain.doFilter(request, response);
    } catch (Throwable e) {
        exception = e;
        this.tracer.addTag(Span.SPAN_ERROR_TAG_NAME, ExceptionUtils.getExceptionMessage(e));
        throw e;
    } finally {
        if (isAsyncStarted(request) || request.isAsyncStarted()) {
            if (log.isDebugEnabled()) {
                log.debug("The span " + spanFromRequest + " will get detached by a HandleInterceptor");
            }
            // TODO: how to deal with response annotations and async?
            return;
        }
        spanFromRequest = createSpanIfRequestNotHandled(request, spanFromRequest, name, skip);
        detachOrCloseSpans(request, response, spanFromRequest, exception);
    }
}