Skip to content

Commit 81f8501

Browse files
committed
#1114 - Provide HalFormsConfiguration API to order fields.
Register various patterns of sorting based on types.
1 parent a9527a3 commit 81f8501

File tree

8 files changed

+178
-15
lines changed

8 files changed

+178
-15
lines changed

src/main/asciidoc/mediatypes.adoc

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -222,6 +222,8 @@ Spring HATEOAS allows to customize those by shaping the model type for the input
222222

223223
For types that you cannot annotate manually, you can register a custom pattern via a `HalFormsConfiguration` bean present in the application context.
224224

225+
.Registering regex patterns for types
226+
====
225227
[source, java]
226228
----
227229
@Configuration
@@ -235,9 +237,35 @@ class CustomConfiguration {
235237
}
236238
}
237239
----
240+
====
238241

239242
This setup will cause the HAL-FORMS template properties for representation model properties of type `CreditCardNumber` to declare a `regex` field with value `[0-9]{16}`.
240243

244+
[[mediatypes.hal-forms.property-order]]
245+
=== Ordering template properties
246+
247+
By default, HAL-FORMS properties are gleaned from the related domain object using Spring Framework's `BeanUtils`. There is no defined ordering. If you wish to enforce a
248+
particular order on these properties, you can specify that through `HalFormsConfiguration`.
249+
250+
.Registering order of template properties for types
251+
====
252+
[source,java]
253+
----
254+
@Configuration
255+
class CustomConfiguration {
256+
257+
@Bean
258+
HalFormsConfiguration halFormsConfiguration() {
259+
260+
HalFormsConfiguration configuration = new HalFormsConfiguration();
261+
configuration.withFieldOrderFor(Employee.class, "employeeId", "name", "role");
262+
}
263+
}
264+
----
265+
====
266+
267+
The listed properties will be rendered first, followed by any not cited.
268+
241269
[[mediatypes.hal-forms.i18n]]
242270
=== Internationalization of form attributes
243271
HAL-FORMS contains attributes that are intended for human interpretation, like a template's title or property prompts.

src/main/java/org/springframework/hateoas/AffordanceModel.java

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,8 @@ static InputPayloadMetadata from(PayloadMetadata metadata) {
161161
* @return
162162
*/
163163
List<String> getI18nCodes();
164+
165+
Optional<ResolvableType> getType();
164166
}
165167

166168
/**
@@ -210,7 +212,17 @@ public <T extends Named> T customize(T target, Function<PropertyMetadata, T> cus
210212
public List<String> getI18nCodes() {
211213
return Collections.emptyList();
212214
}
213-
}
215+
216+
@Override
217+
public Optional<ResolvableType> getType() {
218+
219+
if (metadata instanceof InputPayloadMetadata) {
220+
((InputPayloadMetadata) metadata).getType();
221+
}
222+
223+
return Optional.empty();
224+
}
225+
}
214226

215227
/**
216228
* Metadata about the property model of a representation.

src/main/java/org/springframework/hateoas/mediatype/Affordances.java

Lines changed: 4 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -308,17 +308,10 @@ private String getNameOrDefault() {
308308

309309
String name = method.toString().toLowerCase();
310310

311-
ResolvableType type = TypeBasedPayloadMetadata.class.isInstance(inputMetdata) //
312-
? TypeBasedPayloadMetadata.class.cast(inputMetdata).getType() //
313-
: null;
314-
315-
if (type == null) {
316-
return name;
317-
}
318-
319-
Class<?> resolvedType = type.resolve();
320-
321-
return resolvedType == null ? name : name.concat(resolvedType.getSimpleName());
311+
return inputMetdata.getType() //
312+
.map(ResolvableType::resolve) //
313+
.map(resolvedType -> resolvedType == null ? name : name.concat(resolvedType.getSimpleName())) //
314+
.orElse(name);
322315
}
323316
}
324317
}

src/main/java/org/springframework/hateoas/mediatype/TypeBasedPayloadMetadata.java

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020

2121
import java.util.Arrays;
2222
import java.util.List;
23+
import java.util.Optional;
2324
import java.util.SortedMap;
2425
import java.util.TreeMap;
2526
import java.util.function.Function;
@@ -39,7 +40,7 @@
3940
*/
4041
class TypeBasedPayloadMetadata implements InputPayloadMetadata {
4142

42-
private final @Getter(AccessLevel.PACKAGE) ResolvableType type;
43+
private final ResolvableType type;
4344
private final SortedMap<String, PropertyMetadata> properties;
4445

4546
TypeBasedPayloadMetadata(ResolvableType type, Stream<PropertyMetadata> properties) {
@@ -93,4 +94,9 @@ public List<String> getI18nCodes() {
9394

9495
return Arrays.asList(type.getName(), type.getSimpleName());
9596
}
97+
98+
@Override
99+
public Optional<ResolvableType> getType() {
100+
return Optional.ofNullable(this.type);
101+
}
96102
}

src/main/java/org/springframework/hateoas/mediatype/hal/forms/HalFormsConfiguration.java

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,9 @@
1818
import lombok.Getter;
1919
import lombok.RequiredArgsConstructor;
2020

21+
import java.util.Arrays;
2122
import java.util.HashMap;
23+
import java.util.List;
2224
import java.util.Map;
2325
import java.util.Optional;
2426

@@ -36,6 +38,7 @@ public class HalFormsConfiguration {
3638

3739
private final @Getter HalConfiguration halConfiguration;
3840
private final Map<Class<?>, String> patterns = new HashMap<>();
41+
private final Map<Class<?>, List<String>> fieldOrder = new HashMap<>();
3942

4043
/**
4144
* Creates a new {@link HalFormsConfiguration} backed by a default {@link HalConfiguration}.
@@ -60,4 +63,15 @@ public HalFormsConfiguration registerPattern(Class<?> type, String pattern) {
6063
Optional<String> getTypePatternFor(ResolvableType type) {
6164
return Optional.ofNullable(patterns.get(type.resolve(Object.class)));
6265
}
66+
67+
public HalFormsConfiguration withFieldOrderFor(Class<?> type, String... fieldNames) {
68+
69+
this.fieldOrder.put(type, Arrays.asList(fieldNames));
70+
71+
return this;
72+
}
73+
74+
Optional<List<String>> getFieldOrderFor(ResolvableType type) {
75+
return Optional.ofNullable(fieldOrder.get(type.resolve(Object.class)));
76+
}
6377
}

src/main/java/org/springframework/hateoas/mediatype/hal/forms/HalFormsTemplateBuilder.java

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,8 @@ public Map<String, HalFormsTemplate> findTemplates(RepresentationModel<?> resour
7979
.map(property -> it.hasHttpMethod(HttpMethod.PATCH) ? property.withRequired(false) : property)
8080
.collect(Collectors.toList());
8181

82+
propertiesWithPrompt = sorted(propertiesWithPrompt, it.getInput());
83+
8284
HalFormsTemplate template = HalFormsTemplate.forMethod(it.getHttpMethod()) //
8385
.withProperties(propertiesWithPrompt);
8486

@@ -89,6 +91,33 @@ public Map<String, HalFormsTemplate> findTemplates(RepresentationModel<?> resour
8991
return templates;
9092
}
9193

94+
private List<HalFormsProperty> sorted(List<HalFormsProperty> properties, InputPayloadMetadata input) {
95+
96+
return input.getType() //
97+
.flatMap(configuration::getFieldOrderFor) //
98+
.map(fieldsToSortBy -> {
99+
100+
List<HalFormsProperty> propertiesToSort = new ArrayList<>(properties);
101+
List<HalFormsProperty> sortedProperties = new ArrayList<>();
102+
103+
for (String propertyName : fieldsToSortBy) {
104+
properties.stream() //
105+
.filter(halFormsProperty -> halFormsProperty.getName().equals(propertyName)) //
106+
.findFirst() //
107+
.ifPresent(halFormsProperty -> {
108+
sortedProperties.add(halFormsProperty);
109+
propertiesToSort.remove(halFormsProperty);
110+
});
111+
}
112+
113+
// Whatever properties weren't listed, add them at the end.
114+
sortedProperties.addAll(propertiesToSort);
115+
116+
return sortedProperties;
117+
}) //
118+
.orElse(properties);
119+
}
120+
92121
public PropertyCustomizations forMetadata(InputPayloadMetadata metadata) {
93122
return new PropertyCustomizations(metadata);
94123
}

src/test/java/org/springframework/hateoas/mediatype/AffordancesUnitTests.java

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717

1818
import static org.assertj.core.api.Assertions.*;
1919

20+
import java.util.Optional;
2021
import java.util.function.Consumer;
2122
import java.util.stream.Stream;
2223

@@ -113,8 +114,8 @@ public PayloadMetadataAssert(PayloadMetadata actual) {
113114

114115
public PayloadMetadataAssert isBackedBy(Class<?> type) {
115116

116-
Assertions.assertThat(actual).isInstanceOfSatisfying(TypeBasedPayloadMetadata.class, it -> {
117-
Assertions.assertThat(it.getType()).isEqualTo(ResolvableType.forClass(type));
117+
assertThat(actual).isInstanceOfSatisfying(TypeBasedPayloadMetadata.class, it -> {
118+
assertThat(it.getType()).isEqualTo(Optional.of(ResolvableType.forClass(type)));
118119
});
119120

120121
return this;
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
package org.springframework.hateoas.mediatype.hal.forms;
2+
3+
import lombok.Data;
4+
5+
import org.junit.jupiter.api.BeforeEach;
6+
import org.junit.jupiter.api.Test;
7+
import org.springframework.hateoas.Link;
8+
import org.springframework.hateoas.RepresentationModel;
9+
import org.springframework.hateoas.mediatype.Affordances;
10+
import org.springframework.hateoas.mediatype.MessageResolver;
11+
import org.springframework.http.HttpMethod;
12+
13+
import static org.assertj.core.api.Assertions.*;
14+
15+
public class HalFormsPropertyOrderingUnitTest {
16+
17+
private RepresentationModel<?> model;
18+
19+
@BeforeEach
20+
void setUp() {
21+
22+
this.model = new RepresentationModel<>(Affordances.of(Link.of("/example")) //
23+
.afford(HttpMethod.POST) //
24+
.withInput(Thing.class) //
25+
.toLink());
26+
}
27+
28+
@Test
29+
void noCustomOrdering() {
30+
31+
HalFormsConfiguration halFormsConfiguration = new HalFormsConfiguration();
32+
33+
assertThat(createTemplate(halFormsConfiguration).getProperties()).flatExtracting(HalFormsProperty::getName)
34+
.containsExactly("a", "b", "z");
35+
36+
}
37+
38+
@Test
39+
void specifyAllProperties() {
40+
41+
HalFormsConfiguration halFormsConfiguration = new HalFormsConfiguration() //
42+
.withFieldOrderFor(Thing.class, "z", "b", "a");
43+
44+
assertThat(createTemplate(halFormsConfiguration).getProperties()).flatExtracting(HalFormsProperty::getName)
45+
.containsExactly("z", "b", "a");
46+
}
47+
48+
@Test
49+
void specifySomeProperties() {
50+
51+
HalFormsConfiguration halFormsConfiguration = new HalFormsConfiguration() //
52+
.withFieldOrderFor(Thing.class, "z");
53+
54+
assertThat(createTemplate(halFormsConfiguration).getProperties()).flatExtracting(HalFormsProperty::getName)
55+
.containsExactly("z", "a", "b");
56+
}
57+
58+
@Test
59+
void nonExistentProperty() {
60+
61+
HalFormsConfiguration halFormsConfiguration = new HalFormsConfiguration() //
62+
.withFieldOrderFor(Thing.class, "q", "b");
63+
64+
assertThat(createTemplate(halFormsConfiguration).getProperties()).flatExtracting(HalFormsProperty::getName)
65+
.containsExactly("b", "a", "z");
66+
}
67+
68+
private HalFormsTemplate createTemplate(HalFormsConfiguration halFormsConfiguration) {
69+
return new HalFormsTemplateBuilder(halFormsConfiguration, MessageResolver.DEFAULTS_ONLY).findTemplates(this.model)
70+
.get("default");
71+
}
72+
73+
@Data
74+
private static class Thing {
75+
76+
private String a;
77+
private String b;
78+
private String z;
79+
}
80+
}

0 commit comments

Comments
 (0)