forked from spring-projects/spring-data-commons
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCustomConversions.java
618 lines (496 loc) · 21.2 KB
/
CustomConversions.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
/*
* Copyright 2011-2019 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.convert;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.Value;
import lombok.extern.slf4j.Slf4j;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import org.springframework.core.GenericTypeResolver;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.core.convert.converter.ConverterRegistry;
import org.springframework.core.convert.converter.GenericConverter;
import org.springframework.core.convert.converter.GenericConverter.ConvertiblePair;
import org.springframework.core.convert.support.GenericConversionService;
import org.springframework.data.convert.ConverterBuilder.ConverterAware;
import org.springframework.data.mapping.model.SimpleTypeHolder;
import org.springframework.data.util.Streamable;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
/**
* Value object to capture custom conversion. That is essentially a {@link List} of converters and some additional logic
* around them. The converters build up two sets of types which store-specific basic types can be converted into and
* from. These types will be considered simple ones (which means they neither need deeper inspection nor nested
* conversion. Thus the {@link CustomConversions} also act as factory for {@link SimpleTypeHolder} .
*
* @author Oliver Gierke
* @author Thomas Darimont
* @author Christoph Strobl
* @author Mark Paluch
* @since 2.0
*/
@Slf4j
public class CustomConversions {
private static final String READ_CONVERTER_NOT_SIMPLE = "Registering converter from %s to %s as reading converter although it doesn't convert from a store-supported type! You might wanna check you annotation setup at the converter implementation.";
private static final String WRITE_CONVERTER_NOT_SIMPLE = "Registering converter from %s to %s as writing converter although it doesn't convert to a store-supported type! You might wanna check you annotation setup at the converter implementation.";
private static final String NOT_A_CONVERTER = "Converter %s is neither a Spring Converter, GenericConverter or ConverterFactory!";
private static final List<Object> DEFAULT_CONVERTERS;
static {
List<Object> defaults = new ArrayList<>();
defaults.addAll(JodaTimeConverters.getConvertersToRegister());
defaults.addAll(Jsr310Converters.getConvertersToRegister());
defaults.addAll(ThreeTenBackPortConverters.getConvertersToRegister());
DEFAULT_CONVERTERS = Collections.unmodifiableList(defaults);
}
private final SimpleTypeHolder simpleTypeHolder;
private final List<Object> converters;
private final Set<ConvertiblePair> readingPairs = new LinkedHashSet<>();
private final Set<ConvertiblePair> writingPairs = new LinkedHashSet<>();
private final Set<Class<?>> customSimpleTypes = new HashSet<>();
private final ConversionTargetsCache customReadTargetTypes = new ConversionTargetsCache();
private final ConversionTargetsCache customWriteTargetTypes = new ConversionTargetsCache();
private final Function<ConvertiblePair, Class<?>> getReadTarget = convertiblePair -> getCustomTarget(
convertiblePair.getSourceType(), convertiblePair.getTargetType(), readingPairs);
private Function<ConvertiblePair, Class<?>> getWriteTarget = convertiblePair -> getCustomTarget(
convertiblePair.getSourceType(), convertiblePair.getTargetType(), writingPairs);
private Function<ConvertiblePair, Class<?>> getRawWriteTarget = convertiblePair -> getCustomTarget(
convertiblePair.getSourceType(), null, writingPairs);
/**
* Creates a new {@link CustomConversions} instance registering the given converters.
*
* @param storeConversions must not be {@literal null}.
* @param converters must not be {@literal null}.
*/
public CustomConversions(StoreConversions storeConversions, Collection<?> converters) {
Assert.notNull(storeConversions, "StoreConversions must not be null!");
Assert.notNull(converters, "List of converters must not be null!");
List<Object> toRegister = new ArrayList<>();
// Add user provided converters to make sure they can override the defaults
toRegister.addAll(converters);
toRegister.addAll(storeConversions.getStoreConverters());
toRegister.addAll(DEFAULT_CONVERTERS);
toRegister.stream()//
.flatMap(it -> storeConversions.getRegistrationsFor(it).stream())//
.forEach(this::register);
Collections.reverse(toRegister);
this.converters = Collections.unmodifiableList(toRegister);
this.simpleTypeHolder = new SimpleTypeHolder(customSimpleTypes, storeConversions.getStoreTypeHolder());
}
/**
* Returns the underlying {@link SimpleTypeHolder}.
*
* @return
*/
public SimpleTypeHolder getSimpleTypeHolder() {
return simpleTypeHolder;
}
/**
* Returns whether the given type is considered to be simple. That means it's either a general simple type or we have
* a writing {@link Converter} registered for a particular type.
*
* @see SimpleTypeHolder#isSimpleType(Class)
* @param type
* @return
*/
public boolean isSimpleType(Class<?> type) {
Assert.notNull(type, "Type must not be null!");
return simpleTypeHolder.isSimpleType(type);
}
/**
* Populates the given {@link GenericConversionService} with the converters registered.
*
* @param conversionService
*/
public void registerConvertersIn(ConverterRegistry conversionService) {
Assert.notNull(conversionService, "ConversionService must not be null!");
converters.forEach(it -> registerConverterIn(it, conversionService));
}
/**
* Registers the given converter in the given {@link GenericConversionService}.
*
* @param candidate must not be {@literal null}.
* @param conversionService must not be {@literal null}.
*/
private void registerConverterIn(Object candidate, ConverterRegistry conversionService) {
boolean added = false;
if (candidate instanceof Converter) {
conversionService.addConverter(Converter.class.cast(candidate));
added = true;
}
if (candidate instanceof ConverterFactory) {
conversionService.addConverterFactory(ConverterFactory.class.cast(candidate));
added = true;
}
if (candidate instanceof GenericConverter) {
conversionService.addConverter(GenericConverter.class.cast(candidate));
added = true;
}
if (candidate instanceof ConverterAware) {
ConverterAware.class.cast(candidate).getConverters().forEach(it -> registerConverterIn(it, conversionService));
added = true;
}
if (!added) {
throw new IllegalArgumentException(String.format(NOT_A_CONVERTER, candidate));
}
}
/**
* Registers the given {@link ConvertiblePair} as reading or writing pair depending on the type sides being basic
* Mongo types.
*
* @param converterRegistration
*/
private void register(ConverterRegistration converterRegistration) {
Assert.notNull(converterRegistration, "Converter registration must not be null!");
ConvertiblePair pair = converterRegistration.getConvertiblePair();
if (converterRegistration.isReading()) {
readingPairs.add(pair);
if (LOG.isWarnEnabled() && !converterRegistration.isSimpleSourceType()) {
LOG.warn(String.format(READ_CONVERTER_NOT_SIMPLE, pair.getSourceType(), pair.getTargetType()));
}
}
if (converterRegistration.isWriting()) {
writingPairs.add(pair);
customSimpleTypes.add(pair.getSourceType());
if (LOG.isWarnEnabled() && !converterRegistration.isSimpleTargetType()) {
LOG.warn(String.format(WRITE_CONVERTER_NOT_SIMPLE, pair.getSourceType(), pair.getTargetType()));
}
}
}
/**
* Returns the target type to convert to in case we have a custom conversion registered to convert the given source
* type into a Mongo native one.
*
* @param sourceType must not be {@literal null}
* @return
*/
public Optional<Class<?>> getCustomWriteTarget(Class<?> sourceType) {
Assert.notNull(sourceType, "Source type must not be null!");
Class<?> target = customWriteTargetTypes.computeIfAbsent(sourceType, getRawWriteTarget);
return Void.class.equals(target) || target == null ? Optional.empty() : Optional.of(target);
}
/**
* Returns the target type we can read an inject of the given source type to. The returned type might
* be a subclass of the given expected type though. If {@code requestedTargetType} is {@literal null} we will simply
* return the first target type matching or {@literal null} if no conversion can be found.
*
* @param sourceType must not be {@literal null}
* @param requestedTargetType must not be {@literal null}.
* @return
*/
public Optional<Class<?>> getCustomWriteTarget(Class<?> sourceType, Class<?> requestedTargetType) {
Assert.notNull(sourceType, "Source type must not be null!");
Assert.notNull(requestedTargetType, "Target type must not be null!");
Class<?> target = customWriteTargetTypes.computeIfAbsent(sourceType, requestedTargetType, getWriteTarget);
return Void.class.equals(target) || target == null ? Optional.empty() : Optional.of(target);
}
/**
* Returns whether we have a custom conversion registered to read {@code sourceType} into a native type. The
* returned type might be a subclass of the given expected type though.
*
* @param sourceType must not be {@literal null}
* @return
*/
public boolean hasCustomWriteTarget(Class<?> sourceType) {
Assert.notNull(sourceType, "Source type must not be null!");
return getCustomWriteTarget(sourceType).isPresent();
}
/**
* Returns whether we have a custom conversion registered to read an object of the given source type
* into an object of the given native target type.
*
* @param sourceType must not be {@literal null}.
* @param targetType must not be {@literal null}.
* @return
*/
public boolean hasCustomWriteTarget(Class<?> sourceType, Class<?> targetType) {
Assert.notNull(sourceType, "Source type must not be null!");
Assert.notNull(targetType, "Target type must not be null!");
return getCustomWriteTarget(sourceType, targetType).isPresent();
}
/**
* Returns whether we have a custom conversion registered to read the given source into the given target
* type.
*
* @param sourceType must not be {@literal null}
* @param targetType must not be {@literal null}
* @return
*/
public boolean hasCustomReadTarget(Class<?> sourceType, Class<?> targetType) {
Assert.notNull(sourceType, "Source type must not be null!");
Assert.notNull(targetType, "Target type must not be null!");
return getCustomReadTarget(sourceType, targetType) != null;
}
/**
* Returns the actual target type for the given {@code sourceType} and {@code targetType}. Note that the
* returned {@link Class} could be an assignable type to the given {@code targetType}.
*
* @param sourceType must not be {@literal null}.
* @param targetType must not be {@literal null}.
* @return
*/
@Nullable
private Class<?> getCustomReadTarget(Class<?> sourceType, Class<?> targetType) {
return customReadTargetTypes.computeIfAbsent(sourceType, targetType, getReadTarget);
}
/**
* Inspects the given {@link ConvertiblePair ConvertiblePairs} for ones that have a source compatible type as source. Additionally
* checks assignability of the target type if one is given.
*
* @param sourceType must not be {@literal null}.
* @param targetType can be {@literal null}.
* @param pairs must not be {@literal null}.
* @return
*/
@Nullable
private Class<?> getCustomTarget(Class<?> sourceType, @Nullable Class<?> targetType,
Collection<ConvertiblePair> pairs) {
if (targetType != null && pairs.contains(new ConvertiblePair(sourceType, targetType))) {
return targetType;
}
for (ConvertiblePair pair : pairs) {
if (!hasAssignableSourceType(pair, sourceType)) {
continue;
}
Class<?> candidate = pair.getTargetType();
if (!requestedTargetTypeIsAssignable(targetType, candidate)) {
continue;
}
return candidate;
}
return null;
}
private static boolean hasAssignableSourceType(ConvertiblePair pair, Class<?> sourceType) {
return pair.getSourceType().isAssignableFrom(sourceType);
}
private static boolean requestedTargetTypeIsAssignable(@Nullable Class<?> requestedTargetType, Class<?> targetType) {
return requestedTargetType == null ? true : targetType.isAssignableFrom(requestedTargetType);
}
/**
* Value object to cache custom conversion targets.
*
* @author Mark Paluch
*/
static class ConversionTargetsCache {
private final Map<Class<?>, TargetTypes> customReadTargetTypes = new ConcurrentHashMap<>();
/**
* Get or compute a target type given its {@code sourceType}. Returns a cached {@link Optional} if the value
* (present/absent target) was computed once. Otherwise, uses a {@link Function mappingFunction} to determine a
* possibly existing target type.
*
* @param sourceType must not be {@literal null}.
* @param mappingFunction must not be {@literal null}.
* @return the optional target type.
*/
@Nullable
public Class<?> computeIfAbsent(Class<?> sourceType, Function<ConvertiblePair, Class<?>> mappingFunction) {
return computeIfAbsent(sourceType, AbsentTargetTypeMarker.class, mappingFunction);
}
/**
* Get or compute a target type given its {@code sourceType} and {@code targetType}. Returns a cached
* {@link Optional} if the value (present/absent target) was computed once. Otherwise, uses a {@link Function
* mappingFunction} to determine a possibly existing target type.
*
* @param sourceType must not be {@literal null}.
* @param targetType must not be {@literal null}.
* @param mappingFunction must not be {@literal null}.
* @return the optional target type.
*/
@Nullable
public Class<?> computeIfAbsent(Class<?> sourceType, Class<?> targetType,
Function<ConvertiblePair, Class<?>> mappingFunction) {
TargetTypes targetTypes = customReadTargetTypes.get(sourceType);
if (targetTypes == null) {
targetTypes = customReadTargetTypes.computeIfAbsent(sourceType, TargetTypes::new);
}
return targetTypes.computeIfAbsent(targetType, mappingFunction);
}
/**
* Marker type for absent target type caching.
*/
interface AbsentTargetTypeMarker {}
}
/**
* Value object for a specific {@code Class source type} to determine possible target conversion types.
*
* @author Mark Paluch
*/
@RequiredArgsConstructor
static class TargetTypes {
private final @NonNull Class<?> sourceType;
private final Map<Class<?>, Class<?>> conversionTargets = new ConcurrentHashMap<>();
/**
* Get or compute a target type given its {@code targetType}. Returns a cached {@link Optional} if the value
* (present/absent target) was computed once. Otherwise, uses a {@link Function mappingFunction} to determine a
* possibly existing target type.
*
* @param targetType must not be {@literal null}.
* @param mappingFunction must not be {@literal null}.
* @return the optional target type.
*/
@Nullable
public Class<?> computeIfAbsent(Class<?> targetType, Function<ConvertiblePair, Class<?>> mappingFunction) {
Class<?> optionalTarget = conversionTargets.get(targetType);
if (optionalTarget == null) {
optionalTarget = mappingFunction.apply(new ConvertiblePair(sourceType, targetType));
conversionTargets.put(targetType, optionalTarget == null ? Void.class : optionalTarget);
}
return Void.class.equals(optionalTarget) ? null : optionalTarget;
}
}
/**
* Conversion registration information.
*
* @author Oliver Gierke
* @author Mark Paluch
*/
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
static class ConverterRegistration {
private final @NonNull ConvertiblePair convertiblePair;
private final @NonNull StoreConversions storeConversions;
private final boolean reading;
private final boolean writing;
/**
* Returns whether the converter shall be used for writing.
*
* @return
*/
public boolean isWriting() {
return writing == true || (!reading && isSimpleTargetType());
}
/**
* Returns whether the converter shall be used for reading.
*
* @return
*/
public boolean isReading() {
return reading == true || (!writing && isSimpleSourceType());
}
/**
* Returns the actual conversion pair.
*
* @return
*/
public ConvertiblePair getConvertiblePair() {
return convertiblePair;
}
/**
* Returns whether the source type is a Mongo simple one.
*
* @return
*/
public boolean isSimpleSourceType() {
return storeConversions.isStoreSimpleType(convertiblePair.getSourceType());
}
/**
* Returns whether the target type is a Mongo simple one.
*
* @return
*/
public boolean isSimpleTargetType() {
return storeConversions.isStoreSimpleType(convertiblePair.getTargetType());
}
}
/**
* Value type to capture store-specific extensions to the {@link CustomConversions}. Allows to forward store specific
* default conversions and a set of types that are supposed to be considered simple.
*
* @author Oliver Gierke
*/
@Value
@Getter(AccessLevel.PACKAGE)
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
public static class StoreConversions {
public static final StoreConversions NONE = StoreConversions.of(SimpleTypeHolder.DEFAULT, Collections.emptyList());
SimpleTypeHolder storeTypeHolder;
Collection<?> storeConverters;
/**
* Creates a new {@link StoreConversions} for the given store-specific {@link SimpleTypeHolder} and the given
* converters.
*
* @param storeTypeHolder must not be {@literal null}.
* @param converters must not be {@literal null}.
* @return
*/
public static StoreConversions of(SimpleTypeHolder storeTypeHolder, Object... converters) {
Assert.notNull(storeTypeHolder, "SimpleTypeHolder must not be null!");
Assert.notNull(converters, "Converters must not be null!");
return new StoreConversions(storeTypeHolder, Arrays.asList(converters));
}
/**
* Creates a new {@link StoreConversions} for the given store-specific {@link SimpleTypeHolder} and the given
* converters.
*
* @param storeTypeHolder must not be {@literal null}.
* @param converters must not be {@literal null}.
* @return
*/
public static StoreConversions of(SimpleTypeHolder storeTypeHolder, Collection<?> converters) {
Assert.notNull(storeTypeHolder, "SimpleTypeHolder must not be null!");
Assert.notNull(converters, "Converters must not be null!");
return new StoreConversions(storeTypeHolder, converters);
}
/**
* Returns {@link ConverterRegistration}s for the given converter.
*
* @param converter must not be {@literal null}.
* @return
*/
public Streamable<ConverterRegistration> getRegistrationsFor(Object converter) {
Assert.notNull(converter, "Converter must not be null!");
Class<?> type = converter.getClass();
boolean isWriting = type.isAnnotationPresent(WritingConverter.class);
boolean isReading = type.isAnnotationPresent(ReadingConverter.class);
if (converter instanceof ConverterAware) {
return Streamable.of(() -> ConverterAware.class.cast(converter).getConverters().stream()//
.flatMap(it -> getRegistrationsFor(it).stream()));
} else if (converter instanceof GenericConverter) {
Set<ConvertiblePair> convertibleTypes = GenericConverter.class.cast(converter).getConvertibleTypes();
return convertibleTypes == null //
? Streamable.empty() //
: Streamable.of(convertibleTypes).map(it -> register(it, isReading, isWriting));
} else if (converter instanceof ConverterFactory) {
return getRegistrationFor(converter, ConverterFactory.class, isReading, isWriting);
} else if (converter instanceof Converter) {
return getRegistrationFor(converter, Converter.class, isReading, isWriting);
} else {
throw new IllegalArgumentException(String.format("Unsupported converter type %s!", converter));
}
}
private Streamable<ConverterRegistration> getRegistrationFor(Object converter, Class<?> type, boolean isReading,
boolean isWriting) {
Class<? extends Object> converterType = converter.getClass();
Class<?>[] arguments = GenericTypeResolver.resolveTypeArguments(converterType, type);
if (arguments == null) {
throw new IllegalStateException(String.format("Couldn't resolve type arguments for %s!", converterType));
}
return Streamable.of(register(arguments[0], arguments[1], isReading, isWriting));
}
private ConverterRegistration register(Class<?> source, Class<?> target, boolean isReading, boolean isWriting) {
return register(new ConvertiblePair(source, target), isReading, isWriting);
}
private ConverterRegistration register(ConvertiblePair pair, boolean isReading, boolean isWriting) {
return new ConverterRegistration(pair, this, isReading, isWriting);
}
private boolean isStoreSimpleType(Class<?> type) {
return storeTypeHolder.isSimpleType(type);
}
}
}