UriComponents support for array query params

Issue: SPR-9712
This commit is contained in:
Rossen Stoyanchev 2016-01-29 15:32:42 -05:00
parent aa064d7653
commit f5aa011722
2 changed files with 31 additions and 2 deletions

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -336,6 +336,7 @@ final class HierarchicalUriComponents extends UriComponents {
private MultiValueMap<String, String> expandQueryParams(UriTemplateVariables variables) {
int size = this.queryParams.size();
MultiValueMap<String, String> result = new LinkedMultiValueMap<String, String>(size);
variables = new QueryUriTemplateVariables(variables);
for (Map.Entry<String, List<String>> entry : this.queryParams.entrySet()) {
String name = expandUriComponent(entry.getKey(), variables);
List<String> values = new ArrayList<String>(entry.getValue().size());
@ -882,4 +883,22 @@ final class HierarchicalUriComponents extends UriComponents {
}
};
private static class QueryUriTemplateVariables implements UriTemplateVariables {
private final UriTemplateVariables delegate;
public QueryUriTemplateVariables(UriTemplateVariables delegate) {
this.delegate = delegate;
}
@Override
public Object getValue(String name) {
Object value = this.delegate.getValue(name);
if (ObjectUtils.isArray(value)) {
value = StringUtils.arrayToCommaDelimitedString(ObjectUtils.toObjectArray(value));
}
return value;
}
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -30,6 +30,7 @@ import static org.junit.Assert.*;
/**
* @author Arjen Poutsma
* @author Juergen Hoeller
* @author Rossen Stoyanchev
*/
public class UriTemplateTests {
@ -47,6 +48,15 @@ public class UriTemplateTests {
assertEquals("Invalid expanded template", new URI("http://example.com/hotels/1/bookings/42"), result);
}
// SPR-9712
@Test @SuppressWarnings("PrimitiveArrayArgumentToVariableArgMethod")
public void expandVarArgsWithArrayValue() throws Exception {
UriTemplate template = new UriTemplate("/sum?numbers={numbers}");
URI result = template.expand(new int[] {1, 2, 3});
assertEquals(new URI("/sum?numbers=1,2,3"), result);
}
@Test(expected = IllegalArgumentException.class)
public void expandVarArgsNotEnoughVariables() throws Exception {
UriTemplate template = new UriTemplate("http://example.com/hotels/{hotel}/bookings/{booking}");