Search in sources :

Example 16 with AsyncEvent

use of jakarta.servlet.AsyncEvent in project tomcat by apache.

the class AsyncContextImpl method setErrorState.

public void setErrorState(Throwable t, boolean fireOnError) {
    if (t != null) {
        request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t);
    }
    request.getCoyoteRequest().action(ActionCode.ASYNC_ERROR, null);
    if (fireOnError) {
        if (log.isDebugEnabled()) {
            log.debug(sm.getString("asyncContextImpl.fireOnError"));
        }
        AsyncEvent errorEvent = new AsyncEvent(event.getAsyncContext(), event.getSuppliedRequest(), event.getSuppliedResponse(), t);
        List<AsyncListenerWrapper> listenersCopy = new ArrayList<>(listeners);
        for (AsyncListenerWrapper listener : listenersCopy) {
            try {
                listener.fireOnError(errorEvent);
            } catch (Throwable t2) {
                ExceptionUtils.handleThrowable(t2);
                log.warn(sm.getString("asyncContextImpl.onErrorError", listener.getClass().getName()), t2);
            }
        }
    }
    AtomicBoolean result = new AtomicBoolean();
    request.getCoyoteRequest().action(ActionCode.ASYNC_IS_ERROR, result);
    if (result.get()) {
        // No listener called dispatch() or complete(). This is an error.
        // SRV.2.3.3.3 (search for "error dispatch")
        // Take a local copy to avoid threading issues if another thread
        // clears this (can happen during error handling with non-container
        // threads)
        ServletResponse servletResponse = this.servletResponse;
        if (servletResponse instanceof HttpServletResponse) {
            ((HttpServletResponse) servletResponse).setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
        Host host = (Host) context.getParent();
        Valve stdHostValve = host.getPipeline().getBasic();
        if (stdHostValve instanceof StandardHostValve) {
            ((StandardHostValve) stdHostValve).throwable(request, request.getResponse(), t);
        }
        request.getCoyoteRequest().action(ActionCode.ASYNC_IS_ERROR, result);
        if (result.get()) {
            // Still in the error state. The error page did not call
            // complete() or dispatch(). Complete the async processing.
            complete();
        }
    }
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ServletResponse(jakarta.servlet.ServletResponse) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) ArrayList(java.util.ArrayList) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) Valve(org.apache.catalina.Valve) Host(org.apache.catalina.Host) AsyncEvent(jakarta.servlet.AsyncEvent)

Example 17 with AsyncEvent

use of jakarta.servlet.AsyncEvent in project spring-framework by spring-projects.

the class OpenEntityManagerInViewTests method testOpenEntityManagerInViewInterceptorAsyncErrorScenario.

@Test
public void testOpenEntityManagerInViewInterceptorAsyncErrorScenario() 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 error
    given(this.manager.isOpen()).willReturn(true);
    MockAsyncContext asyncContext = (MockAsyncContext) this.request.getAsyncContext();
    for (AsyncListener listener : asyncContext.getListeners()) {
        listener.onError(new AsyncEvent(asyncContext, new Exception()));
    }
    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 18 with AsyncEvent

use of jakarta.servlet.AsyncEvent in project spring-framework by spring-projects.

the class StandardServletAsyncWebRequestTests method startAsyncAfterCompleted.

@Test
public void startAsyncAfterCompleted() throws Exception {
    this.asyncRequest.onComplete(new AsyncEvent(new MockAsyncContext(this.request, this.response)));
    assertThatIllegalStateException().isThrownBy(this.asyncRequest::startAsync).withMessage("Async processing has already completed");
}
Also used : MockAsyncContext(org.springframework.web.testfixture.servlet.MockAsyncContext) AsyncEvent(jakarta.servlet.AsyncEvent) Test(org.junit.jupiter.api.Test)

Example 19 with AsyncEvent

use of jakarta.servlet.AsyncEvent in project spring-framework by spring-projects.

the class StandardServletAsyncWebRequestTests method onErrorHandlerAfterOnErrorEvent.

// SPR-13292
@SuppressWarnings("unchecked")
@Test
public void onErrorHandlerAfterOnErrorEvent() throws Exception {
    Consumer<Throwable> handler = mock(Consumer.class);
    this.asyncRequest.addErrorHandler(handler);
    this.asyncRequest.startAsync();
    Exception e = new Exception();
    this.asyncRequest.onError(new AsyncEvent(this.request.getAsyncContext(), e));
    verify(handler).accept(e);
}
Also used : AsyncEvent(jakarta.servlet.AsyncEvent) Assertions.assertThatIllegalStateException(org.assertj.core.api.Assertions.assertThatIllegalStateException) Test(org.junit.jupiter.api.Test)

Example 20 with AsyncEvent

use of jakarta.servlet.AsyncEvent in project spring-framework by spring-projects.

the class WebAsyncManagerErrorTests method startCallableProcessingErrorAndComplete.

@Test
public void startCallableProcessingErrorAndComplete() throws Exception {
    StubCallable callable = new StubCallable();
    CallableProcessingInterceptor interceptor = mock(CallableProcessingInterceptor.class);
    Exception e = new Exception();
    given(interceptor.handleError(this.asyncWebRequest, callable, e)).willReturn(RESULT_NONE);
    this.asyncManager.registerCallableInterceptor("interceptor", interceptor);
    this.asyncManager.startCallableProcessing(callable);
    AsyncEvent event = new AsyncEvent(new MockAsyncContext(this.servletRequest, this.servletResponse), e);
    this.asyncWebRequest.onError(event);
    this.asyncWebRequest.onComplete(event);
    assertThat(this.asyncManager.hasConcurrentResult()).isTrue();
    assertThat(this.asyncManager.getConcurrentResult()).isEqualTo(e);
    verify(interceptor).beforeConcurrentHandling(this.asyncWebRequest, callable);
    verify(interceptor).afterCompletion(this.asyncWebRequest, callable);
}
Also used : MockAsyncContext(org.springframework.web.testfixture.servlet.MockAsyncContext) AsyncEvent(jakarta.servlet.AsyncEvent) Test(org.junit.jupiter.api.Test)

Aggregations

AsyncEvent (jakarta.servlet.AsyncEvent)25 Test (org.junit.jupiter.api.Test)22 MockAsyncContext (org.springframework.web.testfixture.servlet.MockAsyncContext)19 NativeWebRequest (org.springframework.web.context.request.NativeWebRequest)4 AsyncListener (jakarta.servlet.AsyncListener)3 ServletResponse (jakarta.servlet.ServletResponse)2 HttpServletResponse (jakarta.servlet.http.HttpServletResponse)2 ArrayList (java.util.ArrayList)2 Assertions.assertThatIllegalStateException (org.assertj.core.api.Assertions.assertThatIllegalStateException)2 AsyncWebRequest (org.springframework.web.context.request.async.AsyncWebRequest)2 StandardServletAsyncWebRequest (org.springframework.web.context.request.async.StandardServletAsyncWebRequest)2 WebAsyncManager (org.springframework.web.context.request.async.WebAsyncManager)2 AsyncContext (jakarta.servlet.AsyncContext)1 ServletException (jakarta.servlet.ServletException)1 ServletRequest (jakarta.servlet.ServletRequest)1 HttpServletRequest (jakarta.servlet.http.HttpServletRequest)1 IOException (java.io.IOException)1 URISyntaxException (java.net.URISyntaxException)1 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)1 Context (org.apache.catalina.Context)1