Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions docs/modules/ROOT/pages/spring-cloud-openfeign.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -841,6 +841,49 @@ public interface DemoTemplate {

If you need more control over the generated query parameter map, you can implement a custom `QueryMapEncoder` bean.

[[feign-querymap-nested-objects]]
==== Nested objects

By default, a nested object of a `@SpringQueryMap` parameter is sent as the `toString()` value of the object.
To send the fields of nested objects as nested query parameters instead, set `spring.cloud.openfeign.client.config.<name>.nested-query-map-enabled` to `true` for a client, or `spring.cloud.openfeign.client.config.default.nested-query-map-enabled` for every client.
The query parameters then use the property path notation that Spring MVC binds:

* a nested object is sent as `range.from=1&range.to=2`
* the objects of a collection or an array are sent as `filters[0].name=status`
* the entries of a `Map` are sent as `attributes[color]=red`

Simple values, such as strings, numbers or dates, and the values of the other JDK types, such as an `Optional` or a `Duration`, are sent as before.
A nested object whose properties are all `null` is skipped, like a `null` value.
A collection or an array is indexed only when all its elements are nested objects, so a collection with simple values, such as a `List<String>`, is still sent as repeated query parameters.
A `Map` key with a square bracket cannot be written in the property path of its entry, so it is rejected with an `EncodeException`.

For example, with the following classes:

[source,java,indent=0]
----
public class Search {
private String query;
private Range price;
private List<Filter> filters;

// [Getters and setters omitted for brevity]
}

public class Range {
private Integer from;
private Integer to;

// [Getters and setters omitted for brevity]
}
----

a call to `demoEndpoint(@SpringQueryMap Search search)` sends `query=shoes&price.from=10&price.to=20&filters[0].name=color&filters[0].value=red`, which a Spring MVC handler can bind with `@ModelAttribute Search search`.

The option is disabled by default, to keep the behaviour of the existing applications.
When it is enabled for a client, the `QueryMapEncoder` of the client, whether it is the auto-configured one or a custom one, is decorated with the `NestedObjectQueryMapEncoder`.

NOTE: Like the other `spring.cloud.openfeign.client.config.*` properties, `nested-query-map-enabled` has no effect on a client whose `FeignClientConfigurer` returns `false` from `inheritParentConfiguration()` (see <<spring-cloud-feign-overriding-defaults>>).

[[hateoas-support]]
=== HATEOAS support

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@
import org.springframework.cloud.openfeign.clientconfig.FeignClientConfigurer;
import org.springframework.cloud.openfeign.loadbalancer.FeignBlockingLoadBalancerClient;
import org.springframework.cloud.openfeign.loadbalancer.RetryableFeignBlockingLoadBalancerClient;
import org.springframework.cloud.openfeign.support.NestedQueryMapCapability;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
Expand All @@ -78,6 +79,7 @@
* @author Felix Dittrich
* @author Dominique Villard
* @author Can Bezmen
* @author Sharang Gupta
*/
public class FeignClientFactoryBean
implements FactoryBean<Object>, InitializingBean, ApplicationContextAware, BeanFactoryAware {
Expand Down Expand Up @@ -275,6 +277,12 @@ protected void configureUsingProperties(FeignClientProperties.FeignClientConfigu
builder.dismiss404();
}
}
Boolean nestedQueryMapEnabled = finalConfig != null && finalConfig.getNestedQueryMapEnabled() != null
? finalConfig.getNestedQueryMapEnabled()
: (baseConfig != null ? baseConfig.getNestedQueryMapEnabled() : null);
if (Boolean.TRUE.equals(nestedQueryMapEnabled)) {
builder.addCapability(new NestedQueryMapCapability());
}
}

protected void configureUsingProperties(FeignClientProperties.FeignClientConfiguration config,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
* @author Hyeonmin Park
* @author Jasbir Singh
* @author Dominique Villard
* @author Sharang Gupta
*/
@ConfigurationProperties("spring.cloud.openfeign.client")
public class FeignClientProperties {
Expand Down Expand Up @@ -162,6 +163,15 @@ public static class FeignClientConfiguration {

private Class<QueryMapEncoder> queryMapEncoder;

/**
* If {@code true}, the nested objects of a {@code @SpringQueryMap} parameter are
* sent as nested query parameters (for example, {@code range.from=1&range.to=2})
* instead of their {@code toString()} value, and the objects of a collection or
* an array as indexed query parameters (for example,
* {@code filters[0].name=status}).
*/
private Boolean nestedQueryMapEnabled;

private MicrometerProperties micrometer;

private Boolean followRedirects;
Expand Down Expand Up @@ -300,6 +310,14 @@ public void setQueryMapEncoder(Class<QueryMapEncoder> queryMapEncoder) {
this.queryMapEncoder = queryMapEncoder;
}

public Boolean getNestedQueryMapEnabled() {
return nestedQueryMapEnabled;
}

public void setNestedQueryMapEnabled(Boolean nestedQueryMapEnabled) {
this.nestedQueryMapEnabled = nestedQueryMapEnabled;
}

public MicrometerProperties getMicrometer() {
return micrometer;
}
Expand Down Expand Up @@ -345,6 +363,7 @@ public boolean equals(Object o) {
&& Objects.equals(defaultQueryParameters, that.defaultQueryParameters)
&& Objects.equals(capabilities, that.capabilities)
&& Objects.equals(queryMapEncoder, that.queryMapEncoder)
&& Objects.equals(nestedQueryMapEnabled, that.nestedQueryMapEnabled)
&& Objects.equals(micrometer, that.micrometer)
&& Objects.equals(followRedirects, that.followRedirects) && Objects.equals(url, that.url);
}
Expand All @@ -353,8 +372,8 @@ public boolean equals(Object o) {
public int hashCode() {
return Objects.hash(loggerLevel, connectTimeout, readTimeout, retryer, errorDecoder, requestInterceptors,
responseInterceptor, dismiss404, encoder, decoder, contract, exceptionPropagationPolicy,
defaultQueryParameters, defaultRequestHeaders, capabilities, queryMapEncoder, micrometer,
followRedirects, url);
defaultQueryParameters, defaultRequestHeaders, capabilities, queryMapEncoder, nestedQueryMapEnabled,
micrometer, followRedirects, url);
}

}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,193 @@
/*
* Copyright 2013-present 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.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.springframework.cloud.openfeign.support;

import java.lang.reflect.Method;
import java.lang.reflect.RecordComponent;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

import feign.QueryMapEncoder;
import feign.codec.EncodeException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.beans.BeanUtils;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ReflectionUtils;

/**
* A {@link QueryMapEncoder} that sends the nested objects of a query map parameter as
* nested query parameters, with the property path notation that Spring MVC binds.
* <p>
* The query map is produced by the delegate encoder. Then, each nested object, that is a
* value that is neither a simple value (see {@link BeanUtils#isSimpleValueType(Class)})
* nor of a {@code java.*} or {@code javax.*} type, is encoded with the delegate too, and
* its entries are added with the name of the value as a prefix:
* <ul>
* <li>a nested object: {@code range.from=1&range.to=2}</li>
* <li>the objects of a collection or an array: {@code filters[0].name=status}</li>
* <li>the entries of a map: {@code attributes[color]=red}</li>
* </ul>
* Simple values and the values of other JDK types, such as an {@code Optional} or a
* {@code Duration}, are kept as is. A nested object whose properties are all {@code null}
* is skipped, like a {@code null} value. The components of a record are used when the
* delegate finds no properties in it, as a {@code BeanQueryMapEncoder} does, such as the
* one for Spring Data. A collection or an array is encoded with the index of its elements
* only when none of them is such a value, so a collection that has some, such as a
* {@code List<String>}, is still sent as repeated query parameters. A map key with a
* square bracket, and a value that is nested in itself, directly or through other values,
* are rejected with an {@link EncodeException}.
*
* @author Sharang Gupta
* @since 5.1.0
* @see org.springframework.cloud.openfeign.FeignClientProperties.FeignClientConfiguration#getNestedQueryMapEnabled()
*/
public class NestedObjectQueryMapEncoder implements QueryMapEncoder {

private static final Log LOG = LogFactory.getLog(NestedObjectQueryMapEncoder.class);

private final QueryMapEncoder delegate;

public NestedObjectQueryMapEncoder(QueryMapEncoder delegate) {
Assert.notNull(delegate, "delegate must not be null");
this.delegate = delegate;
}

@Override
public Map<String, Object> encode(Object object) throws EncodeException {
if (object == null) {
return Collections.emptyMap();
}
Map<String, Object> queryMap = new LinkedHashMap<>();
Set<Object> path = Collections.newSetFromMap(new IdentityHashMap<>());
path.add(object);
addAll(queryMap, "", delegate.encode(object), path);
return queryMap;
}

private void addAll(Map<String, Object> queryMap, String prefix, Map<String, Object> values, Set<Object> path) {
values.forEach((name, value) -> add(queryMap, prefix + name, value, path));
}

private void add(Map<String, Object> queryMap, String name, Object value, Set<Object> path) {
if (value == null) {
return;
}
if (isPlainValue(value)) {
queryMap.put(name, value);
return;
}
// Track the maps, collections, arrays and objects on the current path, so that
// a value nested in itself is rejected instead of recursing forever
if (!path.add(value)) {
throw new EncodeException("Cannot encode the query map: an object of type " + value.getClass().getName()
+ " is nested in itself under '" + name + "'");
}
addNested(queryMap, name, value, path);
path.remove(value);
}

private void addNested(Map<String, Object> queryMap, String name, Object value, Set<Object> path) {
if (value instanceof Map<?, ?> map) {
map.forEach((key, entryValue) -> add(queryMap, name + "[" + mapKey(name, key) + "]", entryValue, path));
}
else if (value instanceof Iterable<?> || value.getClass().isArray()) {
addElements(queryMap, name, value, path);
}
else {
Map<String, Object> properties = delegate.encode(value);
if (properties.isEmpty() && value instanceof Record record) {
// A BeanQueryMapEncoder finds no properties in a record
properties = componentsOf(record);
}
if (properties.isEmpty()) {
// An object whose properties are all null adds nothing, like a null value
if (LOG.isDebugEnabled()) {
LOG.debug("Skipping the nested object '" + name + "' of type " + value.getClass().getName()
+ " from the query map, as none of its properties has a value");
}
return;
}
addAll(queryMap, name + ".", properties, path);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe we should log something if an object with null values is dropped?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good idea. In d003160, the encoder logs at debug level when it skips a nested object because none of its properties has a value, with the name of the parameter and the type of the object.

}
}

private void addElements(Map<String, Object> queryMap, String name, Object value, Set<Object> path) {
Iterable<?> elements = (value instanceof Iterable<?> iterable) ? iterable : CollectionUtils.arrayToList(value);
if (!areAllNested(elements)) {
// A plain value has no property path to index, so keep the elements as Feign
// sends them: an Iterable as repeated query parameters
queryMap.put(name, elements);
return;
}
int index = 0;
for (Object element : elements) {
add(queryMap, name + "[" + index++ + "]", element, path);
}
}

private static String mapKey(String name, Object key) {
String mapKey = String.valueOf(key);
if (mapKey.indexOf('[') >= 0 || mapKey.indexOf(']') >= 0) {
throw new EncodeException("Cannot encode the query map: the key '" + mapKey + "' of the map under '" + name
+ "' has a square bracket, which the property path of its entry cannot hold");
}
return mapKey;
}

private static boolean areAllNested(Iterable<?> elements) {
boolean anyPresent = false;
for (Object element : elements) {
if (element == null) {
continue;
}
if (isPlainValue(element)) {
return false;
}
anyPresent = true;
}
return anyPresent;
}

private static Map<String, Object> componentsOf(Record record) {
Map<String, Object> components = new LinkedHashMap<>();
for (RecordComponent component : record.getClass().getRecordComponents()) {
Method accessor = component.getAccessor();
ReflectionUtils.makeAccessible(accessor);
Object componentValue = ReflectionUtils.invokeMethod(accessor, record);
if (componentValue != null) {
components.put(component.getName(), componentValue);
}
}
return components;
}

private static boolean isPlainValue(Object value) {
if (value instanceof Map<?, ?> || value instanceof Iterable<?> || value.getClass().isArray()) {
return false;
}
String typeName = value.getClass().getName();
return BeanUtils.isSimpleValueType(value.getClass()) || typeName.startsWith("java.")
|| typeName.startsWith("javax.");
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/*
* Copyright 2013-present 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.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.springframework.cloud.openfeign.support;

import feign.Capability;
import feign.QueryMapEncoder;

/**
* A {@link Capability} that decorates the {@link QueryMapEncoder} of a Feign client,
* whichever it is, with the {@link NestedObjectQueryMapEncoder}.
*
* @author Sharang Gupta
* @since 5.1.0
* @see org.springframework.cloud.openfeign.FeignClientProperties.FeignClientConfiguration#getNestedQueryMapEnabled()
*/
public class NestedQueryMapCapability implements Capability {

@Override
public QueryMapEncoder enrich(QueryMapEncoder queryMapEncoder) {
return new NestedObjectQueryMapEncoder(queryMapEncoder);
}

}
Loading
Loading