Java Code Examples for org.springframework.util.MultiValueMap#set()

The following examples show how to use org.springframework.util.MultiValueMap#set() . 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: WebSecurityTests.java    From java-webapp-security-examples with Apache License 2.0 7 votes vote down vote up
@Test
public void testLogin() throws Exception {
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Collections.singletonList(MediaType.TEXT_HTML));
    MultiValueMap<String, String> form = new LinkedMultiValueMap<>();
    form.set("username", "user");
    form.set("password", "password");
    form.set("remember-me", "true");
    getCsrf(form, headers);
    ResponseEntity<String> entity = new TestRestTemplate().exchange(
            "http://localhost:" + this.port + "/login", HttpMethod.POST,
            new HttpEntity<>(form, headers),
            String.class);
    assertEquals(HttpStatus.FOUND, entity.getStatusCode());
    List<String> cookies = entity.getHeaders().get("Set-Cookie");
    assertTrue(cookies.toString().contains("remember-me"));
    assertEquals("http://localhost:" + this.port + "/", entity.getHeaders()
            .getLocation().toString());
}
 
Example 2
Source File: ComplexPortletApplicationContext.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
public MultipartActionRequest resolveMultipart(ActionRequest request) throws MultipartException {
	if (request.getAttribute("fail") != null) {
		throw new MaxUploadSizeExceededException(1000);
	}
	if (request instanceof MultipartActionRequest) {
		throw new IllegalStateException("Already a multipart request");
	}
	if (request.getAttribute("resolved") != null) {
		throw new IllegalStateException("Already resolved");
	}
	request.setAttribute("resolved", Boolean.TRUE);
	MultiValueMap<String, MultipartFile> files = new LinkedMultiValueMap<String, MultipartFile>();
	files.set("someFile", new MockMultipartFile("someFile", "someContent".getBytes()));
	Map<String, String[]> params = new HashMap<String, String[]>();
	params.put("someParam", new String[] {"someParam"});
	return new DefaultMultipartActionRequest(request, files, params, Collections.<String, String>emptyMap());
}
 
Example 3
Source File: OAuth2TokenEndpointClientAdapter.java    From tutorials with MIT License 6 votes vote down vote up
/**
 * Sends a password grant to the token endpoint.
 *
 * @param username the username to authenticate.
 * @param password his password.
 * @return the access token.
 */
@Override
public OAuth2AccessToken sendPasswordGrant(String username, String password) {
    HttpHeaders reqHeaders = new HttpHeaders();
    reqHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    MultiValueMap<String, String> formParams = new LinkedMultiValueMap<>();
    formParams.set("username", username);
    formParams.set("password", password);
    formParams.set("grant_type", "password");
    addAuthentication(reqHeaders, formParams);
    HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(formParams, reqHeaders);
    log.debug("contacting OAuth2 token endpoint to login user: {}", username);
    ResponseEntity<OAuth2AccessToken>
        responseEntity = restTemplate.postForEntity(getTokenEndpoint(), entity, OAuth2AccessToken.class);
    if (responseEntity.getStatusCode() != HttpStatus.OK) {
        log.debug("failed to authenticate user with OAuth2 token endpoint, status: {}", responseEntity.getStatusCodeValue());
        throw new HttpClientErrorException(responseEntity.getStatusCode());
    }
    OAuth2AccessToken accessToken = responseEntity.getBody();
    return accessToken;
}
 
Example 4
Source File: SampleWebUiApplicationTests.java    From enhanced-pet-clinic with Apache License 2.0 6 votes vote down vote up
@After
public void cleanSession() throws Exception {
	ResponseEntity<String> page = sendRequest("http://localhost:" + this.port, HttpMethod.GET);

	MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
	form.set("_csrf", csrfValue);
	httpHeaders.set("X-CSRF-TOKEN", csrfValue);

	page = sendRequest("http://localhost:" + this.port + "/logout", HttpMethod.GET, form);

	assertEquals(HttpStatus.FOUND, page.getStatusCode());

	if (page.getStatusCode() == HttpStatus.FOUND) {
		page = sendRequest(page.getHeaders().getLocation(), HttpMethod.GET);
	}

	httpHeaders = null;
	csrfValue = null;
}
 
Example 5
Source File: HttpEntityTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testEquals() {
	MultiValueMap<String, String> map1 = new LinkedMultiValueMap<>();
	map1.set("Content-Type", "text/plain");

	MultiValueMap<String, String> map2 = new LinkedMultiValueMap<>();
	map2.set("Content-Type", "application/json");

	assertTrue(new HttpEntity<>().equals(new HttpEntity<Object>()));
	assertFalse(new HttpEntity<>(map1).equals(new HttpEntity<Object>()));
	assertFalse(new HttpEntity<>().equals(new HttpEntity<Object>(map2)));

	assertTrue(new HttpEntity<>(map1).equals(new HttpEntity<Object>(map1)));
	assertFalse(new HttpEntity<>(map1).equals(new HttpEntity<Object>(map2)));

	assertTrue(new HttpEntity<String>(null, null).equals(new HttpEntity<String>(null, null)));
	assertFalse(new HttpEntity<>("foo", null).equals(new HttpEntity<String>(null, null)));
	assertFalse(new HttpEntity<String>(null, null).equals(new HttpEntity<>("bar", null)));

	assertTrue(new HttpEntity<>("foo", map1).equals(new HttpEntity<String>("foo", map1)));
	assertFalse(new HttpEntity<>("foo", map1).equals(new HttpEntity<String>("bar", map1)));
}
 
Example 6
Source File: FormHttpMessageConverterTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void writeForm() throws IOException {
	MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
	body.set("name 1", "value 1");
	body.add("name 2", "value 2+1");
	body.add("name 2", "value 2+2");
	body.add("name 3", null);
	MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
	this.converter.write(body, MediaType.APPLICATION_FORM_URLENCODED, outputMessage);

	assertEquals("Invalid result", "name+1=value+1&name+2=value+2%2B1&name+2=value+2%2B2&name+3",
			outputMessage.getBodyAsString(StandardCharsets.UTF_8));
	assertEquals("Invalid content-type", "application/x-www-form-urlencoded;charset=UTF-8",
			outputMessage.getHeaders().getContentType().toString());
	assertEquals("Invalid content-length", outputMessage.getBodyAsBytes().length,
			outputMessage.getHeaders().getContentLength());
}
 
Example 7
Source File: HttpEntityTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testEquals() {
	MultiValueMap<String, String> map1 = new LinkedMultiValueMap<String, String>();
	map1.set("Content-Type", "text/plain");

	MultiValueMap<String, String> map2 = new LinkedMultiValueMap<String, String>();
	map2.set("Content-Type", "application/json");

	assertTrue(new HttpEntity<Object>().equals(new HttpEntity<Object>()));
	assertFalse(new HttpEntity<Object>(map1).equals(new HttpEntity<Object>()));
	assertFalse(new HttpEntity<Object>().equals(new HttpEntity<Object>(map2)));

	assertTrue(new HttpEntity<Object>(map1).equals(new HttpEntity<Object>(map1)));
	assertFalse(new HttpEntity<Object>(map1).equals(new HttpEntity<Object>(map2)));

	assertTrue(new HttpEntity<String>(null, null).equals(new HttpEntity<String>(null, null)));
	assertFalse(new HttpEntity<String>("foo", null).equals(new HttpEntity<String>(null, null)));
	assertFalse(new HttpEntity<String>(null, null).equals(new HttpEntity<String>("bar", null)));

	assertTrue(new HttpEntity<String>("foo", map1).equals(new HttpEntity<String>("foo", map1)));
	assertFalse(new HttpEntity<String>("foo", map1).equals(new HttpEntity<String>("bar", map1)));
}
 
Example 8
Source File: OAuth2TokenEndpointClientAdapter.java    From cubeai with Apache License 2.0 6 votes vote down vote up
/**
 * Sends a password grant to the token endpoint.
 *
 * @param username the username to authenticate.
 * @param password his password.
 * @return the access token.
 */
@Override
public OAuth2AccessToken sendPasswordGrant(String username, String password) {
    HttpHeaders reqHeaders = new HttpHeaders();
    reqHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    MultiValueMap<String, String> formParams = new LinkedMultiValueMap<>();
    formParams.set("username", username);
    formParams.set("password", password);
    formParams.set("grant_type", "password");
    addAuthentication(reqHeaders, formParams);
    HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(formParams, reqHeaders);
    log.debug("contacting OAuth2 token endpoint to login user: {}", username);
    ResponseEntity<OAuth2AccessToken>
        responseEntity = restTemplate.postForEntity(getTokenEndpoint(), entity, OAuth2AccessToken.class);
    if (responseEntity.getStatusCode() != HttpStatus.OK) {
        log.debug("failed to authenticate user with OAuth2 token endpoint, status: {}", responseEntity.getStatusCodeValue());
        throw new HttpClientErrorException(responseEntity.getStatusCode());
    }
    OAuth2AccessToken accessToken = responseEntity.getBody();
    return accessToken;
}
 
Example 9
Source File: WebSecurityTests.java    From java-webapp-security-examples with Apache License 2.0 6 votes vote down vote up
@Test
public void testDenied() throws Exception {
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Collections.singletonList(MediaType.TEXT_HTML));
    MultiValueMap<String, String> form = new LinkedMultiValueMap<>();
    form.set("username", "admin");
    form.set("password", "admin");
    getCsrf(form, headers);
    ResponseEntity<String> entity = new TestRestTemplate().exchange(
            "http://localhost:" + this.port + "/login", HttpMethod.POST,
            new HttpEntity<>(form, headers),
            String.class);
    assertEquals(HttpStatus.FOUND, entity.getStatusCode());
    String cookie = entity.getHeaders().getFirst("Set-Cookie");
    headers.set("Cookie", cookie);
    ResponseEntity<String> page = new TestRestTemplate().exchange(entity.getHeaders()
                    .getLocation(), HttpMethod.GET, new HttpEntity<Void>(headers),
            String.class);
    assertEquals(HttpStatus.OK, page.getStatusCode());
    cookie = entity.getHeaders().getFirst("Set-Cookie");
    assertTrue(cookie.contains("remember-me"));
    assertTrue("Wrong body (message doesn't match):\n" + entity.getBody(), page
            .getBody().contains("Invalid username and password"));
}
 
Example 10
Source File: BodyInsertersTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void fromMultipartData() {
	MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
	map.set("name 3", "value 3");

	BodyInserters.FormInserter<Object> inserter =
			BodyInserters.fromMultipartData("name 1", "value 1")
					.withPublisher("name 2", Flux.just("foo", "bar", "baz"), String.class)
					.with(map);

	MockClientHttpRequest request = new MockClientHttpRequest(HttpMethod.GET, URI.create("https://example.com"));
	Mono<Void> result = inserter.insert(request, this.context);
	StepVerifier.create(result).expectComplete().verify();

}
 
Example 11
Source File: SampleWebUiApplicationTests.java    From spring-boot-tutorial with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
@Test
public void testCreate() {
    MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
    map.set("text", "FOO text");
    map.set("summary", "FOO");
    URI location = this.restTemplate.postForLocation("/", map);
    assertThat(location.toString()).contains("localhost:" + this.port);
}
 
Example 12
Source File: HttpEntityTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void multiValueMap() {
	MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
	map.set("Content-Type", "text/plain");
	String body = "foo";
	HttpEntity<String> entity = new HttpEntity<>(body, map);
	assertEquals(body, entity.getBody());
	assertEquals(MediaType.TEXT_PLAIN, entity.getHeaders().getContentType());
	assertEquals("text/plain", entity.getHeaders().getFirst("Content-Type"));
}
 
Example 13
Source File: BodyInsertersTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void fromMultipartData() {
	MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
	map.set("name 3", "value 3");

	BodyInserters.FormInserter<Object> inserter =
			BodyInserters.fromMultipartData("name 1", "value 1")
					.withPublisher("name 2", Flux.just("foo", "bar", "baz"), String.class)
					.with(map);

	MockClientHttpRequest request = new MockClientHttpRequest(HttpMethod.GET, URI.create("http://example.com"));
	Mono<Void> result = inserter.insert(request, this.context);
	StepVerifier.create(result).expectComplete().verify();

}
 
Example 14
Source File: OAuth2AuthenticationServiceTest.java    From cubeai with Apache License 2.0 5 votes vote down vote up
private void mockPasswordGrant(OAuth2AccessToken accessToken) {
    HttpHeaders reqHeaders = new HttpHeaders();
    reqHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    reqHeaders.add("Authorization", CLIENT_AUTHORIZATION);                //take over Authorization header from client request to UAA request
    MultiValueMap<String, String> formParams = new LinkedMultiValueMap<>();
    formParams.set("username", "user");
    formParams.set("password", "user");
    formParams.add("grant_type", "password");
    HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(formParams, reqHeaders);
    when(restTemplate.postForEntity("http://uaa/oauth/token", entity, OAuth2AccessToken.class))
        .thenReturn(new ResponseEntity<OAuth2AccessToken>(accessToken, HttpStatus.OK));
}
 
Example 15
Source File: OpenIdAccessTokenProvider.java    From cola with MIT License 5 votes vote down vote up
private MultiValueMap<String, String> getParametersForTokenRequest(OpenIdResourceDetails resource, AccessTokenRequest request) {

		MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
		form.set("grant_type", "openid");
		form.set("openid", resource.getOpenId());
		form.set("provider", resource.getProvider());
		form.putAll(request);

		if (resource.isScoped()) {

			StringBuilder builder = new StringBuilder();
			List<String> scope = resource.getScope();

			if (scope != null) {
				Iterator<String> scopeIt = scope.iterator();
				while (scopeIt.hasNext()) {
					builder.append(scopeIt.next());
					if (scopeIt.hasNext()) {
						builder.append(' ');
					}
				}
			}

			form.set("scope", builder.toString());
		}

		return form;

	}
 
Example 16
Source File: MyAuthorizationCodeAccessTokenProvider.java    From springboot-security-wechat with Apache License 2.0 5 votes vote down vote up
private MultiValueMap<String, String> getParametersForAuthorizeRequest(AuthorizationCodeResourceDetails resource, AccessTokenRequest request) {
    MultiValueMap<String, String> form = new LinkedMultiValueMap();
    form.set("response_type", "code");
    form.set("client_id", resource.getClientId());
    if(request.get("scope") != null) {
        form.set("scope", request.getFirst("scope"));
    } else {
        form.set("scope", OAuth2Utils.formatParameterList(resource.getScope()));
    }

    String redirectUri = resource.getPreEstablishedRedirectUri();
    Object preservedState = request.getPreservedState();
    if(redirectUri == null && preservedState != null) {
        redirectUri = String.valueOf(preservedState);
    } else {
        redirectUri = request.getCurrentUri();
    }

    String stateKey = request.getStateKey();
    if(stateKey != null) {
        form.set("state", stateKey);
        if(preservedState == null) {
            throw new InvalidRequestException("Possible CSRF detected - state parameter was present but no state could be found");
        }
    }

    if(redirectUri != null) {
        form.set("redirect_uri", redirectUri);
    }

    return form;
}
 
Example 17
Source File: YahooOAuth2Template.java    From cloudstreetmarket.com with GNU General Public License v3.0 5 votes vote down vote up
@Override
public YahooAccessGrant exchangeForAccess(String authorizationCode, String redirectUri, MultiValueMap<String, String> additionalParameters) {
	MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
	params.set("client_id", clientId);
	params.set("client_secret", clientSecret);
	params.set("code", authorizationCode);
	params.set("redirect_uri", this.redirectUri != null ? this.redirectUri : redirectUri);
	params.set("grant_type", "authorization_code");
	if (additionalParameters != null) {
		params.putAll(additionalParameters);
	}
	return postForAccessGrant(ACCESS_TOKEN_URL, params);
}
 
Example 18
Source File: AbstractYahooOperations.java    From cloudstreetmarket.com with GNU General Public License v3.0 4 votes vote down vote up
protected URI buildUri(YahooAPIType api, String path, String parameterName, String parameterValue) {
    MultiValueMap<String, String> parameters = new LinkedMultiValueMap<String, String>();
    parameters.set(parameterName, parameterValue);
    return buildUri(api, path, parameters);
}
 
Example 19
Source File: SampleWebUiApplicationTests.java    From enhanced-pet-clinic with Apache License 2.0 4 votes vote down vote up
@Test
public void testCreateUserAndLogin() throws Exception {
	ResponseEntity<String> page = getPage("http://localhost:" + this.port + "/users");

	assertTrue("Client or server error.",
			!page.getStatusCode().is4xxClientError() && !page.getStatusCode().is5xxServerError());

	if (page.getStatusCode() == HttpStatus.FOUND) {
		page = getPage(page.getHeaders().getLocation());
	}

	String body = page.getBody();
	assertNotNull("Body was null", body);

	String username = "newuser";
	String password = "password";
	String formAction = getFormAction(page);

	MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
	form.set("username", username);
	form.set("email", "[email protected]");
	form.set("name", "New User");
	form.set("uiPassword", password);
	form.set("verifyPassword", password);
	form.set("_eventId_saveUser", "Create User");
	form.set("_csrf", csrfValue);

	httpHeaders.set("X-CSRF-TOKEN", csrfValue);

	page = postPage(formAction, form);

	if (page.getStatusCode() == HttpStatus.FOUND) {
		page = getPage(page.getHeaders().getLocation());
	}

	assertEquals(HttpStatus.OK, page.getStatusCode());
	body = page.getBody();
	assertNotNull("Body was null", body);
	assertTrue("User not created:\n" + body, body.contains("User " + username + " saved"));

	executeLogin(username, password);
}
 
Example 20
Source File: EtcdClient.java    From spring-boot-etcd with MIT License 3 votes vote down vote up
/**
 * Sets the value of the node with the given key in etcd. Any previously
 * existing key-value pair is returned as prevNode in the etcd response.
 * 
 * @param key
 *            the node's key
 * @param value
 *            the node's value
 * @return the response from etcd with the node
 * @throws EtcdException
 *             in case etcd returned an error
 */
public EtcdResponse put(final String key, final String value) throws EtcdException {
	UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(KEYSPACE);
	builder.pathSegment(key);

	MultiValueMap<String, String> payload = new LinkedMultiValueMap<>(1);
	payload.set("value", value);

	return execute(builder, HttpMethod.PUT, payload, EtcdResponse.class);
}