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

The following examples show how to use org.springframework.util.MultiValueMap#get() . 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: FormHttpMessageConverterTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void readForm() throws Exception {
	String body = "name+1=value+1&name+2=value+2%2B1&name+2=value+2%2B2&name+3";
	Charset iso88591 = Charset.forName("ISO-8859-1");
	MockHttpInputMessage inputMessage = new MockHttpInputMessage(body.getBytes(iso88591));
	inputMessage.getHeaders().setContentType(new MediaType("application", "x-www-form-urlencoded", iso88591));
	MultiValueMap<String, String> result = this.converter.read(null, inputMessage);

	assertEquals("Invalid result", 3, result.size());
	assertEquals("Invalid result", "value 1", result.getFirst("name 1"));
	List<String> values = result.get("name 2");
	assertEquals("Invalid result", 2, values.size());
	assertEquals("Invalid result", "value 2+1", values.get(0));
	assertEquals("Invalid result", "value 2+2", values.get(1));
	assertNull("Invalid result", result.getFirst("name 3"));
}
 
Example 2
Source File: DocumentSecurityServiceImpl.java    From rice with Educational Community License v2.0 6 votes vote down vote up
protected MultiValueMap<PartitionKey, Document> partitionDocumentsForSecurity(List<Document> documents,
        SecuritySession securitySession) {
    MultiValueMap<PartitionKey, Document> partitions = new LinkedMultiValueMap<PartitionKey, Document>();
    for (Document document : documents) {
        DocumentTypeSecurity security = getDocumentTypeSecurity(document.getDocumentTypeName(), securitySession);
        MultiValueMap<String, ExtensionDefinition> securityAttributeExtensionDefinitions = loadExtensionDefinitions(
                security, securitySession);
        for (String applicationId : securityAttributeExtensionDefinitions.keySet()) {
            List<ExtensionDefinition> extensionDefinitions = securityAttributeExtensionDefinitions.get(
                    applicationId);
            PartitionKey key = new PartitionKey(applicationId, extensionDefinitions);
            partitions.add(key, document);
        }
    }
    return partitions;
}
 
Example 3
Source File: AbstractFlashMapManager.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Whether the given FlashMap matches the current request.
 * Uses the expected request path and query parameters saved in the FlashMap.
 */
protected boolean isFlashMapForRequest(FlashMap flashMap, HttpServletRequest request) {
	String expectedPath = flashMap.getTargetRequestPath();
	if (expectedPath != null) {
		String requestUri = getUrlPathHelper().getOriginatingRequestUri(request);
		if (!requestUri.equals(expectedPath) && !requestUri.equals(expectedPath + "/")) {
			return false;
		}
	}
	UriComponents uriComponents = ServletUriComponentsBuilder.fromRequest(request).build();
	MultiValueMap<String, String> actualParams = uriComponents.getQueryParams();
	MultiValueMap<String, String> expectedParams = flashMap.getTargetRequestParams();
	for (String expectedName : expectedParams.keySet()) {
		List<String> actualValues = actualParams.get(expectedName);
		if (actualValues == null) {
			return false;
		}
		for (String expectedValue : expectedParams.get(expectedName)) {
			if (!actualValues.contains(expectedValue)) {
				return false;
			}
		}
	}
	return true;
}
 
Example 4
Source File: FormHttpMessageConverterTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void readForm() throws Exception {
	String body = "name+1=value+1&name+2=value+2%2B1&name+2=value+2%2B2&name+3";
	MockHttpInputMessage inputMessage = new MockHttpInputMessage(body.getBytes(StandardCharsets.ISO_8859_1));
	inputMessage.getHeaders().setContentType(
			new MediaType("application", "x-www-form-urlencoded", StandardCharsets.ISO_8859_1));
	MultiValueMap<String, String> result = this.converter.read(null, inputMessage);

	assertEquals("Invalid result", 3, result.size());
	assertEquals("Invalid result", "value 1", result.getFirst("name 1"));
	List<String> values = result.get("name 2");
	assertEquals("Invalid result", 2, values.size());
	assertEquals("Invalid result", "value 2+1", values.get(0));
	assertEquals("Invalid result", "value 2+2", values.get(1));
	assertNull("Invalid result", result.getFirst("name 3"));
}
 
Example 5
Source File: AuthorizationServerInfo.java    From spring-boot-demo with MIT License 6 votes vote down vote up
public HttpHeaders postForHeaders(String path, MultiValueMap<String, String> formData, final HttpHeaders headers) {
    RequestCallback requestCallback = new NullRequestCallback();
    if (headers != null) {
        requestCallback = request -> request.getHeaders().putAll(headers);
    }
    StringBuilder builder = new StringBuilder(getUrl(path));
    if (!path.contains("?")) {
        builder.append("?");
    } else {
        builder.append("&");
    }
    for (String key : formData.keySet()) {
        for (String value : formData.get(key)) {
            builder.append(key).append("=").append(value);
            builder.append("&");
        }
    }
    builder.deleteCharAt(builder.length() - 1);

    return client.execute(builder.toString(), HttpMethod.POST, requestCallback,
        HttpMessage::getHeaders);
}
 
Example 6
Source File: MockRestRequestMatchers.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private static void assertValueCount(
		String valueType, final String name, MultiValueMap<String, String> map, int count) {

	List<String> values = map.get(name);
	String message = "Expected " + valueType + " <" + name + ">";
	if (values == null) {
		fail(message + " to exist but was null");
	}
	if (count > values.size()) {
		fail(message + " to have at least <" + count + "> values but found " + values);
	}
}
 
Example 7
Source File: ImporterExporterComponentConditional.java    From sofa-lookout with Apache License 2.0 5 votes vote down vote up
private <T> T getFirstAnnotationValueFromMetadata(MultiValueMap<String, Object> map,
                                                  String attributeName) {
    List<Object> value = map.get(attributeName);
    if (CollectionUtils.isEmpty(value)) {
        return null;
    }
    return (T) value.get(0);
}
 
Example 8
Source File: ContentFetchCommand.java    From convergent-ui with Apache License 2.0 5 votes vote down vote up
@Override
protected ContentResponse run() throws Exception {
    log.debug("Getting live content from [ " + location + " ]");
    try {
        HttpServletRequest request = requestContext.getRequest();
        MultiValueMap<String, String> headers = this.helper
                .buildZuulRequestHeaders(request);

        if (request.getQueryString() != null && !request.getQueryString().isEmpty()) {
            MultiValueMap<String, String> params = this.helper
                    .buildZuulRequestQueryParams(request);
        }

        HttpHeaders requestHeaders = new HttpHeaders();
        for (String key : headers.keySet()) {
            for (String s : headers.get(key)) {
                requestHeaders.add(key, s);
            }
        }
        HttpEntity requestEntity = new HttpEntity(null, requestHeaders);

        ResponseEntity<Object> exchange = this.restTemplate.exchange(location, HttpMethod.GET, requestEntity, Object.class);
        
        ContentResponse response = new ContentResponse();
        response.setContent(exchange.getBody());
        response.setContentType(exchange.getHeaders().getContentType());
        response.setError(false);

        return response;
    } catch (Exception e) {
        log.debug("Error fetching live content from [ " + location + " ]", e);
        throw e;
    }
}
 
Example 9
Source File: UrlPathHelper.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Decode the given matrix variables via
 * {@link #decodeRequestString(HttpServletRequest, String)} unless
 * {@link #setUrlDecode(boolean)} is set to {@code true} in which case it is
 * assumed the URL path from which the variables were extracted is already
 * decoded through a call to
 * {@link #getLookupPathForRequest(HttpServletRequest)}.
 * @param request current HTTP request
 * @param vars URI variables extracted from the URL path
 * @return the same Map or a new Map instance
 */
public MultiValueMap<String, String> decodeMatrixVariables(HttpServletRequest request, MultiValueMap<String, String> vars) {
	if (this.urlDecode) {
		return vars;
	}
	else {
		MultiValueMap<String, String> decodedVars = new LinkedMultiValueMap	<String, String>(vars.size());
		for (String key : vars.keySet()) {
			for (String value : vars.get(key)) {
				decodedVars.add(key, decodeInternal(request, value));
			}
		}
		return decodedVars;
	}
}
 
Example 10
Source File: FormHttpMessageConverter.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
private boolean isMultipart(MultiValueMap<String, ?> map, MediaType contentType) {
	if (contentType != null) {
		return MediaType.MULTIPART_FORM_DATA.includes(contentType);
	}
	for (String name : map.keySet()) {
		for (Object value : map.get(name)) {
			if (value != null && !(value instanceof String)) {
				return true;
			}
		}
	}
	return false;
}
 
Example 11
Source File: FlashMap.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Provide request parameters identifying the request for this FlashMap.
 * @param params a Map with the names and values of expected parameters
 */
public FlashMap addTargetRequestParams(MultiValueMap<String, String> params) {
	if (params != null) {
		for (String key : params.keySet()) {
			for (String value : params.get(key)) {
				addTargetRequestParam(key, value);
			}
		}
	}
	return this;
}
 
Example 12
Source File: SpecialRoutesFilter.java    From spring-microservices-in-action with Apache License 2.0 5 votes vote down vote up
/**
 * Convert a {@code MultiValueMap} object to an array of 
 * the {@code Header} objects for the HTTP headers.
 * 
 * @param  headers
 *         The {@code MultiValueMap} object for the headers.
 * 
 * @return  The array of {@code Header} objects.
 */
private Header[] convertHeaders(MultiValueMap<String, String> headers) {
    List<Header> list = new ArrayList<>();
    for (String name : headers.keySet()) {
        for (String value : headers.get(name)) {
            list.add(new BasicHeader(name, value));
        }
    }
    return list.toArray(new BasicHeader[0]);
}
 
Example 13
Source File: AbstractNamedValueServiceParameterResolver.java    From spring-cloud-alibaba with Apache License 2.0 5 votes vote down vote up
@Override
public Object resolve(RestMethodMetadata restMethodMetadata,
		MethodParameterMetadata methodParameterMetadata, HttpServerRequest request) {

	Collection<String> names = getNames(restMethodMetadata, methodParameterMetadata);

	if (isEmpty(names)) { // index can't match
		return null;
	}

	MultiValueMap<String, String> nameAndValues = getNameAndValuesMap(request);

	String targetName = null;

	for (String name : names) {
		if (nameAndValues.containsKey(name)) {
			targetName = name;
			break;
		}
	}

	if (targetName == null) { // request parameter is abstract
		return null;
	}

	Class<?> parameterType = resolveClass(methodParameterMetadata.getType());

	Object paramValue = null;

	if (parameterType.isArray()) { // Array type
		paramValue = nameAndValues.get(targetName);
	}
	else {
		paramValue = nameAndValues.getFirst(targetName);
	}

	return resolveValue(paramValue, parameterType);
}
 
Example 14
Source File: MockRestRequestMatchers.java    From java-technology-stack with MIT License 5 votes vote down vote up
private static void assertValueCount(
		String valueType, final String name, MultiValueMap<String, String> map, int count) {

	List<String> values = map.get(name);
	String message = "Expected " + valueType + " <" + name + ">";
	if (values == null) {
		fail(message + " to exist but was null");
	}
	if (count > values.size()) {
		fail(message + " to have at least <" + count + "> values but found " + values);
	}
}
 
Example 15
Source File: FormHttpMessageConverter.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private boolean isMultipart(MultiValueMap<String, ?> map, @Nullable MediaType contentType) {
	if (contentType != null) {
		return MediaType.MULTIPART_FORM_DATA.includes(contentType);
	}
	for (String name : map.keySet()) {
		for (Object value : map.get(name)) {
			if (value != null && !(value instanceof String)) {
				return true;
			}
		}
	}
	return false;
}
 
Example 16
Source File: CookieWebSessionIdResolver.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public List<String> resolveSessionIds(ServerWebExchange exchange) {
	MultiValueMap<String, HttpCookie> cookieMap = exchange.getRequest().getCookies();
	List<HttpCookie> cookies = cookieMap.get(getCookieName());
	if (cookies == null) {
		return Collections.emptyList();
	}
	return cookies.stream().map(HttpCookie::getValue).collect(Collectors.toList());
}
 
Example 17
Source File: EchoResource.java    From aws-serverless-java-container with Apache License 2.0 5 votes vote down vote up
@RequestMapping(path = "/multivalue-query-string", method = RequestMethod.GET)
public MapResponseModel countMultivalueQueryParams(@RequestParam MultiValueMap<String, String> multipleParams) {
    MapResponseModel out =  new MapResponseModel();
    for (String v : multipleParams.get("multiple")) {
        out.addValue(v, "ok");
    }
    return out;
}
 
Example 18
Source File: ProfileCondition.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
	MultiValueMap<String, Object> attrs = metadata.getAllAnnotationAttributes(Profile.class.getName());
	if (attrs != null) {
		for (Object value : attrs.get("value")) {
			if (context.getEnvironment().acceptsProfiles(Profiles.of((String[]) value))) {
				return true;
			}
		}
		return false;
	}
	return true;
}
 
Example 19
Source File: CommonsMultipartResolverTests.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
private void doTestFiles(MultipartHttpServletRequest request) throws IOException {
	Set<String> fileNames = new HashSet<String>();
	Iterator<String> fileIter = request.getFileNames();
	while (fileIter.hasNext()) {
		fileNames.add(fileIter.next());
	}
	assertEquals(3, fileNames.size());
	assertTrue(fileNames.contains("field1"));
	assertTrue(fileNames.contains("field2"));
	assertTrue(fileNames.contains("field2x"));
	CommonsMultipartFile file1 = (CommonsMultipartFile) request.getFile("field1");
	CommonsMultipartFile file2 = (CommonsMultipartFile) request.getFile("field2");
	CommonsMultipartFile file2x = (CommonsMultipartFile) request.getFile("field2x");

	Map<String, MultipartFile> fileMap = request.getFileMap();
	assertEquals(3, fileMap.size());
	assertTrue(fileMap.containsKey("field1"));
	assertTrue(fileMap.containsKey("field2"));
	assertTrue(fileMap.containsKey("field2x"));
	assertEquals(file1, fileMap.get("field1"));
	assertEquals(file2, fileMap.get("field2"));
	assertEquals(file2x, fileMap.get("field2x"));

	MultiValueMap<String, MultipartFile> multiFileMap = request.getMultiFileMap();
	assertEquals(3, multiFileMap.size());
	assertTrue(multiFileMap.containsKey("field1"));
	assertTrue(multiFileMap.containsKey("field2"));
	assertTrue(multiFileMap.containsKey("field2x"));
	List<MultipartFile> field1Files = multiFileMap.get("field1");
	assertEquals(2, field1Files.size());
	assertTrue(field1Files.contains(file1));
	assertEquals(file1, multiFileMap.getFirst("field1"));
	assertEquals(file2, multiFileMap.getFirst("field2"));
	assertEquals(file2x, multiFileMap.getFirst("field2x"));

	assertEquals("type1", file1.getContentType());
	assertEquals("type2", file2.getContentType());
	assertEquals("type2", file2x.getContentType());
	assertEquals("field1.txt", file1.getOriginalFilename());
	assertEquals("field2.txt", file2.getOriginalFilename());
	assertEquals("field2x.txt", file2x.getOriginalFilename());
	assertEquals("text1", new String(file1.getBytes()));
	assertEquals("text2", new String(file2.getBytes()));
	assertEquals(5, file1.getSize());
	assertEquals(5, file2.getSize());
	assertTrue(file1.getInputStream() instanceof ByteArrayInputStream);
	assertTrue(file2.getInputStream() instanceof ByteArrayInputStream);
	File transfer1 = new File("C:/transfer1");
	file1.transferTo(transfer1);
	File transfer2 = new File("C:/transfer2");
	file2.transferTo(transfer2);
	assertEquals(transfer1, ((MockFileItem) file1.getFileItem()).writtenFile);
	assertEquals(transfer2, ((MockFileItem) file2.getFileItem()).writtenFile);

}
 
Example 20
Source File: ConditionEvaluator.java    From java-technology-stack with MIT License 4 votes vote down vote up
@SuppressWarnings("unchecked")
private List<String[]> getConditionClasses(AnnotatedTypeMetadata metadata) {
	MultiValueMap<String, Object> attributes = metadata.getAllAnnotationAttributes(Conditional.class.getName(), true);
	Object values = (attributes != null ? attributes.get("value") : null);
	return (List<String[]>) (values != null ? values : Collections.emptyList());
}