Search in sources :

Example 51 with FilterChain

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

the class HttpEntityMethodProcessorTests method handleReturnValueWithETagAndETagFilter.

// SPR-13423
@Test
public void handleReturnValueWithETagAndETagFilter() throws Exception {
    String eTagValue = "\"deadb33f8badf00d\"";
    String content = "body";
    Method method = getClass().getDeclaredMethod("handle");
    MethodParameter returnType = new MethodParameter(method, -1);
    FilterChain chain = (req, res) -> {
        ResponseEntity<String> returnValue = ResponseEntity.ok().eTag(eTagValue).body(content);
        try {
            ServletWebRequest requestToUse = new ServletWebRequest((HttpServletRequest) req, (HttpServletResponse) res);
            new HttpEntityMethodProcessor(Collections.singletonList(new StringHttpMessageConverter())).handleReturnValue(returnValue, returnType, mavContainer, requestToUse);
            assertThat(this.servletResponse.getContentAsString()).as("Response body was cached? It should be written directly to the raw response").isEqualTo(content);
        } catch (Exception ex) {
            throw new IllegalStateException(ex);
        }
    };
    this.servletRequest.setMethod("GET");
    new ShallowEtagHeaderFilter().doFilter(this.servletRequest, this.servletResponse, chain);
    assertThat(this.servletResponse.getStatus()).isEqualTo(200);
    assertThat(this.servletResponse.getHeader(HttpHeaders.ETAG)).isEqualTo(eTagValue);
    assertThat(this.servletResponse.getContentAsString()).isEqualTo(content);
}
Also used : BeforeEach(org.junit.jupiter.api.BeforeEach) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) WebDataBinderFactory(org.springframework.web.bind.support.WebDataBinderFactory) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) ModelAndViewContainer(org.springframework.web.method.support.ModelAndViewContainer) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ArrayList(java.util.ArrayList) NativeWebRequest(org.springframework.web.context.request.NativeWebRequest) JsonTypeName(com.fasterxml.jackson.annotation.JsonTypeName) ServletWebRequest(org.springframework.web.context.request.ServletWebRequest) HandlerMethod(org.springframework.web.method.HandlerMethod) MockHttpServletResponse(org.springframework.web.testfixture.servlet.MockHttpServletResponse) MethodParameter(org.springframework.core.MethodParameter) Nullable(org.springframework.lang.Nullable) LocalValidatorFactoryBean(org.springframework.validation.beanvalidation.LocalValidatorFactoryBean) Method(java.lang.reflect.Method) ShallowEtagHeaderFilter(org.springframework.web.filter.ShallowEtagHeaderFilter) ByteArrayHttpMessageConverter(org.springframework.http.converter.ByteArrayHttpMessageConverter) MockHttpServletRequest(org.springframework.web.testfixture.servlet.MockHttpServletRequest) HttpHeaders(org.springframework.http.HttpHeaders) MediaType(org.springframework.http.MediaType) FilterChain(jakarta.servlet.FilterChain) ResponseBody(org.springframework.web.bind.annotation.ResponseBody) Serializable(java.io.Serializable) StringHttpMessageConverter(org.springframework.http.converter.StringHttpMessageConverter) Test(org.junit.jupiter.api.Test) List(java.util.List) HttpEntity(org.springframework.http.HttpEntity) JsonTypeInfo(com.fasterxml.jackson.annotation.JsonTypeInfo) MappingJackson2HttpMessageConverter(org.springframework.http.converter.json.MappingJackson2HttpMessageConverter) HttpMessageConverter(org.springframework.http.converter.HttpMessageConverter) WebDataBinder(org.springframework.web.bind.WebDataBinder) ResponseEntity(org.springframework.http.ResponseEntity) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) Collections(java.util.Collections) FilterChain(jakarta.servlet.FilterChain) MockHttpServletResponse(org.springframework.web.testfixture.servlet.MockHttpServletResponse) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) HandlerMethod(org.springframework.web.method.HandlerMethod) Method(java.lang.reflect.Method) ShallowEtagHeaderFilter(org.springframework.web.filter.ShallowEtagHeaderFilter) StringHttpMessageConverter(org.springframework.http.converter.StringHttpMessageConverter) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) MockHttpServletRequest(org.springframework.web.testfixture.servlet.MockHttpServletRequest) ResponseEntity(org.springframework.http.ResponseEntity) MethodParameter(org.springframework.core.MethodParameter) ServletWebRequest(org.springframework.web.context.request.ServletWebRequest) Test(org.junit.jupiter.api.Test)

Example 52 with FilterChain

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

the class HttpEntityMethodProcessorMockTests method handleEtagWithHttp304AndEtagFilterHasNoImpact.

@Test
public void handleEtagWithHttp304AndEtagFilterHasNoImpact() throws Exception {
    String eTagValue = "\"deadb33f8badf00d\"";
    FilterChain chain = (req, res) -> {
        servletRequest.addHeader(HttpHeaders.IF_NONE_MATCH, eTagValue);
        ResponseEntity<String> returnValue = ResponseEntity.ok().eTag(eTagValue).body("body");
        initStringMessageConversion(TEXT_PLAIN);
        try {
            processor.handleReturnValue(returnValue, returnTypeResponseEntity, mavContainer, webRequest);
        } catch (Exception ex) {
            throw new IllegalStateException(ex);
        }
    };
    new ShallowEtagHeaderFilter().doFilter(this.servletRequest, this.servletResponse, chain);
    assertConditionalResponse(HttpStatus.NOT_MODIFIED, null, eTagValue, -1);
}
Also used : BeforeEach(org.junit.jupiter.api.BeforeEach) Arrays(java.util.Arrays) ArgumentMatchers.argThat(org.mockito.ArgumentMatchers.argThat) Date(java.util.Date) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) ZonedDateTime(java.time.ZonedDateTime) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) ModelAndViewContainer(org.springframework.web.method.support.ModelAndViewContainer) HttpMessageNotWritableException(org.springframework.http.converter.HttpMessageNotWritableException) ByteArrayResource(org.springframework.core.io.ByteArrayResource) ServletWebRequest(org.springframework.web.context.request.ServletWebRequest) MockHttpServletResponse(org.springframework.web.testfixture.servlet.MockHttpServletResponse) Instant.ofEpochMilli(java.time.Instant.ofEpochMilli) ByteArrayInputStream(java.io.ByteArrayInputStream) BDDMockito.given(org.mockito.BDDMockito.given) MethodParameter(org.springframework.core.MethodParameter) InputStreamResource(org.springframework.core.io.InputStreamResource) APPLICATION_OCTET_STREAM(org.springframework.http.MediaType.APPLICATION_OCTET_STREAM) URI(java.net.URI) Method(java.lang.reflect.Method) Resource(org.springframework.core.io.Resource) MockHttpServletRequest(org.springframework.web.testfixture.servlet.MockHttpServletRequest) HttpHeaders(org.springframework.http.HttpHeaders) MediaType(org.springframework.http.MediaType) Set(java.util.Set) StandardCharsets(java.nio.charset.StandardCharsets) ZoneId(java.time.ZoneId) Test(org.junit.jupiter.api.Test) HttpEntity(org.springframework.http.HttpEntity) HttpMessageConverter(org.springframework.http.converter.HttpMessageConverter) Mockito.mock(org.mockito.Mockito.mock) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ArgumentCaptor(org.mockito.ArgumentCaptor) Assertions.assertThatThrownBy(org.assertj.core.api.Assertions.assertThatThrownBy) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) ShallowEtagHeaderFilter(org.springframework.web.filter.ShallowEtagHeaderFilter) ArgumentMatchers.isA(org.mockito.ArgumentMatchers.isA) RequestEntity(org.springframework.http.RequestEntity) FilterChain(jakarta.servlet.FilterChain) HttpMethod(org.springframework.http.HttpMethod) BDDMockito.then(org.mockito.BDDMockito.then) TEXT_PLAIN(org.springframework.http.MediaType.TEXT_PLAIN) IOException(java.io.IOException) Mockito.times(org.mockito.Mockito.times) Mockito.verify(org.mockito.Mockito.verify) HttpMediaTypeNotSupportedException(org.springframework.web.HttpMediaTypeNotSupportedException) HttpStatus(org.springframework.http.HttpStatus) ArgumentMatchers.anyCollection(org.mockito.ArgumentMatchers.anyCollection) HttpInputMessage(org.springframework.http.HttpInputMessage) Mockito.never(org.mockito.Mockito.never) ChronoUnit(java.time.temporal.ChronoUnit) HttpMediaTypeNotAcceptableException(org.springframework.web.HttpMediaTypeNotAcceptableException) PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE(org.springframework.web.servlet.HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE) ResponseEntity(org.springframework.http.ResponseEntity) Collections(java.util.Collections) RFC_1123_DATE_TIME(java.time.format.DateTimeFormatter.RFC_1123_DATE_TIME) Mockito.reset(org.mockito.Mockito.reset) InputStream(java.io.InputStream) HttpOutputMessage(org.springframework.http.HttpOutputMessage) ResponseEntity(org.springframework.http.ResponseEntity) FilterChain(jakarta.servlet.FilterChain) ShallowEtagHeaderFilter(org.springframework.web.filter.ShallowEtagHeaderFilter) HttpMessageNotWritableException(org.springframework.http.converter.HttpMessageNotWritableException) IOException(java.io.IOException) HttpMediaTypeNotSupportedException(org.springframework.web.HttpMediaTypeNotSupportedException) HttpMediaTypeNotAcceptableException(org.springframework.web.HttpMediaTypeNotAcceptableException) Test(org.junit.jupiter.api.Test)

Example 53 with FilterChain

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

the class OpenEntityManagerInViewTests method testOpenEntityManagerInViewFilterAsyncScenario.

@Test
public void testOpenEntityManagerInViewFilterAsyncScenario() throws Exception {
    given(manager.isOpen()).willReturn(true);
    final EntityManagerFactory factory2 = mock(EntityManagerFactory.class);
    final EntityManager manager2 = mock(EntityManager.class);
    given(factory2.createEntityManager()).willReturn(manager2);
    given(manager2.isOpen()).willReturn(true);
    MockServletContext sc = new MockServletContext();
    StaticWebApplicationContext wac = new StaticWebApplicationContext();
    wac.setServletContext(sc);
    wac.getDefaultListableBeanFactory().registerSingleton("entityManagerFactory", factory);
    wac.getDefaultListableBeanFactory().registerSingleton("myEntityManagerFactory", factory2);
    wac.refresh();
    sc.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
    MockFilterConfig filterConfig = new MockFilterConfig(wac.getServletContext(), "filter");
    MockFilterConfig filterConfig2 = new MockFilterConfig(wac.getServletContext(), "filter2");
    filterConfig2.addInitParameter("entityManagerFactoryBeanName", "myEntityManagerFactory");
    final OpenEntityManagerInViewFilter filter = new OpenEntityManagerInViewFilter();
    filter.init(filterConfig);
    final OpenEntityManagerInViewFilter filter2 = new OpenEntityManagerInViewFilter();
    filter2.init(filterConfig2);
    final AtomicInteger count = new AtomicInteger();
    final FilterChain filterChain = (servletRequest, servletResponse) -> {
        assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue();
        servletRequest.setAttribute("invoked", Boolean.TRUE);
        count.incrementAndGet();
    };
    final AtomicInteger count2 = new AtomicInteger();
    final FilterChain filterChain2 = (servletRequest, servletResponse) -> {
        assertThat(TransactionSynchronizationManager.hasResource(factory2)).isTrue();
        filter.doFilter(servletRequest, servletResponse, filterChain);
        count2.incrementAndGet();
    };
    FilterChain filterChain3 = new PassThroughFilterChain(filter2, filterChain2);
    AsyncWebRequest asyncWebRequest = mock(AsyncWebRequest.class);
    given(asyncWebRequest.isAsyncStarted()).willReturn(true);
    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");
    assertThat(TransactionSynchronizationManager.hasResource(factory)).isFalse();
    assertThat(TransactionSynchronizationManager.hasResource(factory2)).isFalse();
    filter2.doFilter(this.request, this.response, filterChain3);
    assertThat(TransactionSynchronizationManager.hasResource(factory)).isFalse();
    assertThat(TransactionSynchronizationManager.hasResource(factory2)).isFalse();
    assertThat(count.get()).isEqualTo(1);
    assertThat(count2.get()).isEqualTo(1);
    assertThat(request.getAttribute("invoked")).isNotNull();
    verify(asyncWebRequest, times(2)).addCompletionHandler(any(Runnable.class));
    verify(asyncWebRequest).addTimeoutHandler(any(Runnable.class));
    verify(asyncWebRequest, times(2)).addCompletionHandler(any(Runnable.class));
    verify(asyncWebRequest).startAsync();
    // Async dispatch after concurrent handling produces result ...
    reset(asyncWebRequest);
    given(asyncWebRequest.isAsyncStarted()).willReturn(false);
    assertThat(TransactionSynchronizationManager.hasResource(factory)).isFalse();
    assertThat(TransactionSynchronizationManager.hasResource(factory2)).isFalse();
    filter.doFilter(this.request, this.response, filterChain3);
    assertThat(TransactionSynchronizationManager.hasResource(factory)).isFalse();
    assertThat(TransactionSynchronizationManager.hasResource(factory2)).isFalse();
    assertThat(count.get()).isEqualTo(2);
    assertThat(count2.get()).isEqualTo(2);
    verify(this.manager).close();
    verify(manager2).close();
    wac.close();
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) BeforeEach(org.junit.jupiter.api.BeforeEach) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) AsyncWebRequest(org.springframework.web.context.request.async.AsyncWebRequest) StaticWebApplicationContext(org.springframework.web.context.support.StaticWebApplicationContext) Callable(java.util.concurrent.Callable) WebAsyncManager(org.springframework.web.context.request.async.WebAsyncManager) TransactionSynchronizationManager(org.springframework.transaction.support.TransactionSynchronizationManager) ServletWebRequest(org.springframework.web.context.request.ServletWebRequest) MockHttpServletResponse(org.springframework.web.testfixture.servlet.MockHttpServletResponse) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) BDDMockito.given(org.mockito.BDDMockito.given) SimpleAsyncTaskExecutor(org.springframework.core.task.SimpleAsyncTaskExecutor) AsyncEvent(jakarta.servlet.AsyncEvent) StandardServletAsyncWebRequest(org.springframework.web.context.request.async.StandardServletAsyncWebRequest) WebAsyncUtils(org.springframework.web.context.request.async.WebAsyncUtils) MockHttpServletRequest(org.springframework.web.testfixture.servlet.MockHttpServletRequest) FilterChain(jakarta.servlet.FilterChain) WebApplicationContext(org.springframework.web.context.WebApplicationContext) MockFilterConfig(org.springframework.web.testfixture.servlet.MockFilterConfig) Mockito.times(org.mockito.Mockito.times) EntityManagerFactory(jakarta.persistence.EntityManagerFactory) Mockito.verify(org.mockito.Mockito.verify) TimeUnit(java.util.concurrent.TimeUnit) Test(org.junit.jupiter.api.Test) CountDownLatch(java.util.concurrent.CountDownLatch) AfterEach(org.junit.jupiter.api.AfterEach) AsyncListener(jakarta.servlet.AsyncListener) EntityManager(jakarta.persistence.EntityManager) MockAsyncContext(org.springframework.web.testfixture.servlet.MockAsyncContext) PassThroughFilterChain(org.springframework.web.testfixture.servlet.PassThroughFilterChain) Mockito.reset(org.mockito.Mockito.reset) MockServletContext(org.springframework.web.testfixture.servlet.MockServletContext) Mockito.mock(org.mockito.Mockito.mock) WebAsyncManager(org.springframework.web.context.request.async.WebAsyncManager) FilterChain(jakarta.servlet.FilterChain) PassThroughFilterChain(org.springframework.web.testfixture.servlet.PassThroughFilterChain) StaticWebApplicationContext(org.springframework.web.context.support.StaticWebApplicationContext) AsyncWebRequest(org.springframework.web.context.request.async.AsyncWebRequest) StandardServletAsyncWebRequest(org.springframework.web.context.request.async.StandardServletAsyncWebRequest) MockServletContext(org.springframework.web.testfixture.servlet.MockServletContext) MockFilterConfig(org.springframework.web.testfixture.servlet.MockFilterConfig) EntityManager(jakarta.persistence.EntityManager) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) EntityManagerFactory(jakarta.persistence.EntityManagerFactory) PassThroughFilterChain(org.springframework.web.testfixture.servlet.PassThroughFilterChain) Test(org.junit.jupiter.api.Test)

Example 54 with FilterChain

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

the class CharacterEncodingFilterTests method forceEncodingAlwaysSetsEncoding.

@Test
public void forceEncodingAlwaysSetsEncoding() throws Exception {
    HttpServletRequest request = mock(HttpServletRequest.class);
    request.setCharacterEncoding(ENCODING);
    given(request.getAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE)).willReturn(null);
    given(request.getAttribute(filteredName(FILTER_NAME))).willReturn(null);
    given(request.getDispatcherType()).willReturn(DispatcherType.REQUEST);
    HttpServletResponse response = mock(HttpServletResponse.class);
    FilterChain filterChain = mock(FilterChain.class);
    CharacterEncodingFilter filter = new CharacterEncodingFilter(ENCODING, true);
    filter.init(new MockFilterConfig(FILTER_NAME));
    filter.doFilter(request, response, filterChain);
    verify(request).setAttribute(filteredName(FILTER_NAME), Boolean.TRUE);
    verify(request).removeAttribute(filteredName(FILTER_NAME));
    verify(response).setCharacterEncoding(ENCODING);
    verify(filterChain).doFilter(request, response);
}
Also used : HttpServletRequest(jakarta.servlet.http.HttpServletRequest) FilterChain(jakarta.servlet.FilterChain) MockHttpServletResponse(org.springframework.web.testfixture.servlet.MockHttpServletResponse) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) MockFilterConfig(org.springframework.web.testfixture.servlet.MockFilterConfig) Test(org.junit.jupiter.api.Test)

Example 55 with FilterChain

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

the class CharacterEncodingFilterTests method setForceEncodingOnRequestOnly.

// SPR-14240
@Test
public void setForceEncodingOnRequestOnly() throws Exception {
    HttpServletRequest request = mock(HttpServletRequest.class);
    request.setCharacterEncoding(ENCODING);
    given(request.getAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE)).willReturn(null);
    given(request.getAttribute(filteredName(FILTER_NAME))).willReturn(null);
    given(request.getDispatcherType()).willReturn(DispatcherType.REQUEST);
    HttpServletResponse response = mock(HttpServletResponse.class);
    FilterChain filterChain = mock(FilterChain.class);
    CharacterEncodingFilter filter = new CharacterEncodingFilter(ENCODING, true, false);
    filter.init(new MockFilterConfig(FILTER_NAME));
    filter.doFilter(request, response, filterChain);
    verify(request).setAttribute(filteredName(FILTER_NAME), Boolean.TRUE);
    verify(request).removeAttribute(filteredName(FILTER_NAME));
    verify(request, times(2)).setCharacterEncoding(ENCODING);
    verify(response, never()).setCharacterEncoding(ENCODING);
    verify(filterChain).doFilter(request, response);
}
Also used : HttpServletRequest(jakarta.servlet.http.HttpServletRequest) FilterChain(jakarta.servlet.FilterChain) MockHttpServletResponse(org.springframework.web.testfixture.servlet.MockHttpServletResponse) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) MockFilterConfig(org.springframework.web.testfixture.servlet.MockFilterConfig) Test(org.junit.jupiter.api.Test)

Aggregations

FilterChain (jakarta.servlet.FilterChain)141 Test (org.junit.jupiter.api.Test)134 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)103 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)102 HttpServletResponse (jakarta.servlet.http.HttpServletResponse)68 HttpServletRequest (jakarta.servlet.http.HttpServletRequest)54 MockHttpServletResponse (org.springframework.web.testfixture.servlet.MockHttpServletResponse)35 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)32 MockHttpServletRequest (org.springframework.web.testfixture.servlet.MockHttpServletRequest)29 ServletRequest (jakarta.servlet.ServletRequest)25 ServletResponse (jakarta.servlet.ServletResponse)25 Authentication (org.springframework.security.core.Authentication)23 MockFilterChain (org.springframework.mock.web.MockFilterChain)20 ServletException (jakarta.servlet.ServletException)16 StandardCharsets (java.nio.charset.StandardCharsets)16 TestingAuthenticationToken (org.springframework.security.authentication.TestingAuthenticationToken)16 IOException (java.io.IOException)15 BeforeEach (org.junit.jupiter.api.BeforeEach)14 FileCopyUtils (org.springframework.util.FileCopyUtils)14 Arrays (java.util.Arrays)11