org.springframework.test.web.servlet.request.RequestPostProcessor Java Examples

The following examples show how to use org.springframework.test.web.servlet.request.RequestPostProcessor. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AbstractMockMvcBuilder.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Build a {@link org.springframework.test.web.servlet.MockMvc} instance.
 */
@Override
@SuppressWarnings("rawtypes")
public final MockMvc build() {
	WebApplicationContext wac = initWebAppContext();
	ServletContext servletContext = wac.getServletContext();
	MockServletConfig mockServletConfig = new MockServletConfig(servletContext);

	for (MockMvcConfigurer configurer : this.configurers) {
		RequestPostProcessor processor = configurer.beforeMockMvcCreated(this, wac);
		if (processor != null) {
			if (this.defaultRequestBuilder == null) {
				this.defaultRequestBuilder = MockMvcRequestBuilders.get("/");
			}
			if (this.defaultRequestBuilder instanceof ConfigurableSmartRequestBuilder) {
				((ConfigurableSmartRequestBuilder) this.defaultRequestBuilder).with(processor);
			}
		}
	}

	Filter[] filterArray = this.filters.toArray(new Filter[0]);

	return super.createMockMvc(filterArray, mockServletConfig, wac, this.defaultRequestBuilder,
			this.globalResultMatchers, this.globalResultHandlers, this.dispatcherServletCustomizers);
}
 
Example #2
Source File: AbstractMockMvcBuilder.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Build a {@link org.springframework.test.web.servlet.MockMvc} instance.
 */
@Override
@SuppressWarnings("rawtypes")
public final MockMvc build() {
	WebApplicationContext wac = initWebAppContext();
	ServletContext servletContext = wac.getServletContext();
	MockServletConfig mockServletConfig = new MockServletConfig(servletContext);

	for (MockMvcConfigurer configurer : this.configurers) {
		RequestPostProcessor processor = configurer.beforeMockMvcCreated(this, wac);
		if (processor != null) {
			if (this.defaultRequestBuilder == null) {
				this.defaultRequestBuilder = MockMvcRequestBuilders.get("/");
			}
			if (this.defaultRequestBuilder instanceof ConfigurableSmartRequestBuilder) {
				((ConfigurableSmartRequestBuilder) this.defaultRequestBuilder).with(processor);
			}
		}
	}

	Filter[] filterArray = this.filters.toArray(new Filter[0]);

	return super.createMockMvc(filterArray, mockServletConfig, wac, this.defaultRequestBuilder,
			this.globalResultMatchers, this.globalResultHandlers, this.dispatcherServletCustomizers);
}
 
Example #3
Source File: FrameworkExtensionTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public RequestPostProcessor beforeMockMvcCreated(ConfigurableMockMvcBuilder<?> builder,
		WebApplicationContext context) {
	return request -> {
		request.setUserPrincipal(mock(Principal.class));
		return request;
	};
}
 
Example #4
Source File: OAuthHelper.java    From resource-server-testing with MIT License 5 votes vote down vote up
public RequestPostProcessor bearerToken(final String clientid, final String username) {
	return mockRequest -> {
		OAuth2Authentication auth = oAuth2Authentication(clientid, username);
		OAuth2AccessToken token = tokenservice.createAccessToken(auth);
		mockRequest.addHeader("Authorization", "Bearer " + token.getValue());
		return mockRequest;
	};
}
 
Example #5
Source File: MockMvcBase.java    From spring-auto-restdocs with Apache License 2.0 5 votes vote down vote up
protected RequestPostProcessor userToken() {
    return request -> {
        // If the tests requires setup logic for users, you can place it here.
        // Authorization headers or cookies for users should be added here as well.
        String accessToken;
        try {
            accessToken = getAccessToken("test", "test");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        request.addHeader("Authorization", "Bearer " + accessToken);
        return documentAuthorization(request, "User access token required.");
    };
}
 
Example #6
Source File: AccountResourceTest.java    From angularjs-springboot-bookstore with MIT License 5 votes vote down vote up
@Test
public void testAuthenticatedUser() throws Exception {
    restUserMockMvc.perform(get("/api/authenticate")
            .with(new RequestPostProcessor() {
                public MockHttpServletRequest postProcessRequest(MockHttpServletRequest request) {
                    request.setRemoteUser("test");
                    return request;
                }
            })
            .accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andExpect(content().string("test"));
}
 
Example #7
Source File: SharedHttpSessionConfigurer.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public RequestPostProcessor beforeMockMvcCreated(ConfigurableMockMvcBuilder<?> builder,
		WebApplicationContext context) {

	return request -> {
		if (this.session != null) {
			request.setSession(this.session);
		}
		return request;
	};
}
 
Example #8
Source File: FrameworkExtensionTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public RequestPostProcessor beforeMockMvcCreated(ConfigurableMockMvcBuilder<?> builder,
		WebApplicationContext context) {
	return request -> {
		request.setUserPrincipal(mock(Principal.class));
		return request;
	};
}
 
Example #9
Source File: FrameworkExtensionTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public RequestPostProcessor beforeMockMvcCreated(ConfigurableMockMvcBuilder<?> builder,
		WebApplicationContext context) {
	return request -> {
		request.setUserPrincipal(mock(Principal.class));
		return request;
	};
}
 
Example #10
Source File: AbstractMockMvcBuilder.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Build a {@link org.springframework.test.web.servlet.MockMvc} instance.
 */
@Override
@SuppressWarnings("rawtypes")
public final MockMvc build() {

	WebApplicationContext wac = initWebAppContext();

	ServletContext servletContext = wac.getServletContext();
	MockServletConfig mockServletConfig = new MockServletConfig(servletContext);

	for (MockMvcConfigurer configurer : this.configurers) {
		RequestPostProcessor processor = configurer.beforeMockMvcCreated(this, wac);
		if (processor != null) {
			if (this.defaultRequestBuilder == null) {
				this.defaultRequestBuilder = MockMvcRequestBuilders.get("/");
			}
			if (this.defaultRequestBuilder instanceof ConfigurableSmartRequestBuilder) {
				((ConfigurableSmartRequestBuilder) this.defaultRequestBuilder).with(processor);
			}
		}
	}

	Filter[] filterArray = this.filters.toArray(new Filter[this.filters.size()]);

	return super.createMockMvc(filterArray, mockServletConfig, wac, this.defaultRequestBuilder,
			this.globalResultMatchers, this.globalResultHandlers, this.dispatchOptions);
}
 
Example #11
Source File: SharedHttpSessionConfigurer.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public RequestPostProcessor beforeMockMvcCreated(ConfigurableMockMvcBuilder<?> builder,
		WebApplicationContext context) {

	return request -> {
		if (this.session != null) {
			request.setSession(this.session);
		}
		return request;
	};
}
 
Example #12
Source File: OAuth2TokenMockUtil.java    From tutorials with MIT License 4 votes vote down vote up
public RequestPostProcessor oauth2Authentication(String username) {
    return oauth2Authentication(username, Collections.emptySet());
}
 
Example #13
Source File: OAuth2TokenMockUtil.java    From tutorials with MIT License 4 votes vote down vote up
public RequestPostProcessor oauth2Authentication(String username, Set<String> scopes) {
    return oauth2Authentication(username, scopes, Collections.emptySet());
}
 
Example #14
Source File: WritingTest.java    From logbook with MIT License 4 votes vote down vote up
private RequestPostProcessor http11() {
    return request -> {
        request.setProtocol("HTTP/1.1");
        return request;
    };
}
 
Example #15
Source File: OAuth2TokenMockUtil.java    From tutorials with MIT License 4 votes vote down vote up
public RequestPostProcessor oauth2Authentication(String username) {
    return oauth2Authentication(username, Collections.emptySet());
}
 
Example #16
Source File: OAuth2TokenMockUtil.java    From tutorials with MIT License 4 votes vote down vote up
public RequestPostProcessor oauth2Authentication(String username, Set<String> scopes) {
    return oauth2Authentication(username, scopes, Collections.emptySet());
}
 
Example #17
Source File: LayoutDialectControllerIntegrationTest.java    From tutorials with MIT License 4 votes vote down vote up
private RequestPostProcessor testUser() {
    return user("user1").password("user1Pass").roles("USER");
}
 
Example #18
Source File: ExpressionUtilityObjectsControllerIntegrationTest.java    From tutorials with MIT License 4 votes vote down vote up
private RequestPostProcessor testUser() {
    return user("user1").password("user1Pass").roles("USER");
}
 
Example #19
Source File: OAuth2TokenMockUtil.java    From tutorials with MIT License 4 votes vote down vote up
public RequestPostProcessor oauth2Authentication(String username, Set<String> scopes) {
    return oauth2Authentication(username, scopes, Collections.emptySet());
}
 
Example #20
Source File: MyControllerTest.java    From resource-server-testing with MIT License 4 votes vote down vote up
@Test
public void testHelloAliceWithRole() throws Exception {
	RequestPostProcessor bearerToken = helper.bearerToken("myclientwith", "alice");
	mvc.perform(get("/hello").with(bearerToken)).andExpect(status().isOk()).andExpect(content().string("Hello alice"));
}
 
Example #21
Source File: FragmentsIntegrationTest.java    From tutorials with MIT License 4 votes vote down vote up
private RequestPostProcessor testUser() {
    return user("user1").password("user1Pass").roles("USER");
}
 
Example #22
Source File: MyControllerTest.java    From resource-server-testing with MIT License 4 votes vote down vote up
@Test
public void testHelloUserWithRole() throws Exception {
	RequestPostProcessor bearerToken = helper.bearerToken("myclientwith", "user");
	mvc.perform(get("/hello").with(bearerToken)).andExpect(status().isOk()).andExpect(content().string("Hello user"));
}
 
Example #23
Source File: FormRequestTest.java    From logbook with MIT License 4 votes vote down vote up
private RequestPostProcessor http11() {
    return request -> {
        request.setProtocol("HTTP/1.1");
        return request;
    };
}
 
Example #24
Source File: SampleSecureOAuth2ActuatorApplicationTests.java    From spring-security-oauth2-boot with Apache License 2.0 4 votes vote down vote up
private RequestPostProcessor userCredentials() {
	return httpBasic("user", "password");
}
 
Example #25
Source File: SecurityUtils.java    From JavaSpringMvcBlog with MIT License 4 votes vote down vote up
public static RequestPostProcessor userAdmin() {
    return user("admin").roles("USER", "ADMIN");
}
 
Example #26
Source File: SecurityUtils.java    From JavaSpringMvcBlog with MIT License 4 votes vote down vote up
public static RequestPostProcessor userBob() {
    return user("Bob").roles("USER");
}
 
Example #27
Source File: SecurityUtils.java    From JavaSpringMvcBlog with MIT License 4 votes vote down vote up
public static RequestPostProcessor userAlice() {
    return user("Alice").roles("USER");
}
 
Example #28
Source File: HtmlUnitRequestBuilder.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
public void setForwardPostProcessor(RequestPostProcessor forwardPostProcessor) {
	this.forwardPostProcessor = forwardPostProcessor;
}
 
Example #29
Source File: MockMvcConfigurerAdapter.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@Override
public RequestPostProcessor beforeMockMvcCreated(ConfigurableMockMvcBuilder<?> builder, WebApplicationContext cxt) {
	return null;
}
 
Example #30
Source File: AbstractProvisioningTest.java    From freeacs with MIT License 4 votes vote down vote up
public static void provisionUnit(@Nullable RequestPostProcessor authPostProcessor, MockMvc mvc) throws Exception {
    MockHttpSession session = new MockHttpSession();
    MockHttpServletRequestBuilder postRequestBuilder = post("/tr069").session(session);
    if (authPostProcessor != null) {
        postRequestBuilder = postRequestBuilder.with(authPostProcessor);
    }
    mvc.perform(postRequestBuilder
            .content(getFileAsString("/provision/cpe/Inform.xml")))
            .andExpect(status().isOk())
            .andExpect(content().contentType("text/xml"))
            .andExpect(header().string("SOAPAction", ""))
            .andExpect(xpath("/*[local-name() = 'Envelope']" +
                    "/*[local-name() = 'Body']" +
                    "/*[local-name() = 'InformResponse']" +
                    "/MaxEnvelopes")
                    .string("1"));
    mvc.perform(post("/tr069")
            .session(session))
            .andExpect(status().isOk())
            .andExpect(content().contentType("text/xml"))
            .andExpect(header().string("SOAPAction", ""))
            .andExpect(xpath("/*[local-name() = 'Envelope']" +
                    "/*[local-name() = 'Body']" +
                    "/*[local-name() = 'GetParameterValues']" +
                    "/ParameterNames" +
                    "/string[1]")
                    .string("InternetGatewayDevice.DeviceInfo.VendorConfigFile."))
            .andExpect(xpath("/*[local-name() = 'Envelope']" +
                    "/*[local-name() = 'Body']" +
                    "/*[local-name() = 'GetParameterValues']" +
                    "/ParameterNames" +
                    "/string[2]")
                    .string("InternetGatewayDevice.ManagementServer.PeriodicInformInterval"));
    mvc.perform(post("/tr069")
            .session(session)
            .content(getFileAsString("/provision/cpe/GetParameterValuesResponse.xml")))
            .andExpect(status().isOk())
            .andExpect(content().contentType("text/xml"))
            .andExpect(header().string("SOAPAction", ""))
            .andExpect(xpath("/*[local-name() = 'Envelope']" +
                    "/*[local-name() = 'Body']" +
                    "/*[local-name() = 'SetParameterValues']" +
                    "/ParameterList" +
                    "/ParameterValueStruct" +
                    "/Name")
                    .string("InternetGatewayDevice.ManagementServer.PeriodicInformInterval"))
            .andExpect(xpath("/*[local-name() = 'Envelope']" +
                    "/*[local-name() = 'Body']" +
                    "/*[local-name() = 'SetParameterValues']" +
                    "/ParameterList" +
                    "/ParameterValueStruct" +
                    "/Value")
                    .string(hasNoSpace()));
    mvc.perform(post("/tr069")
            .session(session)
            .content(getFileAsString("/provision/cpe/SetParameterValuesResponse.xml")))
            .andExpect(status().isNoContent())
            .andExpect(content().contentType("text/html"))
            .andExpect(header().doesNotExist("SOAPAction"));
    if (authPostProcessor != null) {
        mvc.perform(post("/tr069")
                .session(session))
                .andExpect(status().isUnauthorized());
    }
}