Search in sources :

Example 1 with WebAsyncManager

use of org.springframework.web.context.request.async.WebAsyncManager in project spring-framework by spring-projects.

the class FrameworkServlet method processRequest.

/**
	 * Process this request, publishing an event regardless of the outcome.
	 * <p>The actual event handling is performed by the abstract
	 * {@link #doService} template method.
	 */
protected final void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    long startTime = System.currentTimeMillis();
    Throwable failureCause = null;
    LocaleContext previousLocaleContext = LocaleContextHolder.getLocaleContext();
    LocaleContext localeContext = buildLocaleContext(request);
    RequestAttributes previousAttributes = RequestContextHolder.getRequestAttributes();
    ServletRequestAttributes requestAttributes = buildRequestAttributes(request, response, previousAttributes);
    WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
    asyncManager.registerCallableInterceptor(FrameworkServlet.class.getName(), new RequestBindingInterceptor());
    initContextHolders(request, localeContext, requestAttributes);
    try {
        doService(request, response);
    } catch (ServletException ex) {
        failureCause = ex;
        throw ex;
    } catch (IOException ex) {
        failureCause = ex;
        throw ex;
    } catch (Throwable ex) {
        failureCause = ex;
        throw new NestedServletException("Request processing failed", ex);
    } finally {
        resetContextHolders(request, previousLocaleContext, previousAttributes);
        if (requestAttributes != null) {
            requestAttributes.requestCompleted();
        }
        if (logger.isDebugEnabled()) {
            if (failureCause != null) {
                this.logger.debug("Could not complete request", failureCause);
            } else {
                if (asyncManager.isConcurrentHandlingStarted()) {
                    logger.debug("Leaving response open for concurrent processing");
                } else {
                    this.logger.debug("Successfully completed request");
                }
            }
        }
        publishRequestHandledEvent(request, response, startTime, failureCause);
    }
}
Also used : WebAsyncManager(org.springframework.web.context.request.async.WebAsyncManager) ServletException(javax.servlet.ServletException) NestedServletException(org.springframework.web.util.NestedServletException) SimpleLocaleContext(org.springframework.context.i18n.SimpleLocaleContext) LocaleContext(org.springframework.context.i18n.LocaleContext) NestedServletException(org.springframework.web.util.NestedServletException) ServletRequestAttributes(org.springframework.web.context.request.ServletRequestAttributes) RequestAttributes(org.springframework.web.context.request.RequestAttributes) ServletRequestAttributes(org.springframework.web.context.request.ServletRequestAttributes) IOException(java.io.IOException)

Example 2 with WebAsyncManager

use of org.springframework.web.context.request.async.WebAsyncManager in project spring-security by spring-projects.

the class WebSecurityConfigurerAdapterMockitoTests method loadConfigWhenDefaultConfigThenWebAsyncManagerIntegrationFilterAdded.

@Test
public void loadConfigWhenDefaultConfigThenWebAsyncManagerIntegrationFilterAdded() throws Exception {
    this.spring.register(WebAsyncPopulatedByDefaultConfig.class).autowire();
    WebAsyncManager webAsyncManager = mock(WebAsyncManager.class);
    this.mockMvc.perform(get("/").requestAttr(WebAsyncUtils.WEB_ASYNC_MANAGER_ATTRIBUTE, webAsyncManager));
    ArgumentCaptor<CallableProcessingInterceptor> callableProcessingInterceptorArgCaptor = ArgumentCaptor.forClass(CallableProcessingInterceptor.class);
    verify(webAsyncManager, atLeastOnce()).registerCallableInterceptor(any(), callableProcessingInterceptorArgCaptor.capture());
    CallableProcessingInterceptor callableProcessingInterceptor = callableProcessingInterceptorArgCaptor.getAllValues().stream().filter((e) -> SecurityContextCallableProcessingInterceptor.class.isAssignableFrom(e.getClass())).findFirst().orElse(null);
    assertThat(callableProcessingInterceptor).isNotNull();
}
Also used : WebAsyncManager(org.springframework.web.context.request.async.WebAsyncManager) SecurityContextCallableProcessingInterceptor(org.springframework.security.web.context.request.async.SecurityContextCallableProcessingInterceptor) CallableProcessingInterceptor(org.springframework.web.context.request.async.CallableProcessingInterceptor) SecurityContextCallableProcessingInterceptor(org.springframework.security.web.context.request.async.SecurityContextCallableProcessingInterceptor) Test(org.junit.jupiter.api.Test)

Example 3 with WebAsyncManager

use of org.springframework.web.context.request.async.WebAsyncManager in project spring-security by spring-projects.

the class WebAsyncManagerIntegrationFilter method doFilterInternal.

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
    SecurityContextCallableProcessingInterceptor securityProcessingInterceptor = (SecurityContextCallableProcessingInterceptor) asyncManager.getCallableInterceptor(CALLABLE_INTERCEPTOR_KEY);
    if (securityProcessingInterceptor == null) {
        asyncManager.registerCallableInterceptor(CALLABLE_INTERCEPTOR_KEY, new SecurityContextCallableProcessingInterceptor());
    }
    filterChain.doFilter(request, response);
}
Also used : WebAsyncManager(org.springframework.web.context.request.async.WebAsyncManager)

Example 4 with WebAsyncManager

use of org.springframework.web.context.request.async.WebAsyncManager in project spring-framework by spring-projects.

the class DispatcherServlet method doDispatch.

/**
 * Process the actual dispatching to the handler.
 * <p>The handler will be obtained by applying the servlet's HandlerMappings in order.
 * The HandlerAdapter will be obtained by querying the servlet's installed HandlerAdapters
 * to find the first that supports the handler class.
 * <p>All HTTP methods are handled by this method. It's up to HandlerAdapters or handlers
 * themselves to decide which methods are acceptable.
 * @param request current HTTP request
 * @param response current HTTP response
 * @throws Exception in case of any kind of processing failure
 */
@SuppressWarnings("deprecation")
protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
    HttpServletRequest processedRequest = request;
    HandlerExecutionChain mappedHandler = null;
    boolean multipartRequestParsed = false;
    WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
    try {
        ModelAndView mv = null;
        Exception dispatchException = null;
        try {
            processedRequest = checkMultipart(request);
            multipartRequestParsed = (processedRequest != request);
            // Determine handler for the current request.
            mappedHandler = getHandler(processedRequest);
            if (mappedHandler == null) {
                noHandlerFound(processedRequest, response);
                return;
            }
            // Determine handler adapter for the current request.
            HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());
            // Process last-modified header, if supported by the handler.
            String method = request.getMethod();
            boolean isGet = HttpMethod.GET.matches(method);
            if (isGet || HttpMethod.HEAD.matches(method)) {
                long lastModified = ha.getLastModified(request, mappedHandler.getHandler());
                if (new ServletWebRequest(request, response).checkNotModified(lastModified) && isGet) {
                    return;
                }
            }
            if (!mappedHandler.applyPreHandle(processedRequest, response)) {
                return;
            }
            // Actually invoke the handler.
            mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
            if (asyncManager.isConcurrentHandlingStarted()) {
                return;
            }
            applyDefaultViewName(processedRequest, mv);
            mappedHandler.applyPostHandle(processedRequest, response, mv);
        } catch (Exception ex) {
            dispatchException = ex;
        } catch (Throwable err) {
            // As of 4.3, we're processing Errors thrown from handler methods as well,
            // making them available for @ExceptionHandler methods and other scenarios.
            dispatchException = new NestedServletException("Handler dispatch failed", err);
        }
        processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException);
    } catch (Exception ex) {
        triggerAfterCompletion(processedRequest, response, mappedHandler, ex);
    } catch (Throwable err) {
        triggerAfterCompletion(processedRequest, response, mappedHandler, new NestedServletException("Handler processing failed", err));
    } finally {
        if (asyncManager.isConcurrentHandlingStarted()) {
            // Instead of postHandle and afterCompletion
            if (mappedHandler != null) {
                mappedHandler.applyAfterConcurrentHandlingStarted(processedRequest, response);
            }
        } else {
            // Clean up any resources used by a multipart request.
            if (multipartRequestParsed) {
                cleanupMultipart(processedRequest);
            }
        }
    }
}
Also used : HttpServletRequest(jakarta.servlet.http.HttpServletRequest) MultipartHttpServletRequest(org.springframework.web.multipart.MultipartHttpServletRequest) WebAsyncManager(org.springframework.web.context.request.async.WebAsyncManager) NestedServletException(org.springframework.web.util.NestedServletException) ServletWebRequest(org.springframework.web.context.request.ServletWebRequest) MultipartException(org.springframework.web.multipart.MultipartException) ServletException(jakarta.servlet.ServletException) BeanInitializationException(org.springframework.beans.factory.BeanInitializationException) NestedServletException(org.springframework.web.util.NestedServletException) IOException(java.io.IOException) NoSuchBeanDefinitionException(org.springframework.beans.factory.NoSuchBeanDefinitionException)

Example 5 with WebAsyncManager

use of org.springframework.web.context.request.async.WebAsyncManager in project spring-framework by spring-projects.

the class HandlerFunctionAdapter method handle.

@Nullable
@Override
public ModelAndView handle(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Object handler) throws Exception {
    WebAsyncManager asyncManager = getWebAsyncManager(servletRequest, servletResponse);
    ServerRequest serverRequest = getServerRequest(servletRequest);
    ServerResponse serverResponse;
    if (asyncManager.hasConcurrentResult()) {
        serverResponse = handleAsync(asyncManager);
    } else {
        HandlerFunction<?> handlerFunction = (HandlerFunction<?>) handler;
        serverResponse = handlerFunction.handle(serverRequest);
    }
    if (serverResponse != null) {
        return serverResponse.writeTo(servletRequest, servletResponse, new ServerRequestContext(serverRequest));
    } else {
        return null;
    }
}
Also used : WebAsyncManager(org.springframework.web.context.request.async.WebAsyncManager) ServerResponse(org.springframework.web.servlet.function.ServerResponse) HandlerFunction(org.springframework.web.servlet.function.HandlerFunction) ServerRequest(org.springframework.web.servlet.function.ServerRequest) Nullable(org.springframework.lang.Nullable)

Aggregations

WebAsyncManager (org.springframework.web.context.request.async.WebAsyncManager)18 AsyncWebRequest (org.springframework.web.context.request.async.AsyncWebRequest)7 Test (org.junit.jupiter.api.Test)6 StandardServletAsyncWebRequest (org.springframework.web.context.request.async.StandardServletAsyncWebRequest)5 ServletWebRequest (org.springframework.web.context.request.ServletWebRequest)4 EntityManager (jakarta.persistence.EntityManager)3 EntityManagerFactory (jakarta.persistence.EntityManagerFactory)3 AsyncEvent (jakarta.servlet.AsyncEvent)3 AsyncListener (jakarta.servlet.AsyncListener)3 IOException (java.io.IOException)3 MockAsyncContext (org.springframework.web.testfixture.servlet.MockAsyncContext)3 PersistenceException (jakarta.persistence.PersistenceException)2 ServletException (jakarta.servlet.ServletException)2 Session (org.hibernate.Session)2 DataAccessResourceFailureException (org.springframework.dao.DataAccessResourceFailureException)2 Nullable (org.springframework.lang.Nullable)2 EntityManagerHolder (org.springframework.orm.jpa.EntityManagerHolder)2 NestedServletException (org.springframework.web.util.NestedServletException)2 FilterChain (jakarta.servlet.FilterChain)1 HttpServletRequest (jakarta.servlet.http.HttpServletRequest)1