Search in sources :

Example 1 with AsyncListener

use of jakarta.servlet.AsyncListener 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 2 with AsyncListener

use of jakarta.servlet.AsyncListener 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 3 with AsyncListener

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

the class ServletHttpHandlerAdapter method service.

@Override
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
    // Check for existing error attribute first
    if (DispatcherType.ASYNC == request.getDispatcherType()) {
        Throwable ex = (Throwable) request.getAttribute(WRITE_ERROR_ATTRIBUTE_NAME);
        throw new ServletException("Failed to create response content", ex);
    }
    // Start async before Read/WriteListener registration
    AsyncContext asyncContext = request.startAsync();
    asyncContext.setTimeout(-1);
    ServletServerHttpRequest httpRequest;
    AsyncListener requestListener;
    String logPrefix;
    try {
        httpRequest = createRequest(((HttpServletRequest) request), asyncContext);
        requestListener = httpRequest.getAsyncListener();
        logPrefix = httpRequest.getLogPrefix();
    } catch (URISyntaxException ex) {
        if (logger.isDebugEnabled()) {
            logger.debug("Failed to get request  URL: " + ex.getMessage());
        }
        ((HttpServletResponse) response).setStatus(400);
        asyncContext.complete();
        return;
    }
    ServerHttpResponse httpResponse = createResponse(((HttpServletResponse) response), asyncContext, httpRequest);
    AsyncListener responseListener = ((ServletServerHttpResponse) httpResponse).getAsyncListener();
    if (httpRequest.getMethod() == HttpMethod.HEAD) {
        httpResponse = new HttpHeadResponseDecorator(httpResponse);
    }
    AtomicBoolean completionFlag = new AtomicBoolean();
    HandlerResultSubscriber subscriber = new HandlerResultSubscriber(asyncContext, completionFlag, logPrefix);
    asyncContext.addListener(new HttpHandlerAsyncListener(requestListener, responseListener, subscriber, completionFlag, logPrefix));
    this.httpHandler.handle(httpRequest, httpResponse).subscribe(subscriber);
}
Also used : HttpServletResponse(jakarta.servlet.http.HttpServletResponse) AsyncContext(jakarta.servlet.AsyncContext) URISyntaxException(java.net.URISyntaxException) ServletException(jakarta.servlet.ServletException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) AsyncListener(jakarta.servlet.AsyncListener)

Example 4 with AsyncListener

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

the class TestAsyncContextImpl method testAsyncListenerSupplyRequestResponse.

@Test
public void testAsyncListenerSupplyRequestResponse() {
    final ServletRequest servletRequest = EasyMock.createMock(ServletRequest.class);
    final ServletResponse servletResponse = EasyMock.createMock(ServletResponse.class);
    final AsyncListener listener = new AsyncListener() {

        @Override
        public void onTimeout(AsyncEvent event) throws IOException {
            checkRequestResponse(event);
        }

        @Override
        public void onStartAsync(AsyncEvent event) throws IOException {
            checkRequestResponse(event);
        }

        @Override
        public void onError(AsyncEvent event) throws IOException {
            checkRequestResponse(event);
        }

        @Override
        public void onComplete(AsyncEvent event) throws IOException {
            checkRequestResponse(event);
        }

        private void checkRequestResponse(AsyncEvent event) {
            Assert.assertEquals(servletRequest, event.getSuppliedRequest());
            Assert.assertEquals(servletResponse, event.getSuppliedResponse());
        }
    };
    final Context context = new TesterContext();
    final Response response = new Response();
    final Request request = new Request(null);
    request.setCoyoteRequest(new org.apache.coyote.Request());
    request.getMappingData().context = context;
    final AsyncContextImpl ac = new AsyncContextImpl(request);
    ac.addListener(listener, servletRequest, servletResponse);
    ac.setStarted(context, request, response, true);
    ac.addListener(listener, servletRequest, servletResponse);
    ac.setErrorState(new Exception(), true);
    ac.fireOnComplete();
}
Also used : AsyncContext(jakarta.servlet.AsyncContext) Context(org.apache.catalina.Context) TesterContext(org.apache.tomcat.unittest.TesterContext) ServletRequest(jakarta.servlet.ServletRequest) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) ServletResponse(jakarta.servlet.ServletResponse) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) Request(org.apache.catalina.connector.Request) ServletRequest(jakarta.servlet.ServletRequest) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) AsyncEvent(jakarta.servlet.AsyncEvent) URISyntaxException(java.net.URISyntaxException) ServletException(jakarta.servlet.ServletException) IOException(java.io.IOException) ServletResponse(jakarta.servlet.ServletResponse) Response(org.apache.catalina.connector.Response) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) AsyncListener(jakarta.servlet.AsyncListener) TesterContext(org.apache.tomcat.unittest.TesterContext) TomcatBaseTest(org.apache.catalina.startup.TomcatBaseTest) Test(org.junit.Test)

Aggregations

AsyncListener (jakarta.servlet.AsyncListener)4 AsyncEvent (jakarta.servlet.AsyncEvent)3 AsyncContext (jakarta.servlet.AsyncContext)2 ServletException (jakarta.servlet.ServletException)2 HttpServletResponse (jakarta.servlet.http.HttpServletResponse)2 URISyntaxException (java.net.URISyntaxException)2 Test (org.junit.jupiter.api.Test)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 MockAsyncContext (org.springframework.web.testfixture.servlet.MockAsyncContext)2 ServletRequest (jakarta.servlet.ServletRequest)1 ServletResponse (jakarta.servlet.ServletResponse)1 HttpServletRequest (jakarta.servlet.http.HttpServletRequest)1 IOException (java.io.IOException)1 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)1 Context (org.apache.catalina.Context)1 Request (org.apache.catalina.connector.Request)1 Response (org.apache.catalina.connector.Response)1 TomcatBaseTest (org.apache.catalina.startup.TomcatBaseTest)1