-
Notifications
You must be signed in to change notification settings - Fork 556
/
DomainObjectReaderUnitTests.java
executable file
·874 lines (643 loc) · 26.2 KB
/
DomainObjectReaderUnitTests.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
/*
* Copyright 2015-2022 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.data.rest.webmvc.json;
import static com.fasterxml.jackson.annotation.JsonProperty.Access.*;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.*;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.RequiredArgsConstructor;
import lombok.Value;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.*;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentMatchers;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Immutable;
import org.springframework.data.annotation.ReadOnlyProperty;
import org.springframework.data.annotation.Reference;
import org.springframework.data.annotation.Transient;
import org.springframework.data.annotation.Version;
import org.springframework.data.keyvalue.core.mapping.context.KeyValueMappingContext;
import org.springframework.data.mapping.PersistentProperty;
import org.springframework.data.mapping.context.PersistentEntities;
import org.springframework.data.rest.core.config.RepositoryRestConfiguration;
import org.springframework.data.rest.core.mapping.ResourceMappings;
import org.springframework.data.rest.webmvc.mapping.Associations;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeInfo.As;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.node.ObjectNode;
/**
* Unit tests for {@link DomainObjectReader}.
*
* @author Oliver Gierke
* @author Craig Andrews
* @author Mathias Düsterhöft
* @author Ken Dombeck
* @author Thomas Mrozinski
*/
@ExtendWith(MockitoExtension.class)
class DomainObjectReaderUnitTests {
@Mock ResourceMappings mappings;
DomainObjectReader reader;
PersistentEntities entities;
@BeforeEach
void setUp() {
KeyValueMappingContext<?, ?> mappingContext = new KeyValueMappingContext<>();
mappingContext.getPersistentEntity(SampleUser.class);
mappingContext.getPersistentEntity(Person.class);
mappingContext.getPersistentEntity(TypeWithGenericMap.class);
mappingContext.getPersistentEntity(VersionedType.class);
mappingContext.getPersistentEntity(SampleWithCreatedDate.class);
mappingContext.getPersistentEntity(SampleWithTransient.class);
mappingContext.getPersistentEntity(User.class);
mappingContext.getPersistentEntity(Inner.class);
mappingContext.getPersistentEntity(Outer.class);
mappingContext.getPersistentEntity(Parent.class);
mappingContext.getPersistentEntity(Product.class);
mappingContext.getPersistentEntity(TransientReadOnlyProperty.class);
mappingContext.getPersistentEntity(CollectionOfEnumWithMethods.class);
mappingContext.getPersistentEntity(SampleWithReference.class);
mappingContext.getPersistentEntity(Note.class);
mappingContext.getPersistentEntity(WithNullCollection.class);
mappingContext.getPersistentEntity(ArrayHolder.class);
mappingContext.getPersistentEntity(Apple.class);
mappingContext.getPersistentEntity(Pear.class);
mappingContext.afterPropertiesSet();
this.entities = new PersistentEntities(Collections.singleton(mappingContext));
this.reader = new DomainObjectReader(entities, new Associations(mappings, mock(RepositoryRestConfiguration.class)));
}
@Test // DATAREST-461
void doesNotConsiderIgnoredProperties() throws Exception {
SampleUser user = new SampleUser("firstname", "password");
JsonNode node = new ObjectMapper().readTree("{}");
SampleUser result = reader.readPut((ObjectNode) node, user, new ObjectMapper());
assertThat(result.name).isNull();
assertThat(result.password).isEqualTo("password");
}
@Test // DATAREST-556
void considersMappedFieldNamesWhenApplyingNodeToDomainObject() throws Exception {
ObjectMapper mapper = new ObjectMapper();
mapper.setPropertyNamingStrategy(PropertyNamingStrategy.UPPER_CAMEL_CASE);
JsonNode node = new ObjectMapper().readTree("{\"FirstName\":\"Carter\",\"LastName\":\"Beauford\"}");
Person result = reader.readPut((ObjectNode) node, new Person("Dave", "Matthews"), mapper);
assertThat(result.firstName).isEqualTo("Carter");
assertThat(result.lastName).isEqualTo("Beauford");
}
@Test // DATAREST-605
void mergesMapCorrectly() throws Exception {
SampleUser user = new SampleUser("firstname", "password");
user.relatedUsers = Collections.singletonMap("parent", new SampleUser("firstname", "password"));
JsonNode node = new ObjectMapper()
.readTree("{ \"relatedUsers\" : { \"parent\" : { \"password\" : \"sneeky\", \"name\" : \"Oliver\" } } }");
SampleUser result = reader.readPut((ObjectNode) node, user, new ObjectMapper());
// Assert that the nested Map values also consider ignored properties
assertThat(result.relatedUsers.get("parent").password).isEqualTo("password");
assertThat(result.relatedUsers.get("parent").name).isEqualTo("Oliver");
}
@Test // DATAREST-701
@SuppressWarnings("unchecked")
void mergesNestedMapWithoutTypeInformation() throws Exception {
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree("{\"map\" : {\"a\": \"1\", \"b\": {\"c\": \"2\"}}}");
TypeWithGenericMap target = new TypeWithGenericMap();
target.map = new HashMap<String, Object>();
target.map.put("b", new HashMap<String, Object>());
TypeWithGenericMap result = reader.readPut((ObjectNode) node, target, mapper);
assertThat(result.map.get("a")).isEqualTo("1");
Object object = result.map.get("b");
assertThat(object).isInstanceOf(Map.class);
assertThat(((Map<Object, Object>) object).get("c")).isEqualTo("2");
}
@Test // DATAREST-701
void rejectsMergingUnknownDomainObject() throws Exception {
ObjectMapper mapper = new ObjectMapper();
ObjectNode node = (ObjectNode) mapper.readTree("{}");
assertThatExceptionOfType(JsonMappingException.class) //
.isThrownBy(() -> reader.readPut(node, "", mapper));
}
@Test // DATAREST-705
void doesNotWipeIdAndVersionPropertyForPut() throws Exception {
VersionedType type = new VersionedType();
type.id = 1L;
type.version = 1L;
type.firstname = "Dave";
ObjectMapper mapper = new ObjectMapper();
ObjectNode node = (ObjectNode) mapper.readTree("{ \"lastname\" : \"Matthews\" }");
VersionedType result = reader.readPut(node, type, mapper);
assertThat(result.lastname).isEqualTo("Matthews");
assertThat(result.firstname).isNull();
assertThat(result.id).isEqualTo(1L);
assertThat(result.version).isEqualTo(1L);
}
@Test // DATAREST-1006
void doesNotWipeReadOnlyJsonPropertyForPut() throws Exception {
SampleUser sampleUser = new SampleUser("name", "password");
sampleUser.lastLogin = new Date();
ObjectMapper mapper = new ObjectMapper();
ObjectNode node = (ObjectNode) mapper.readTree("{ \"name\" : \"another\" }");
SampleUser result = reader.readPut(node, sampleUser, mapper);
assertThat(result.name).isEqualTo("another");
assertThat(result.password).isNotNull();
assertThat(result.lastLogin).isNotNull();
}
@Test // DATAREST-873
void doesNotApplyInputToReadOnlyFields() throws Exception {
ObjectMapper mapper = new ObjectMapper();
ObjectNode node = (ObjectNode) mapper.readTree("{}");
Date reference = new Date();
SampleWithCreatedDate sample = new SampleWithCreatedDate();
sample.createdDate = reference;
assertThat(reader.readPut(node, sample, mapper).createdDate).isEqualTo(reference);
}
@Test // DATAREST-931
void readsPatchForEntityNestedInCollection() throws Exception {
Phone phone = new Phone();
phone.creationDate = new GregorianCalendar();
User user = new User();
user.phones.add(phone);
ByteArrayInputStream source = new ByteArrayInputStream(
"{ \"phones\" : [ { \"label\" : \"some label\" } ] }".getBytes(StandardCharsets.UTF_8));
User result = reader.read(source, user, new ObjectMapper());
assertThat(result.phones.get(0).creationDate).isNotNull();
}
@Test // DATAREST-919
@SuppressWarnings("unchecked")
void readsComplexNestedMapsAndArrays() throws Exception {
Map<String, Object> childMap = new HashMap<String, Object>();
childMap.put("child1", "ok");
HashMap<String, Object> nestedMap = new HashMap<String, Object>();
nestedMap.put("c1", "v1");
TypeWithGenericMap map = new TypeWithGenericMap();
map.map = new HashMap<String, Object>();
map.map.put("sub1", "ok");
map.map.put("sub2", new ArrayList<String>(Arrays.asList("ok1", "ok2")));
map.map.put("sub3", new ArrayList<Object>(Arrays.asList(childMap)));
map.map.put("sub4", nestedMap);
ObjectMapper mapper = new ObjectMapper();
ObjectNode payload = (ObjectNode) mapper.readTree("{ \"map\" : { \"sub1\" : \"ok\","
+ " \"sub2\" : [ \"ok1\", \"ok2\" ], \"sub3\" : [ { \"childOk1\" : \"ok\" }], \"sub4\" : {"
+ " \"c1\" : \"v1\", \"c2\" : \"new\" } } }");
TypeWithGenericMap result = reader.readPut(payload, map, mapper);
assertThat(result.map.get("sub1")).isEqualTo("ok");
List<String> sub2 = as(result.map.get("sub2"), List.class);
assertThat(sub2.get(0)).isEqualTo("ok1");
assertThat(sub2.get(1)).isEqualTo("ok2");
List<Map<String, String>> sub3 = as(result.map.get("sub3"), List.class);
assertThat(sub3.get(0).get("childOk1")).isEqualTo("ok");
Map<Object, String> sub4 = as(result.map.get("sub4"), Map.class);
assertThat(sub4.get("c1")).isEqualTo("v1");
assertThat(sub4.get("c2")).isEqualTo("new");
}
@Test // DATAREST-938
void nestedEntitiesAreUpdated() throws Exception {
Inner inner = new Inner();
inner.name = "inner name";
inner.prop = "something";
Outer outer = new Outer();
outer.prop = "else";
outer.name = "outer name";
outer.inner = inner;
JsonNode node = new ObjectMapper().readTree("{ \"inner\" : { \"name\" : \"new inner name\" } }");
Outer result = reader.doMerge((ObjectNode) node, outer, new ObjectMapper());
assertThat(result).isSameAs(outer);
assertThat(result.prop).isEqualTo("else");
assertThat(result.inner.prop).isEqualTo("something");
assertThat(result.inner.name).isEqualTo("new inner name");
assertThat(result.inner).isSameAs(inner);
}
@Test // DATAREST-937
void considersTransientProperties() throws Exception {
SampleWithTransient sample = new SampleWithTransient();
sample.name = "name";
sample.temporary = "temp";
JsonNode node = new ObjectMapper().readTree("{ \"name\" : \"new name\", \"temporary\" : \"new temp\" }");
SampleWithTransient result = reader.readPut((ObjectNode) node, sample, new ObjectMapper());
assertThat(result.name).isEqualTo("new name");
assertThat(result.temporary).isEqualTo("new temp");
}
@Test // DATAREST-953
void writesArrayForPut() throws Exception {
Child inner = new Child();
inner.items = new ArrayList<Item>();
inner.items.add(new Item());
Parent source = new Parent();
source.inner = inner;
JsonNode node = new ObjectMapper().readTree("{ \"inner\" : { \"items\" : [ { \"some\" : \"value\" } ] } }");
Parent result = reader.readPut((ObjectNode) node, source, new ObjectMapper());
assertThat(result.inner.items.get(0).some).isEqualTo("value");
}
@Test // DATAREST-956
void writesArrayWithAddedItemForPut() throws Exception {
Child inner = new Child();
inner.items = new ArrayList<Item>();
inner.items.add(new Item());
Parent source = new Parent();
source.inner = inner;
JsonNode node = new ObjectMapper().readTree("{ \"inner\" : { \"items\" : [ " + "{ \"some\" : \"value1\" },"
+ "{ \"some\" : \"value2\" }," + "{ \"some\" : \"value3\" } ] } }");
Parent result = reader.readPut((ObjectNode) node, source, new ObjectMapper());
assertThat(result.inner.items).hasSize(3);
assertThat(result.inner.items.get(0).some).isEqualTo("value1");
assertThat(result.inner.items.get(1).some).isEqualTo("value2");
assertThat(result.inner.items.get(2).some).isEqualTo("value3");
}
@Test // DATAREST-956
void writesArrayWithRemovedItemForPut() throws Exception {
Child inner = new Child();
inner.items = new ArrayList<Item>();
inner.items.add(new Item("test1"));
inner.items.add(new Item("test2"));
inner.items.add(new Item("test3"));
Parent source = new Parent();
source.inner = inner;
JsonNode node = new ObjectMapper().readTree("{ \"inner\" : { \"items\" : [ { \"some\" : \"value\" } ] } }");
Parent result = reader.readPut((ObjectNode) node, source, new ObjectMapper());
assertThat(result.inner.items).hasSize(1);
assertThat(result.inner.items.get(0).some).isEqualTo("value");
}
@Test // DATAREST-959
void addsElementToPreviouslyEmptyCollection() throws Exception {
Parent source = new Parent();
source.inner = new Child();
source.inner.items = null;
JsonNode node = new ObjectMapper().readTree("{ \"inner\" : { \"items\" : [ { \"some\" : \"value\" } ] } }");
Parent result = reader.readPut((ObjectNode) node, source, new ObjectMapper());
assertThat(result.inner.items).hasSize(1);
assertThat(result.inner.items.get(0).some).isEqualTo("value");
}
@Test // DATAREST-959
@SuppressWarnings("unchecked")
void turnsObjectIntoCollection() throws Exception {
Parent source = new Parent();
source.inner = new Child();
source.inner.object = new Item("value");
JsonNode node = new ObjectMapper()
.readTree("{ \"inner\" : { \"object\" : [ { \"some\" : \"value\" }, { \"some\" : \"otherValue\" } ] } }");
Parent result = reader.readPut((ObjectNode) node, source, new ObjectMapper());
assertThat(result.inner.object).isInstanceOf(Collection.class);
Collection<?> collection = (Collection<?>) result.inner.object;
assertThat(collection).hasSize(2);
Iterator<Map<String, Object>> iterator = (Iterator<Map<String, Object>>) collection.iterator();
assertThat(iterator.next().get("some")).isEqualTo("value");
assertThat(iterator.next().get("some")).isEqualTo("otherValue");
}
@Test // DATAREST-965
void writesObjectWithRemovedItemsForPut() throws Exception {
Child inner = new Child();
inner.items = new ArrayList<Item>();
inner.items.add(new Item("test1"));
inner.items.add(new Item("test2"));
Parent source = new Parent();
source.inner = inner;
JsonNode node = new ObjectMapper().readTree("{ \"inner\" : { \"object\" : \"value\" } }");
Parent result = reader.readPut((ObjectNode) node, source, new ObjectMapper());
assertThat(result.inner.items).isNull();
assertThat((String) result.inner.object).isEqualTo("value");
}
@Test // DATAREST-965
void writesArrayWithRemovedObjectForPut() throws Exception {
Child inner = new Child();
inner.object = "value";
Parent source = new Parent();
source.inner = inner;
JsonNode node = new ObjectMapper().readTree("{ \"inner\" : { \"items\" : [ { \"some\" : \"value\" } ] } }");
Parent result = reader.readPut((ObjectNode) node, source, new ObjectMapper());
assertThat(result.inner.items).hasSize(1);
assertThat(result.inner.items.get(0).some).isEqualTo("value");
assertThat(result.inner.object).isNull();
}
@Test // DATAREST-986
void readsComplexMap() throws Exception {
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(
"{ \"map\" : { \"en\" : { \"value\" : \"eventual\" }, \"de\" : { \"value\" : \"schlussendlich\" } } }");
Product result = reader.readPut((ObjectNode) node, new Product(), mapper);
assertThat(result.map.get(Locale.ENGLISH)).isEqualTo(new LocalizedValue("eventual"));
assertThat(result.map.get(Locale.GERMAN)).isEqualTo(new LocalizedValue("schlussendlich"));
}
@Test // DATAREST-987
void handlesTransientPropertyWithoutFieldProperly() throws Exception {
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree("{ \"name\" : \"Foo\" }");
reader.readPut((ObjectNode) node, new TransientReadOnlyProperty(), mapper);
}
@Test // DATAREST-977
void readsCollectionOfComplexEnum() throws Exception {
CollectionOfEnumWithMethods sample = new CollectionOfEnumWithMethods();
sample.enums.add(SampleEnum.FIRST);
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree("{ \"enums\" : [ \"SECOND\", \"FIRST\" ] }");
@SuppressWarnings("deprecation")
CollectionOfEnumWithMethods result = reader.merge((ObjectNode) node, sample, mapper);
assertThat(result.enums).containsExactly(SampleEnum.SECOND, SampleEnum.FIRST);
}
@Test // DATAREST-944
void mergesAssociations() {
List<Nested> originalCollection = Arrays.asList(new Nested(2, 3));
SampleWithReference source = new SampleWithReference(Arrays.asList(new Nested(1, 2), new Nested(2, 3)));
SampleWithReference target = new SampleWithReference(originalCollection);
SampleWithReference result = reader.mergeForPut(source, target, new ObjectMapper());
assertThat(result.nested).isEqualTo(source.nested);
assertThat(result.nested == originalCollection).isFalse();
}
@Test // DATAREST-944
void mergesAssociationsAndKeepsMutableCollection() {
ArrayList<Nested> originalCollection = new ArrayList<Nested>(Arrays.asList(new Nested(2, 3)));
SampleWithReference source = new SampleWithReference(
new ArrayList<Nested>(Arrays.asList(new Nested(1, 2), new Nested(2, 3))));
SampleWithReference target = new SampleWithReference(originalCollection);
SampleWithReference result = reader.mergeForPut(source, target, new ObjectMapper());
assertThat(result.nested).isEqualTo(source.nested);
assertThat(result.nested).isSameAs(originalCollection);
}
@Test // DATAREST-1030
void patchWithReferenceToRelatedEntityIsResolvedCorrectly() throws Exception {
Associations associations = mock(Associations.class);
PersistentProperty<?> any = ArgumentMatchers.any(PersistentProperty.class);
when(associations.isLinkableAssociation(any)).thenReturn(true);
DomainObjectReader reader = new DomainObjectReader(entities, associations);
Tag first = new Tag();
Tag second = new Tag();
Note note = new Note();
note.tags.add(first);
note.tags.add(second);
SimpleModule module = new SimpleModule();
module.addDeserializer(Tag.class, new SelectValueByIdSerializer<Tag>(Collections.singletonMap(second.id, second)));
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(module);
ObjectNode readTree = (ObjectNode) mapper.readTree(String.format("{ \"tags\" : [ \"%s\"]}", second.id));
Note result = reader.doMerge(readTree, note, mapper);
assertThat(result.tags).contains(second);
}
@Test // DATAREST-1249
void mergesIntoUninitializedCollection() throws Exception {
ObjectMapper mapper = new ObjectMapper();
ObjectNode source = (ObjectNode) mapper.readTree("{ \"strings\" : [ \"value\" ] }");
WithNullCollection result = reader.readPut(source, new WithNullCollection(), mapper);
assertThat(result.strings).containsExactly("value");
}
@Test // DATAREST-1383
void doesNotWipeReadOnlyPropertyForPatch() throws Exception {
SampleUser user = new SampleUser("name", "password");
user.lastLogin = new Date();
user.email = "foo@bar.com";
ObjectMapper mapper = new ObjectMapper();
ObjectNode source = (ObjectNode) mapper.readTree("{ \"lastLogin\" : null, \"email\" : \"bar@foo.com\"}");
@SuppressWarnings("deprecation")
SampleUser result = reader.merge(source, user, mapper);
assertThat(result.lastLogin).isNotNull();
assertThat(result.email).isEqualTo("foo@bar.com");
}
@Test // DATAREST-1068
void arraysCanBeResizedDuringMerge() throws Exception {
ObjectMapper mapper = new ObjectMapper();
ArrayHolder target = new ArrayHolder(new String[] {});
JsonNode node = mapper.readTree("{ \"array\" : [ \"new\" ] }");
ArrayHolder updated = reader.doMerge((ObjectNode) node, target, mapper);
assertThat(updated.array).containsExactly("new");
}
@Test // #2130
void writesPolymorphicArrayWithSwitchedItemForPut() throws Exception {
Apple apple = new Apple();
apple.apple = "apple";
apple.color = "red";
apple.ignored = "ignored";
Pear pear = new Pear();
pear.pear = "pear";
Fruit result = reader.mergeForPut(pear, apple, new ObjectMapper());
assertThat(result).isInstanceOfSatisfying(Pear.class, it -> {
// Exposed property is wiped as expected for PUT
assertThat(it.color).isNull();
// Non-exposed state is transferred
assertThat(it.ignored).isEqualTo("ignored");
// Type specific state applied, too
assertThat(it.pear).isEqualTo("pear");
});
}
@SuppressWarnings("unchecked")
private static <T> T as(Object source, Class<T> type) {
assertThat(source).isInstanceOf(type);
return (T) source;
}
@JsonAutoDetect(fieldVisibility = Visibility.ANY)
static class SampleUser {
String name;
@JsonIgnore String password;
Map<String, SampleUser> relatedUsers;
@JsonProperty(access = READ_ONLY) //
private Date lastLogin;
@ReadOnlyProperty //
private String email;
public SampleUser(String name, String password) {
this.name = name;
this.password = password;
}
protected SampleUser() {}
}
// DATAREST-556
@JsonAutoDetect(fieldVisibility = Visibility.ANY)
static class Person {
String firstName, lastName;
public Person(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
protected Person() {}
}
@JsonAutoDetect(fieldVisibility = Visibility.ANY)
static class TypeWithGenericMap {
Map<String, Object> map;
}
@JsonAutoDetect(fieldVisibility = Visibility.ANY)
static class VersionedType {
@Id Long id;
@Version Long version;
String firstname, lastname;
}
@JsonAutoDetect(fieldVisibility = Visibility.ANY)
static class SampleWithCreatedDate {
@CreatedDate //
@ReadOnlyProperty //
Date createdDate;
}
static class User {
public List<Phone> phones = new ArrayList<Phone>();
}
static class Phone {
public Calendar creationDate;
public String label;
}
@JsonAutoDetect(fieldVisibility = Visibility.ANY)
static class SampleWithTransient {
String name;
@Transient String temporary;
}
@JsonAutoDetect(fieldVisibility = Visibility.ANY)
static class Outer {
String name;
String prop;
Inner inner;
}
@JsonAutoDetect(fieldVisibility = Visibility.ANY)
static class Inner {
String name;
String prop;
}
@JsonAutoDetect(fieldVisibility = Visibility.ANY)
static class Parent {
Child inner;
}
@JsonAutoDetect(fieldVisibility = Visibility.ANY)
static class Child {
List<Item> items;
Object object;
}
@JsonAutoDetect(fieldVisibility = Visibility.ANY)
@NoArgsConstructor
@AllArgsConstructor
static class Item {
String some;
}
@JsonAutoDetect(fieldVisibility = Visibility.ANY)
static class Product {
Map<Locale, LocalizedValue> map = new HashMap<Locale, LocalizedValue>();
}
@JsonAutoDetect(fieldVisibility = Visibility.ANY)
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode
static class LocalizedValue {
String value;
}
@JsonAutoDetect(getterVisibility = Visibility.ANY)
static class TransientReadOnlyProperty {
@Transient
public String getName() {
return null;
}
void setName(String name) {}
}
// DATAREST-977
interface EnumInterface {
String getFoo();
}
static enum SampleEnum implements EnumInterface {
FIRST {
@Override
public String getFoo() {
return "first";
}
},
SECOND {
public String getFoo() {
return "second";
}
};
}
@JsonAutoDetect(fieldVisibility = Visibility.ANY)
static class CollectionOfEnumWithMethods {
List<SampleEnum> enums = new ArrayList<SampleEnum>();
}
@EqualsAndHashCode
@AllArgsConstructor
static class SampleWithReference {
private @Getter @Reference List<Nested> nested;
}
@Immutable
@Value
static class Nested {
int x, y;
}
// DATAREST-1030
@JsonAutoDetect(fieldVisibility = Visibility.ANY)
static class Note {
@Id UUID id = UUID.randomUUID();
@Reference List<Tag> tags = new ArrayList<Tag>();
}
@JsonAutoDetect(fieldVisibility = Visibility.ANY)
static class Tag {
@Id UUID id = UUID.randomUUID();
String name;
}
@RequiredArgsConstructor
static class SelectValueByIdSerializer<T> extends JsonDeserializer<T> {
private final Map<? extends Object, T> values;
@Override
public T deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
String text = p.getText();
return values.entrySet().stream()//
.filter(it -> it.getKey().toString().equals(text))//
.map(it -> it.getValue())//
.findFirst().orElse(null);
}
}
// DATAREST-1249
@JsonAutoDetect(fieldVisibility = Visibility.ANY)
static class WithNullCollection {
List<String> strings;
}
// DATAREST-1068
@Value
static class ArrayHolder {
String[] array;
}
// DATAREST-1026
@JsonAutoDetect(fieldVisibility = Visibility.ANY)
static class Basket {
@Id Long id;
List<Fruit> fruits;
}
@JsonAutoDetect(fieldVisibility = Visibility.ANY)
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = As.PROPERTY, property = "type")
@JsonSubTypes({ @JsonSubTypes.Type(name = "Apple", value = Apple.class),
@JsonSubTypes.Type(name = "Pear", value = Pear.class) })
static class Fruit {
String color;
@JsonIgnore String ignored;
}
@JsonAutoDetect(fieldVisibility = Visibility.ANY)
static class Apple extends Fruit {
String apple;
}
@JsonAutoDetect(fieldVisibility = Visibility.ANY)
static class Pear extends Fruit {
String pear;
}
}