-
Notifications
You must be signed in to change notification settings - Fork 149
/
Converter.java
388 lines (333 loc) · 13.3 KB
/
Converter.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
/**
* Copyright 2014-2023 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
*
* http://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 net.kaczmarzyk.spring.data.jpa.utils;
import net.kaczmarzyk.spring.data.jpa.web.annotation.OnTypeMismatch;
import org.springframework.core.convert.ConversionService;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.format.DateTimeParseException;
import java.time.format.ResolverStyle;
import java.time.temporal.ChronoField;
import java.util.*;
import java.util.function.BiFunction;
import static java.util.Objects.nonNull;
/**
* @author Tomasz Kaczmarzyk
*/
@SuppressWarnings("unchecked")
public final class Converter {
public static class ValuesRejectedException extends IllegalArgumentException {
private static final long serialVersionUID = 1L;
private Collection<String> rejectedValues;
public ValuesRejectedException(Collection<String> rejectedValues, String message) {
super(message);
this.rejectedValues = rejectedValues;
}
public Collection<String> getRejectedValues() {
return rejectedValues;
}
@Override
public String toString() {
return this.getClass() + ": " + getMessage();
}
}
public static class ValueRejectedException extends IllegalArgumentException {
private static final long serialVersionUID = 1L;
private String rejectedValue;
public ValueRejectedException(String rejectedValue, String message) {
this(rejectedValue, message, null);
}
public ValueRejectedException(String rejectedValue, String message, Exception cause) {
super(message, cause);
this.rejectedValue = rejectedValue;
}
public String getRejectedValue() {
return rejectedValue;
}
@Override
public String toString() {
return this.getClass().getSimpleName() + ": " + getMessage();
}
}
private static Map<Class<?>, String> DEFAULT_DATE_FORMATS = new HashMap<>();
static {
DEFAULT_DATE_FORMATS.put(Date.class, "yyyy-MM-dd");
DEFAULT_DATE_FORMATS.put(LocalDate.class, "yyyy-MM-dd");
DEFAULT_DATE_FORMATS.put(LocalDateTime.class, "yyyy-MM-dd\'T\'HH:mm:ss");
DEFAULT_DATE_FORMATS.put(OffsetDateTime.class, "yyyy-MM-dd\'T\'HH:mm:ss.SSSXXX");
DEFAULT_DATE_FORMATS.put(Instant.class, "yyyy-MM-dd\'T\'HH:mm:ss.SSSXXX");
DEFAULT_DATE_FORMATS.put(Timestamp.class, "yyyy-MM-dd\'T\'HH:mm:ss.SSS\'Z\'");
}
private static BiFunction<Enum<?>, String, Boolean> enumMatcherCaseSensitive = (enumVal, rawValue) -> enumVal.name().equals(rawValue);
private BiFunction<Enum<?>, String, Boolean> enumMatcherCaseInsensitive;
private String dateFormat;
private OnTypeMismatch onTypeMismatch;
private ConversionService conversionService;
private Converter(String dateFormat, OnTypeMismatch onTypeMismatch, ConversionService conversionService, Locale locale) {
this.dateFormat = dateFormat;
this.onTypeMismatch = onTypeMismatch;
this.conversionService = conversionService;
this.enumMatcherCaseInsensitive = (enumVal, rawValue) -> enumVal.name().toUpperCase(locale).equals(rawValue.toUpperCase(locale));
}
public <T> List<T> convert(List<String> values, Class<T> expectedClass) {
if (expectedClass == String.class) {
return (List<T>) values;
}
List<String> rejected = null;
List<T> result = new ArrayList<>();
for (String value : values) {
try {
result.add(convert(value, expectedClass));
} catch (ValueRejectedException e) {
if (rejected == null) {
rejected = new ArrayList<>();
}
rejected.add(e.getRejectedValue());
}
}
onTypeMismatch.handleRejectedValues(rejected);
return result;
}
public <T> T convert(String value, Class<T> expectedClass) {
return convert(value, expectedClass, false);
}
public <T> T convert(String value, Class<T> expectedClass, boolean ignoreCase) {
if (expectedClass.isEnum()) {
return (T) convertToEnum(value, (Class<? extends Enum<?>>) expectedClass, ignoreCase);
} else if (expectedClass.isAssignableFrom(Date.class)) {
return (T) convertToDate(value);
} else if (expectedClass.isAssignableFrom(Calendar.class)) {
return (T) convertToCalendar(value);
} else if (isAssignableFromAnyOf(expectedClass, Boolean.class, boolean.class)) {
return (T) convertToBoolean(value);
} else if (isAssignableFromAnyOf(expectedClass, Integer.class, int.class, Long.class, long.class)) {
return (T) convertToLong(value);
} else if (isAssignableFromAnyOf(expectedClass, float.class, Float.class)) {
return (T) convertToFloat(value);
} else if (isAssignableFromAnyOf(expectedClass, double.class, Double.class)) {
return (T) convertToDouble(value);
} else if (isAssignableFromAnyOf(expectedClass, char.class, Character.class)) {
return (T) convertToChar(value, ignoreCase);
} else if (expectedClass.isAssignableFrom(LocalDateTime.class)) {
return (T) convertToLocalDateTime(value);
} else if (expectedClass.isAssignableFrom(LocalDate.class)) {
return (T) convertToLocalDate(value);
} else if (expectedClass.isAssignableFrom(BigDecimal.class)) {
return (T) convertToBigDecimal(value);
} else if (expectedClass.isAssignableFrom(UUID.class)) {
return (T) convertToUUID(value);
} else if (expectedClass.isAssignableFrom(OffsetDateTime.class)) {
return (T) convertToOffsetDateTime(value);
} else if (expectedClass.isAssignableFrom(Instant.class)) {
return (T) convertToInstant(value);
} else if (expectedClass.isAssignableFrom(Timestamp.class)) {
return (T) convertToTimestamp(value);
} else if (nonNull(conversionService) && conversionService.canConvert(String.class, expectedClass)) {
return conversionService.convert(value, expectedClass);
}
return (T) value;
}
private boolean isAssignableFromAnyOf(Class<?> expectedClass, Class<?>... candidates) {
for (Class<?> candidate : candidates) {
if (expectedClass.isAssignableFrom(candidate)) {
return true;
}
}
return false;
}
private LocalDate convertToLocalDate(String value) {
String dateFormat = getDateFormat(LocalDate.class);
try {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(dateFormat);
return LocalDate.parse(value, formatter);
} catch (DateTimeParseException | IllegalArgumentException e) {
throw new ValueRejectedException(value, "LocalDate format exception, expected format: " + dateFormat, e);
}
}
private LocalDateTime convertToLocalDateTime(String value) {
String dateFormat = getDateFormat(LocalDateTime.class);
try {
DateTimeFormatter formatter = formatterWithDefaultTime(dateFormat);
return LocalDateTime.parse(value, formatter);
} catch (DateTimeParseException | IllegalArgumentException e) {
throw new ValueRejectedException(value, "LocalDateTime format exception, expected format: " + dateFormat, e);
}
}
private Long convertToLong(String value) {
try {
return Long.valueOf(value);
} catch (NumberFormatException e) {
throw new ValueRejectedException(value, "number format exception", e);
}
}
private Double convertToDouble(String value) {
try {
return Double.valueOf(value);
} catch (NumberFormatException e) {
throw new ValueRejectedException(value, "number format exception", e);
}
}
private Character convertToChar(String value, boolean ignoreCase) {
if (value.length() == 1) {
return ignoreCase ? Character.toUpperCase(value.charAt(0)) : value.charAt(0);
} else {
throw new ValueRejectedException(value, "value is not a single character exception");
}
}
private Float convertToFloat(String value) {
try {
return Float.valueOf(value);
} catch (NumberFormatException e) {
throw new ValueRejectedException(value, "number format exception", e);
}
}
private BigDecimal convertToBigDecimal(String value) {
try {
return new BigDecimal(value);
} catch (NumberFormatException e) {
throw new ValueRejectedException(value, "number format exception", e);
}
}
private Boolean convertToBoolean(String value) {
if ("true".equals(value)) {
return true;
} else if ("false".equals(value)) {
return false;
} else {
throw new ValueRejectedException(value, "unparseable boolean");
}
}
public Date convertToDate(String value) {
String dateFormat = getDateFormat(Date.class);
try {
validateDateFormat(dateFormat, value);
return new SimpleDateFormat(dateFormat).parse(value);
} catch (ParseException | DateTimeParseException e) {
throw new ValueRejectedException(value, "Date format exception, expected format: " + dateFormat, e);
}
}
public Calendar convertToCalendar(String value) {
String dateFormat = getDateFormat(Date.class);
try {
validateDateFormat(dateFormat, value);
Calendar cal = Calendar.getInstance();
cal.setTime(new SimpleDateFormat(dateFormat).parse(value));
return cal;
} catch (ParseException | DateTimeParseException e) {
throw new ValueRejectedException(value, "Date format exception, expected format: " + dateFormat, e);
}
}
public String getDateFormat(Class<?> clazz) {
if (dateFormat == null) {
return DEFAULT_DATE_FORMATS.get(clazz);
}
return dateFormat;
}
public UUID convertToUUID(String value) {
try {
return UUID.fromString(value);
} catch (IllegalArgumentException e) {
throw new ValueRejectedException(value, "unparseable uuid", e);
}
}
public OffsetDateTime convertToOffsetDateTime(String value) {
String dateFormat = getDateFormat(OffsetDateTime.class);
try {
DateTimeFormatter formatter = formatterWithDefaultTime(dateFormat);
return OffsetDateTime.parse(value, formatter);
} catch (DateTimeParseException | IllegalArgumentException e) {
throw new ValueRejectedException(value, "OffsetDateTime format exception, expected format: " + dateFormat, e);
}
}
public Instant convertToInstant(String value) {
String dateFormat = getDateFormat(Instant.class);
try {
return Instant.from(formatterWithDefaultTime(dateFormat).parse(value));
} catch (DateTimeParseException | IllegalArgumentException e) {
throw new ValueRejectedException(value, "Instant format exception, expected format: " + dateFormat, e);
}
}
private <T> T convertToEnum(String value, Class<? extends Enum<?>> enumClass, Boolean ignoreCase) {
BiFunction<Enum<?>, String, Boolean> enumMatcher = ignoreCase ? enumMatcherCaseInsensitive : enumMatcherCaseSensitive;
for (Enum<?> enumVal : enumClass.getEnumConstants()) {
if (enumMatcher.apply(enumVal, value)) {
return (T) enumVal;
}
}
throw new ValueRejectedException(value, "could not find value " + value + " for enum class " + enumClass.getSimpleName());
}
private Timestamp convertToTimestamp(String value) {
String dateFormat = getDateFormat(Timestamp.class);
try {
validateDateFormat(dateFormat, value);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat);
Date parsedDate = simpleDateFormat.parse(value);
return new Timestamp(parsedDate.getTime());
} catch (Exception e) {
throw new ValueRejectedException(value, "Timestamp format exception, expected format: " + dateFormat, e);
}
}
private void validateDateFormat(String expectedDateFormatPattern, String date) throws DateTimeParseException {
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern(expectedDateFormatPattern)
.withResolverStyle(ResolverStyle.STRICT);
dateFormatter.parse(date);
}
private DateTimeFormatter formatterWithDefaultTime(String dateFormat) {
return new DateTimeFormatterBuilder()
.appendPattern(dateFormat)
.parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
.parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
.parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
.parseDefaulting(ChronoField.NANO_OF_SECOND, 0)
.parseDefaulting(ChronoField.OFFSET_SECONDS, 0)
.toFormatter();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((dateFormat == null) ? 0 : dateFormat.hashCode());
result = prime * result + ((onTypeMismatch == null) ? 0 : onTypeMismatch.hashCode());
return result;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Converter converter = (Converter) o;
return Objects.equals(dateFormat, converter.dateFormat) &&
onTypeMismatch == converter.onTypeMismatch;
}
@Override
public String toString() {
return "Converter [dateFormat=" + dateFormat + ", onTypeMismatch=" + onTypeMismatch + "]";
}
public static Converter withDateFormat(String dateFormat, OnTypeMismatch onTypeMismatch, ConversionService conversionService) {
return new Converter(dateFormat, onTypeMismatch, conversionService, Locale.getDefault());
}
public static Converter withTypeMismatchBehaviour(OnTypeMismatch onTypeMismatch, ConversionService conversionService, Locale locale) {
return new Converter(null, onTypeMismatch, conversionService, locale);
}
}