-
-
Notifications
You must be signed in to change notification settings - Fork 201
Expand file tree
/
Copy pathValue.java
More file actions
726 lines (669 loc) · 19.2 KB
/
Copy pathValue.java
File metadata and controls
726 lines (669 loc) · 19.2 KB
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
/*
* Jooby https://jooby.io
* Apache License Version 2.0 https://jooby.io/LICENSE.txt
* Copyright 2014 Edgar Espina
*/
package io.jooby.value;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeParseException;
import java.util.*;
import java.util.function.BiFunction;
import java.util.function.Function;
import org.jspecify.annotations.Nullable;
import io.jooby.Context;
import io.jooby.Formdata;
import io.jooby.SneakyThrows;
import io.jooby.exception.MissingValueException;
import io.jooby.exception.TypeMismatchException;
import io.jooby.internal.ArrayValue;
import io.jooby.internal.HashValue;
import io.jooby.internal.HeadersValue;
import io.jooby.internal.MissingValue;
import io.jooby.internal.MultipartNode;
import io.jooby.internal.SingleValue;
/**
* Unified API for HTTP value. This API plays two role:
*
* <p>- unify access to HTTP values, like query, path, form and header parameter - works as
* validation API, because it is able to check for required and type-safe values
*
* <p>The value API is composed by three types:
*
* <p>- Single value - Object value - Sequence of values (array)
*
* <p>Single value are can be converted to string, int, boolean, enum like values. Object value is a
* key:value structure (like a hash). Sequence of values are index based structure.
*
* <p>All these 3 types are modeled into a single Value class. At any time you can treat a value as
* 1) single, 2) hash or 3) array of them.
*
* @since 2.0.0
* @author edgar
*/
public interface Value extends Iterable<Value> {
/**
* Get a value at the given position.
*
* @param index Position.
* @return A value at the given position.
*/
Value get(int index);
/**
* Get a value that matches the given name.
*
* @param name Field name.
* @return Field value.
*/
Value get(String name);
/**
* Get a value that matches the given name or fallback back to default value.
*
* @param name Field name.
* @param defaultValue Default Value.
* @return Field value.
*/
Value getOrDefault(String name, String defaultValue);
/**
* The number of values this one has. For single values size is <code>0</code>.
*
* @return Number of values. Mainly for array and hash values.
*/
int size();
/**
* Value iterator.
*
* @return Value iterator.
*/
Iterator<Value> iterator();
/**
* Process the given expression and resolve value references.
*
* <pre>{@code
* Value value = Value.single("foo", "bar");
*
* String output = value.resolve("${foo}");
* System.out.println(output);
* }</pre>
*
* @param expression Text expression.
* @return Resolved text.
*/
default String resolve(String expression) {
return resolve(expression, "${", "}");
}
/**
* Process the given expression and resolve value references.
*
* <pre>{@code
* Value value = Value.single("foo", "bar");
*
* String output = value.resolve("${missing}", true);
* System.out.println(output);
* }</pre>
*
* @param expression Text expression.
* @param ignoreMissing On missing values, keep the expression as it is.
* @return Resolved text.
*/
default String resolve(String expression, boolean ignoreMissing) {
return resolve(expression, ignoreMissing, "${", "}");
}
/**
* Process the given expression and resolve value references.
*
* <pre>{@code
* Value value = Value.single("foo", "bar");
*
* String output = value.resolve("<%missing%>", "<%", "%>");
* System.out.println(output);
* }</pre>
*
* @param expression Text expression.
* @param startDelim Start delimiter.
* @param endDelim End delimiter.
* @return Resolved text.
*/
default String resolve(String expression, String startDelim, String endDelim) {
return resolve(expression, false, startDelim, endDelim);
}
/**
* Process the given expression and resolve value references.
*
* <pre>{@code
* Value value = Value.single("foo", "bar");
*
* String output = value.resolve("<%missing%>", "<%", "%>");
* System.out.println(output);
* }</pre>
*
* @param expression Text expression.
* @param ignoreMissing On missing values, keep the expression as it is.
* @param startDelim Start delimiter.
* @param endDelim End delimiter.
* @return Resolved text.
*/
default String resolve(
String expression, boolean ignoreMissing, String startDelim, String endDelim) {
if (expression.isEmpty()) {
return "";
}
BiFunction<Integer, BiFunction<Integer, Integer, RuntimeException>, RuntimeException> err =
(start, ex) -> {
String snapshot = expression.substring(0, start);
int line = Math.max(1, (int) snapshot.chars().filter(ch -> ch == '\n').count());
int column = start - snapshot.lastIndexOf('\n');
return ex.apply(line, column);
};
StringBuilder buffer = new StringBuilder();
int offset = 0;
int start = expression.indexOf(startDelim);
while (start >= 0) {
int end = expression.indexOf(endDelim, start + startDelim.length());
if (end == -1) {
throw err.apply(
start,
(line, column) ->
new IllegalArgumentException(
"found '"
+ startDelim
+ "' expecting '"
+ endDelim
+ "' at "
+ line
+ ":"
+ column));
}
buffer.append(expression.substring(offset, start));
String key = expression.substring(start + startDelim.length(), end);
String value;
try {
// seek
String[] path = key.split("\\.");
var src = path[0].equals(name()) ? this : get(path[0]);
for (int i = 1; i < path.length; i++) {
src = src.get(path[i]);
}
value = src.value();
} catch (MissingValueException x) {
if (ignoreMissing) {
value = expression.substring(start, end + endDelim.length());
} else {
throw err.apply(
start,
(line, column) ->
new NoSuchElementException(
"Missing " + startDelim + key + endDelim + " at " + line + ":" + column));
}
}
buffer.append(value);
offset = end + endDelim.length();
start = expression.indexOf(startDelim, offset);
}
if (buffer.isEmpty()) {
return expression;
}
if (offset < expression.length()) {
buffer.append(expression.substring(offset));
}
return buffer.toString();
}
/**
* Convert this value to long (if possible).
*
* @return Long value.
*/
default long longValue() {
try {
return Long.parseLong(value());
} catch (NumberFormatException x) {
try {
LocalDateTime date = LocalDateTime.parse(value(), Context.RFC1123);
Instant instant = date.toInstant(ZoneOffset.UTC);
return instant.toEpochMilli();
} catch (DateTimeParseException ignored) {
}
throw new TypeMismatchException(name(), long.class, x);
}
}
/**
* Convert this value to long (if possible) or fallback to given value when missing.
*
* @param defaultValue Default value.
* @return Convert this value to long (if possible) or fallback to given value when missing.
*/
default long longValue(long defaultValue) {
try {
return longValue();
} catch (MissingValueException x) {
return defaultValue;
}
}
/**
* Convert this value to int (if possible).
*
* @return Int value.
*/
default int intValue() {
try {
return Integer.parseInt(value());
} catch (NumberFormatException x) {
throw new TypeMismatchException(name(), int.class, x);
}
}
/**
* Convert this value to int (if possible) or fallback to given value when missing.
*
* @param defaultValue Default value.
* @return Convert this value to int (if possible) or fallback to given value when missing.
*/
default int intValue(int defaultValue) {
try {
return intValue();
} catch (MissingValueException x) {
return defaultValue;
}
}
/**
* Convert this value to byte (if possible).
*
* @return Convert this value to byte (if possible).
*/
default byte byteValue() {
try {
return Byte.parseByte(value());
} catch (NumberFormatException x) {
throw new TypeMismatchException(name(), byte.class, x);
}
}
/**
* Convert this value to byte (if possible) or fallback to given value when missing.
*
* @param defaultValue Default value.
* @return Convert this value to byte (if possible) or fallback to given value when missing.
*/
default byte byteValue(byte defaultValue) {
try {
return byteValue();
} catch (MissingValueException x) {
return defaultValue;
}
}
/**
* Convert this value to float (if possible).
*
* @return Convert this value to float (if possible).
*/
default float floatValue() {
try {
return Float.parseFloat(value());
} catch (NumberFormatException x) {
throw new TypeMismatchException(name(), float.class, x);
}
}
/**
* Convert this value to float (if possible) or fallback to given value when missing.
*
* @param defaultValue Default value.
* @return Convert this value to float (if possible) or fallback to given value when missing.
*/
default float floatValue(float defaultValue) {
try {
return floatValue();
} catch (MissingValueException x) {
return defaultValue;
}
}
/**
* Convert this value to double (if possible).
*
* @return Convert this value to double (if possible).
*/
default double doubleValue() {
try {
return Double.parseDouble(value());
} catch (NumberFormatException x) {
throw new TypeMismatchException(name(), double.class, x);
}
}
/**
* Convert this value to double (if possible) or fallback to given value when missing.
*
* @param defaultValue Default value.
* @return Convert this value to double (if possible) or fallback to given value when missing.
*/
default double doubleValue(double defaultValue) {
try {
return doubleValue();
} catch (MissingValueException x) {
return defaultValue;
}
}
/**
* Convert this value to boolean (if possible).
*
* @return Convert this value to boolean (if possible).
*/
default boolean booleanValue() {
return Boolean.parseBoolean(value());
}
/**
* Convert this value to boolean (if possible) or fallback to given value when missing.
*
* @param defaultValue Default value.
* @return Convert this value to boolean (if possible) or fallback to given value when missing.
*/
default boolean booleanValue(boolean defaultValue) {
try {
return booleanValue();
} catch (MissingValueException x) {
return defaultValue;
}
}
/**
* Convert this value to String (if possible) or fallback to given value when missing.
*
* @param defaultValue Default value.
* @return Convert this value to String (if possible) or fallback to given value when missing.
*/
default String value(String defaultValue) {
try {
return value();
} catch (MissingValueException x) {
return defaultValue;
}
}
/**
* Convert this value to String (if possible) or <code>null</code> when missing.
*
* @return Convert this value to String (if possible) or <code>null</code> when missing.
*/
@Nullable default String valueOrNull() {
return value((String) null);
}
/**
* Convert value using the given function.
*
* @param fn Function.
* @param <T> Target type.
* @return Converted value.
*/
default <T> T value(SneakyThrows.Function<String, T> fn) {
return fn.apply(value());
}
/**
* Get string value.
*
* @return String value.
*/
String value();
/**
* Get list of values.
*
* @return List of values.
*/
List<String> toList();
/**
* Get set of values.
*
* @return set of values.
*/
Set<String> toSet();
/**
* Convert this value to an Enum.
*
* @param fn Mapping function.
* @param <T> Enum type.
* @return Enum.
*/
default <T extends Enum<T>> T toEnum(SneakyThrows.Function<String, T> fn) {
return toEnum(fn, String::toUpperCase);
}
/**
* Convert this value to an Enum.
*
* @param fn Mapping function.
* @param nameProvider Enum name provider.
* @param <T> Enum type.
* @return Enum.
*/
default <T extends Enum<T>> T toEnum(
SneakyThrows.Function<String, T> fn, Function<String, String> nameProvider) {
return fn.apply(nameProvider.apply(value()));
}
/**
* Get a value or empty optional.
*
* @return Value or empty optional.
*/
default Optional<String> toOptional() {
try {
return Optional.of(value());
} catch (MissingValueException x) {
return Optional.empty();
}
}
/**
* True if this is a single value (not a hash or array).
*
* @return True if this is a single value (not a hash or array).
*/
default boolean isSingle() {
return this instanceof SingleValue;
}
/**
* True for missing values.
*
* @return True for missing values.
*/
default boolean isMissing() {
return this instanceof MissingValue;
}
/**
* True for present values.
*
* @return True for present values.
*/
default boolean isPresent() {
return !isMissing();
}
/**
* True if this value is an array/sequence (not single or hash).
*
* @return True if this value is an array/sequence.
*/
default boolean isArray() {
return this instanceof ArrayValue;
}
/**
* True if this is a hash/object value (not single or array).
*
* @return True if this is a hash/object value (not single or array).
*/
default boolean isObject() {
return this instanceof HashValue;
}
/**
* Name of this value or <code>empty string</code> for root hash.
*
* @return Name of this value or <code>empty string</code> for root hash.
*/
@Nullable String name();
/**
* Get a value or empty optional.
*
* @param type Item type.
* @param <T> Item type.
* @return Value or empty optional.
*/
default <T> Optional<T> toOptional(Class<T> type) {
try {
return Optional.ofNullable(toNullable(type));
} catch (MissingValueException x) {
return Optional.empty();
}
}
/**
* Get list of the given type.
*
* @param type Type to convert.
* @param <T> Item type.
* @return List of items.
*/
default <T> List<T> toList(Class<T> type) {
return List.of(to(type));
}
/**
* Get set of the given type.
*
* @param type Type to convert.
* @param <T> Item type.
* @return Set of items.
*/
default <T> Set<T> toSet(Class<T> type) {
return Set.of(to(type));
}
/**
* Convert this value to the given type. Support values are single-value, array-value and
* object-value. Object-value can be converted to a JavaBean type.
*
* <p>At least one of the property of the node must match a target type property.
*
* @param type Type to convert.
* @param <T> Element type.
* @return Instance of the type.
*/
<T> T to(Class<T> type);
/**
* Convert this value to the given type. Support values are single-value, array-value and
* object-value. Object-value can be converted to a JavaBean type.
*
* @param type Type to convert.
* @param <T> Element type.
* @return Instance of the type or <code>null</code>.
*/
@Nullable <T> T toNullable(Class<T> type);
/**
* Value as multi-value map.
*
* @return Value as multi-value map.
*/
Map<String, List<String>> toMultimap();
/**
* Value as single-value map.
*
* @return Value as single-value map.
*/
default Map<String, String> toMap() {
Map<String, String> map = new LinkedHashMap<>();
toMultimap().forEach((k, v) -> map.put(k, v.get(0)));
return map;
}
/* ***********************************************************************************************
* Factory methods
* ***********************************************************************************************
*/
/**
* Creates a missing value.
*
* @param valueFactory Current context.
* @param name Name of missing value.
* @return Missing value.
*/
static Value missing(ValueFactory valueFactory, String name) {
return new MissingValue(valueFactory, name);
}
/**
* Creates a single value.
*
* @param valueFactory Current context.
* @param name Name of value.
* @param value Value.
* @return Single value.
*/
static Value value(ValueFactory valueFactory, String name, String value) {
return new SingleValue(valueFactory, name, value);
}
/**
* Creates a sequence/array of values.
*
* @param valueFactory Current context.
* @param name Name of array.
* @param values Field values.
* @return Array value.
*/
static Value array(ValueFactory valueFactory, String name, List<String> values) {
return new ArrayValue(valueFactory, name).add(values);
}
/**
* Creates a value that fits better with the given values.
*
* <p>- For null/empty values. It produces a missing value. - For single element (size==1). It
* produces a single value - For multi-value elements (size>1). It produces an array value.
*
* @param valueFactory Current context.
* @param name Field name.
* @param values Field values.
* @return A value.
*/
static Value create(ValueFactory valueFactory, String name, @Nullable List<String> values) {
if (values == null || values.isEmpty()) {
return missing(valueFactory, name);
}
if (values.size() == 1) {
return value(valueFactory, name, values.getFirst());
}
return new ArrayValue(valueFactory, name).add(values);
}
/**
* Creates a value that fits better with the given values.
*
* <p>- For null/empty values. It produces a missing value. - For single element (size==1). It
* produces a single value
*
* @param valueFactory Current context.
* @param name Field name.
* @param value Field values.
* @return A value.
*/
static Value create(ValueFactory valueFactory, String name, @Nullable String value) {
if (value == null) {
return missing(valueFactory, name);
}
return value(valueFactory, name, value);
}
/**
* Create a hash/object value using the map values.
*
* @param valueFactory Current context.
* @param values Map values.
* @return A hash/object value.
*/
static Value hash(ValueFactory valueFactory, Map<String, Collection<String>> values) {
var node = new HashValue(valueFactory, null);
node.put(values);
return node;
}
/**
* Creates a formdata.
*
* @param valueFactory Current context.
* @return A hash/object value.
*/
static Formdata formdata(ValueFactory valueFactory) {
return new MultipartNode(valueFactory);
}
/**
* Create a hash/object value using the map values.
*
* @param valueFactory Current context.
* @param values Map values.
* @return A hash/object value.
*/
static Value headers(ValueFactory valueFactory, Map<String, Collection<String>> values) {
var node = new HeadersValue(valueFactory);
node.put(values);
return node;
}
}