Skip to content

Commit

Permalink
Support Optional in UriComponentsBuilder#queryParam
Browse files Browse the repository at this point in the history
Closes gh-25951
  • Loading branch information
rstoyanchev committed Oct 23, 2020
1 parent 5644a7a commit e66e347
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -698,7 +698,7 @@ public UriComponentsBuilder queryParam(String name, Object... values) {
Assert.notNull(name, "Name must not be null");
if (!ObjectUtils.isEmpty(values)) {
for (Object value : values) {
String valueAsString = (value != null ? value.toString() : null);
String valueAsString = getQueryParamValue(value);
this.queryParams.add(name, valueAsString);
}
}
Expand All @@ -709,6 +709,16 @@ public UriComponentsBuilder queryParam(String name, Object... values) {
return this;
}

@Nullable
private String getQueryParamValue(@Nullable Object value) {
if (value != null) {
return (value instanceof Optional ?
((Optional<?>) value).map(Object::toString).orElse(null) :
value.toString());
}
return null;
}

@Override
public UriComponentsBuilder queryParam(String name, @Nullable Collection<?> values) {
return queryParam(name, (CollectionUtils.isEmpty(values) ? EMPTY_VALUES : values.toArray()));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -749,14 +749,24 @@ void queryParam() {

@Test
void queryParamWithList() {
UriComponentsBuilder builder = UriComponentsBuilder.newInstance();
UriComponents result = builder.queryParam("baz", Arrays.asList("qux", 42)).build();
List<String> values = Arrays.asList("qux", "42");
UriComponents result = UriComponentsBuilder.newInstance().queryParam("baz", values).build();

assertThat(result.getQuery()).isEqualTo("baz=qux&baz=42");
MultiValueMap<String, String> expectedQueryParams = new LinkedMultiValueMap<>(2);
expectedQueryParams.add("baz", "qux");
expectedQueryParams.add("baz", "42");
assertThat(result.getQueryParams()).isEqualTo(expectedQueryParams);
assertThat(result.getQueryParams()).containsOnlyKeys("baz").containsEntry("baz", values);
}

@Test
void queryParamWithOptionalValue() {
UriComponents result = UriComponentsBuilder.newInstance()
.queryParam("foo", Optional.empty())
.queryParam("baz", Optional.of("qux"), 42)
.build();

assertThat(result.getQuery()).isEqualTo("foo&baz=qux&baz=42");
assertThat(result.getQueryParams()).containsOnlyKeys("foo", "baz")
.containsEntry("foo", Collections.singletonList(null))
.containsEntry("baz", Arrays.asList("qux", "42"));
}

@Test
Expand Down

0 comments on commit e66e347

Please sign in to comment.