Search in sources :

Example 11 with WebAsyncManager

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

the class OpenEntityManagerInViewTests method testOpenEntityManagerInViewInterceptorAsyncTimeoutScenario.

@Test
public void testOpenEntityManagerInViewInterceptorAsyncTimeoutScenario() throws Exception {
    // Initial request thread
    OpenEntityManagerInViewInterceptor interceptor = new OpenEntityManagerInViewInterceptor();
    interceptor.setEntityManagerFactory(factory);
    given(this.factory.createEntityManager()).willReturn(this.manager);
    interceptor.preHandle(this.webRequest);
    assertThat(TransactionSynchronizationManager.hasResource(this.factory)).isTrue();
    AsyncWebRequest asyncWebRequest = new StandardServletAsyncWebRequest(this.request, this.response);
    WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(this.request);
    asyncManager.setTaskExecutor(this.taskExecutor);
    asyncManager.setAsyncWebRequest(asyncWebRequest);
    asyncManager.startCallableProcessing((Callable<String>) () -> "anything");
    this.taskExecutor.await();
    assertThat(asyncManager.getConcurrentResult()).as("Concurrent result ").isEqualTo("anything");
    interceptor.afterConcurrentHandlingStarted(this.webRequest);
    assertThat(TransactionSynchronizationManager.hasResource(this.factory)).isFalse();
    // Async request timeout
    given(this.manager.isOpen()).willReturn(true);
    MockAsyncContext asyncContext = (MockAsyncContext) this.request.getAsyncContext();
    for (AsyncListener listener : asyncContext.getListeners()) {
        listener.onTimeout(new AsyncEvent(asyncContext));
    }
    for (AsyncListener listener : asyncContext.getListeners()) {
        listener.onComplete(new AsyncEvent(asyncContext));
    }
    verify(this.manager).close();
}
Also used : WebAsyncManager(org.springframework.web.context.request.async.WebAsyncManager) StandardServletAsyncWebRequest(org.springframework.web.context.request.async.StandardServletAsyncWebRequest) AsyncListener(jakarta.servlet.AsyncListener) MockAsyncContext(org.springframework.web.testfixture.servlet.MockAsyncContext) AsyncWebRequest(org.springframework.web.context.request.async.AsyncWebRequest) StandardServletAsyncWebRequest(org.springframework.web.context.request.async.StandardServletAsyncWebRequest) AsyncEvent(jakarta.servlet.AsyncEvent) Test(org.junit.jupiter.api.Test)

Example 12 with WebAsyncManager

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

the class OpenSessionInViewFilter method doFilterInternal.

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    SessionFactory sessionFactory = lookupSessionFactory(request);
    boolean participate = false;
    WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
    String key = getAlreadyFilteredAttributeName();
    if (TransactionSynchronizationManager.hasResource(sessionFactory)) {
        // Do not modify the Session: just set the participate flag.
        participate = true;
    } else {
        boolean isFirstRequest = !isAsyncDispatch(request);
        if (isFirstRequest || !applySessionBindingInterceptor(asyncManager, key)) {
            logger.debug("Opening Hibernate Session in OpenSessionInViewFilter");
            Session session = openSession(sessionFactory);
            SessionHolder sessionHolder = new SessionHolder(session);
            TransactionSynchronizationManager.bindResource(sessionFactory, sessionHolder);
            AsyncRequestInterceptor interceptor = new AsyncRequestInterceptor(sessionFactory, sessionHolder);
            asyncManager.registerCallableInterceptor(key, interceptor);
            asyncManager.registerDeferredResultInterceptor(key, interceptor);
        }
    }
    try {
        filterChain.doFilter(request, response);
    } finally {
        if (!participate) {
            SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.unbindResource(sessionFactory);
            if (!isAsyncStarted(request)) {
                logger.debug("Closing Hibernate Session in OpenSessionInViewFilter");
                SessionFactoryUtils.closeSession(sessionHolder.getSession());
            }
        }
    }
}
Also used : SessionFactory(org.hibernate.SessionFactory) WebAsyncManager(org.springframework.web.context.request.async.WebAsyncManager) SessionHolder(org.springframework.orm.hibernate5.SessionHolder) Session(org.hibernate.Session)

Example 13 with WebAsyncManager

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

the class HandlerFunctionAdapter method getWebAsyncManager.

private WebAsyncManager getWebAsyncManager(HttpServletRequest servletRequest, HttpServletResponse servletResponse) {
    AsyncWebRequest asyncWebRequest = WebAsyncUtils.createAsyncWebRequest(servletRequest, servletResponse);
    asyncWebRequest.setTimeout(this.asyncRequestTimeout);
    WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(servletRequest);
    asyncManager.setAsyncWebRequest(asyncWebRequest);
    return asyncManager;
}
Also used : WebAsyncManager(org.springframework.web.context.request.async.WebAsyncManager) AsyncWebRequest(org.springframework.web.context.request.async.AsyncWebRequest)

Example 14 with WebAsyncManager

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

the class DefaultAsyncServerResponse method writeAsync.

static void writeAsync(HttpServletRequest request, HttpServletResponse response, DeferredResult<?> deferredResult) throws ServletException, IOException {
    WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
    AsyncWebRequest asyncWebRequest = WebAsyncUtils.createAsyncWebRequest(request, response);
    asyncManager.setAsyncWebRequest(asyncWebRequest);
    try {
        asyncManager.startDeferredResultProcessing(deferredResult);
    } catch (IOException | ServletException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new ServletException("Async processing failed", ex);
    }
}
Also used : WebAsyncManager(org.springframework.web.context.request.async.WebAsyncManager) ServletException(jakarta.servlet.ServletException) IOException(java.io.IOException) AsyncWebRequest(org.springframework.web.context.request.async.AsyncWebRequest) TimeoutException(java.util.concurrent.TimeoutException) ServletException(jakarta.servlet.ServletException) IOException(java.io.IOException) CompletionException(java.util.concurrent.CompletionException) ExecutionException(java.util.concurrent.ExecutionException)

Example 15 with WebAsyncManager

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

the class RequestMappingHandlerAdapter method invokeHandlerMethod.

/**
 * Invoke the {@link RequestMapping} handler method preparing a {@link ModelAndView}
 * if view resolution is required.
 * @since 4.2
 * @see #createInvocableHandlerMethod(HandlerMethod)
 */
@Nullable
protected ModelAndView invokeHandlerMethod(HttpServletRequest request, HttpServletResponse response, HandlerMethod handlerMethod) throws Exception {
    ServletWebRequest webRequest = new ServletWebRequest(request, response);
    try {
        WebDataBinderFactory binderFactory = getDataBinderFactory(handlerMethod);
        ModelFactory modelFactory = getModelFactory(handlerMethod, binderFactory);
        ServletInvocableHandlerMethod invocableMethod = createInvocableHandlerMethod(handlerMethod);
        if (this.argumentResolvers != null) {
            invocableMethod.setHandlerMethodArgumentResolvers(this.argumentResolvers);
        }
        if (this.returnValueHandlers != null) {
            invocableMethod.setHandlerMethodReturnValueHandlers(this.returnValueHandlers);
        }
        invocableMethod.setDataBinderFactory(binderFactory);
        invocableMethod.setParameterNameDiscoverer(this.parameterNameDiscoverer);
        ModelAndViewContainer mavContainer = new ModelAndViewContainer();
        mavContainer.addAllAttributes(RequestContextUtils.getInputFlashMap(request));
        modelFactory.initModel(webRequest, mavContainer, invocableMethod);
        mavContainer.setIgnoreDefaultModelOnRedirect(this.ignoreDefaultModelOnRedirect);
        AsyncWebRequest asyncWebRequest = WebAsyncUtils.createAsyncWebRequest(request, response);
        asyncWebRequest.setTimeout(this.asyncRequestTimeout);
        WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
        asyncManager.setTaskExecutor(this.taskExecutor);
        asyncManager.setAsyncWebRequest(asyncWebRequest);
        asyncManager.registerCallableInterceptors(this.callableInterceptors);
        asyncManager.registerDeferredResultInterceptors(this.deferredResultInterceptors);
        if (asyncManager.hasConcurrentResult()) {
            Object result = asyncManager.getConcurrentResult();
            mavContainer = (ModelAndViewContainer) asyncManager.getConcurrentResultContext()[0];
            asyncManager.clearConcurrentResult();
            LogFormatUtils.traceDebug(logger, traceOn -> {
                String formatted = LogFormatUtils.formatValue(result, !traceOn);
                return "Resume with async result [" + formatted + "]";
            });
            invocableMethod = invocableMethod.wrapConcurrentResult(result);
        }
        invocableMethod.invokeAndHandle(webRequest, mavContainer);
        if (asyncManager.isConcurrentHandlingStarted()) {
            return null;
        }
        return getModelAndView(mavContainer, modelFactory, webRequest);
    } finally {
        webRequest.requestCompleted();
    }
}
Also used : WebAsyncManager(org.springframework.web.context.request.async.WebAsyncManager) ModelAndViewContainer(org.springframework.web.method.support.ModelAndViewContainer) ModelFactory(org.springframework.web.method.annotation.ModelFactory) AsyncWebRequest(org.springframework.web.context.request.async.AsyncWebRequest) ServletWebRequest(org.springframework.web.context.request.ServletWebRequest) WebDataBinderFactory(org.springframework.web.bind.support.WebDataBinderFactory) 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