|
11 | 11 |
|
12 | 12 | import org.elasticsearch.datageneration.FieldType; |
13 | 13 |
|
| 14 | +import java.math.BigDecimal; |
14 | 15 | import java.util.List; |
15 | 16 | import java.util.Map; |
16 | 17 | import java.util.Objects; |
@@ -48,21 +49,52 @@ protected Object expected(Map<String, Object> fieldMapping, Object value, TestCo |
48 | 49 | return maybeFoldList(resultList); |
49 | 50 | } |
50 | 51 |
|
51 | | - @SuppressWarnings("unchecked") |
52 | 52 | private T convert(Object value, T nullValue, Map<String, Object> fieldMapping) { |
53 | | - if (value == null) { |
54 | | - return nullValue; |
55 | | - } |
56 | | - // String coercion is true by default |
57 | | - if (value instanceof String s && s.isEmpty()) { |
58 | | - return nullValue; |
59 | | - } |
60 | | - if (value instanceof Number n) { |
61 | | - return convert(n, fieldMapping); |
| 53 | + switch (value) { |
| 54 | + case null -> { |
| 55 | + return nullValue; |
| 56 | + } |
| 57 | + |
| 58 | + // String coercion is true by default |
| 59 | + case String s -> { |
| 60 | + if (s.isEmpty()) { |
| 61 | + return nullValue; |
| 62 | + } |
| 63 | + // Attempt to parse the string as a number. If that fails, the string is malformed, so return null |
| 64 | + Number parsed = tryParseString(s); |
| 65 | + if (parsed != null) { |
| 66 | + return convert(parsed, fieldMapping); |
| 67 | + } |
| 68 | + return null; |
| 69 | + } |
| 70 | + |
| 71 | + case Number n -> { |
| 72 | + return convert(n, fieldMapping); |
| 73 | + } |
| 74 | + |
| 75 | + default -> { |
| 76 | + // Malformed values are excluded |
| 77 | + return null; |
| 78 | + } |
62 | 79 | } |
| 80 | + } |
63 | 81 |
|
64 | | - // Malformed values are excluded |
65 | | - return null; |
| 82 | + /** |
| 83 | + * Tries to parse a string as a number, matching the behavior of UnsignedLongFieldMapper.parseUnsignedLong(). |
| 84 | + * Returns null if the string cannot be parsed as a valid number. |
| 85 | + */ |
| 86 | + private Number tryParseString(String s) { |
| 87 | + try { |
| 88 | + return Long.parseUnsignedLong(s); |
| 89 | + } catch (NumberFormatException ex1) { |
| 90 | + try { |
| 91 | + BigDecimal bd = new BigDecimal(s); |
| 92 | + return bd.toBigIntegerExact(); |
| 93 | + } catch (NumberFormatException | ArithmeticException ex2) { |
| 94 | + // not a valid number |
| 95 | + return null; |
| 96 | + } |
| 97 | + } |
66 | 98 | } |
67 | 99 |
|
68 | 100 | protected abstract T convert(Number value, Map<String, Object> fieldMapping); |
|
0 commit comments