Search in sources :

Example 16 with AsyncContext

use of jakarta.servlet.AsyncContext in project spring-security by spring-projects.

the class SecurityContextHolderAwareRequestFilterTests method getAsyncContextStart.

@Test
public void getAsyncContextStart() throws Exception {
    ArgumentCaptor<Runnable> runnableCaptor = ArgumentCaptor.forClass(Runnable.class);
    SecurityContext context = SecurityContextHolder.createEmptyContext();
    TestingAuthenticationToken expectedAuth = new TestingAuthenticationToken("user", "password", "ROLE_USER");
    context.setAuthentication(expectedAuth);
    SecurityContextHolder.setContext(context);
    AsyncContext asyncContext = mock(AsyncContext.class);
    given(this.request.getAsyncContext()).willReturn(asyncContext);
    Runnable runnable = () -> {
    };
    wrappedRequest().getAsyncContext().start(runnable);
    verifyZeroInteractions(this.authenticationManager, this.logoutHandler);
    verify(asyncContext).start(runnableCaptor.capture());
    DelegatingSecurityContextRunnable wrappedRunnable = (DelegatingSecurityContextRunnable) runnableCaptor.getValue();
    assertThat(ReflectionTestUtils.getField(wrappedRunnable, "delegateSecurityContext")).isEqualTo(context);
    assertThat(ReflectionTestUtils.getField(wrappedRunnable, "delegate"));
}
Also used : DelegatingSecurityContextRunnable(org.springframework.security.concurrent.DelegatingSecurityContextRunnable) SecurityContext(org.springframework.security.core.context.SecurityContext) AsyncContext(jakarta.servlet.AsyncContext) DelegatingSecurityContextRunnable(org.springframework.security.concurrent.DelegatingSecurityContextRunnable) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) Test(org.junit.jupiter.api.Test)

Example 17 with AsyncContext

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

the class ServerHttpRequestTests method createRequest.

private ServerHttpRequest createRequest(String uriString, String contextPath) throws Exception {
    URI uri = URI.create(uriString);
    MockHttpServletRequest request = new TestHttpServletRequest(uri);
    request.setContextPath(contextPath);
    AsyncContext asyncContext = new MockAsyncContext(request, new MockHttpServletResponse());
    return new ServletServerHttpRequest(request, asyncContext, "", DefaultDataBufferFactory.sharedInstance, 1024);
}
Also used : MockHttpServletRequest(org.springframework.web.testfixture.servlet.MockHttpServletRequest) MockAsyncContext(org.springframework.web.testfixture.servlet.MockAsyncContext) MockAsyncContext(org.springframework.web.testfixture.servlet.MockAsyncContext) AsyncContext(jakarta.servlet.AsyncContext) URI(java.net.URI) MockHttpServletResponse(org.springframework.web.testfixture.servlet.MockHttpServletResponse)

Example 18 with AsyncContext

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

the class MockMvc method perform.

/**
 * Perform a request and return a type that allows chaining further
 * actions, such as asserting expectations, on the result.
 * @param requestBuilder used to prepare the request to execute;
 * see static factory methods in
 * {@link org.springframework.test.web.servlet.request.MockMvcRequestBuilders}
 * @return an instance of {@link ResultActions} (never {@code null})
 * @see org.springframework.test.web.servlet.request.MockMvcRequestBuilders
 * @see org.springframework.test.web.servlet.result.MockMvcResultMatchers
 */
public ResultActions perform(RequestBuilder requestBuilder) throws Exception {
    if (this.defaultRequestBuilder != null && requestBuilder instanceof Mergeable) {
        requestBuilder = (RequestBuilder) ((Mergeable) requestBuilder).merge(this.defaultRequestBuilder);
    }
    MockHttpServletRequest request = requestBuilder.buildRequest(this.servletContext);
    AsyncContext asyncContext = request.getAsyncContext();
    MockHttpServletResponse mockResponse;
    HttpServletResponse servletResponse;
    if (asyncContext != null) {
        servletResponse = (HttpServletResponse) asyncContext.getResponse();
        mockResponse = unwrapResponseIfNecessary(servletResponse);
    } else {
        mockResponse = new MockHttpServletResponse();
        servletResponse = mockResponse;
    }
    if (this.defaultResponseCharacterEncoding != null) {
        mockResponse.setDefaultCharacterEncoding(this.defaultResponseCharacterEncoding.name());
    }
    if (requestBuilder instanceof SmartRequestBuilder) {
        request = ((SmartRequestBuilder) requestBuilder).postProcessRequest(request);
    }
    MvcResult mvcResult = new DefaultMvcResult(request, mockResponse);
    request.setAttribute(MVC_RESULT_ATTRIBUTE, mvcResult);
    RequestAttributes previousAttributes = RequestContextHolder.getRequestAttributes();
    RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request, servletResponse));
    MockFilterChain filterChain = new MockFilterChain(this.servlet, this.filters);
    filterChain.doFilter(request, servletResponse);
    if (DispatcherType.ASYNC.equals(request.getDispatcherType()) && asyncContext != null && !request.isAsyncStarted()) {
        asyncContext.complete();
    }
    applyDefaultResultActions(mvcResult);
    RequestContextHolder.setRequestAttributes(previousAttributes);
    return new ResultActions() {

        @Override
        public ResultActions andExpect(ResultMatcher matcher) throws Exception {
            matcher.match(mvcResult);
            return this;
        }

        @Override
        public ResultActions andDo(ResultHandler handler) throws Exception {
            handler.handle(mvcResult);
            return this;
        }

        @Override
        public MvcResult andReturn() {
            return mvcResult;
        }
    };
}
Also used : Mergeable(org.springframework.beans.Mergeable) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) ServletRequestAttributes(org.springframework.web.context.request.ServletRequestAttributes) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) AsyncContext(jakarta.servlet.AsyncContext) ServletRequestAttributes(org.springframework.web.context.request.ServletRequestAttributes) RequestAttributes(org.springframework.web.context.request.RequestAttributes) MockFilterChain(org.springframework.mock.web.MockFilterChain) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse)

Example 19 with AsyncContext

use of jakarta.servlet.AsyncContext 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)

Aggregations

AsyncContext (jakarta.servlet.AsyncContext)19 Test (org.junit.jupiter.api.Test)3 TestingAuthenticationToken (org.springframework.security.authentication.TestingAuthenticationToken)3 DelegatingSecurityContextRunnable (org.springframework.security.concurrent.DelegatingSecurityContextRunnable)3 SecurityContext (org.springframework.security.core.context.SecurityContext)3 HttpServletResponse (jakarta.servlet.http.HttpServletResponse)2 SimpleDateFormat (java.text.SimpleDateFormat)2 Date (java.util.Date)2 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)2 Context (org.apache.catalina.Context)2 Tomcat (org.apache.catalina.startup.Tomcat)2 AsyncListener (jakarta.servlet.AsyncListener)1 ServletException (jakarta.servlet.ServletException)1 ServletInputStream (jakarta.servlet.ServletInputStream)1 ServletOutputStream (jakarta.servlet.ServletOutputStream)1 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1 OutputStream (java.io.OutputStream)1 Socket (java.net.Socket)1 URI (java.net.URI)1