-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTemporalAmountParser.java
More file actions
417 lines (343 loc) · 15.9 KB
/
TemporalAmountParser.java
File metadata and controls
417 lines (343 loc) · 15.9 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
package com.eternalcode.commons.time;
import com.eternalcode.commons.Lazy;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAmount;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Predicate;
/**
* This class is used to parse temporal amount from string and format it to string.
* It can parse both {@link Period} and {@link Duration}.
* <p>
* It can parse both estimated and exact temporal amount.
* Estimated temporal amount is a temporal amount that is not exact.
* For example, if you want to parse 1 month, you can write 1mo or 30d.
* If you write 1mo, it can be estimated to 28, 29, 30 or 31 days.
* If you write 1y, it can be estimated to 365 or 366 days.
* </p>
* <p>
* This class is immutable.
* You can create new instance using constructor {@link PeriodParser#PeriodParser()} or {@link DurationParser#DurationParser()}.
* You can also use {@link DurationParser#DATE_TIME_UNITS}, {@link PeriodParser#DATE_UNITS} and {@link DurationParser#TIME_UNITS}.
* You can add new units using {@link #withUnit(String, ChronoUnit)}.
* </p>
* <p>
* Use {@link #parse(String)} to parse temporal amount from string.
* Use {@link #format(TemporalAmount)} to format temporal amount to string.
* </p>
* @param <T> type of temporal amount (must be {@link Duration} or {@link Period} or subclass of TemporalAmount)
*/
public abstract class TemporalAmountParser<T extends TemporalAmount> {
private static final Map<ChronoUnit, BigInteger> UNIT_TO_NANO = new LinkedHashMap<>();
static {
UNIT_TO_NANO.put(ChronoUnit.NANOS, BigInteger.valueOf(1L));
UNIT_TO_NANO.put(ChronoUnit.MICROS, BigInteger.valueOf(1_000L));
UNIT_TO_NANO.put(ChronoUnit.MILLIS, BigInteger.valueOf(1_000_000L));
UNIT_TO_NANO.put(ChronoUnit.SECONDS, BigInteger.valueOf(1_000_000_000L));
UNIT_TO_NANO.put(ChronoUnit.MINUTES, BigInteger.valueOf(60 * 1_000_000_000L));
UNIT_TO_NANO.put(ChronoUnit.HOURS, BigInteger.valueOf(60 * 60 * 1_000_000_000L));
UNIT_TO_NANO.put(ChronoUnit.DAYS, BigInteger.valueOf(24 * 60 * 60 * 1_000_000_000L));
UNIT_TO_NANO.put(ChronoUnit.WEEKS, BigInteger.valueOf(7 * 24 * 60 * 60 * 1_000_000_000L));
UNIT_TO_NANO.put(ChronoUnit.MONTHS, BigInteger.valueOf(30 * 24 * 60 * 60 * 1_000_000_000L));
UNIT_TO_NANO.put(ChronoUnit.YEARS, BigInteger.valueOf(365 * 24 * 60 * 60 * 1_000_000_000L));
UNIT_TO_NANO.put(ChronoUnit.DECADES, BigInteger.valueOf(10 * 365 * 24 * 60 * 60 * 1_000_000_000L));
}
private final ChronoUnit defaultZero;
private final Lazy<String> defaultZeroSymbol;
private final Map<String, ChronoUnit> units = new LinkedHashMap<>();
private final Set<TimeModifier> modifiers = new HashSet<>();
private final LocalDateTimeProvider baseForTimeEstimation;
protected TemporalAmountParser(ChronoUnit defaultZero, Map<String, ChronoUnit> units, Set<TimeModifier> modifiers, LocalDateTimeProvider baseForTimeEstimation) {
this(defaultZero, baseForTimeEstimation);
this.units.putAll(units);
this.modifiers.addAll(modifiers);
}
protected TemporalAmountParser(ChronoUnit defaultZero, LocalDateTimeProvider baseForTimeEstimation) {
this.defaultZero = defaultZero;
this.baseForTimeEstimation = baseForTimeEstimation;
this.defaultZeroSymbol = new Lazy<>(() -> this.units.entrySet()
.stream()
.filter(entry -> entry.getValue() == defaultZero)
.map(entry -> entry.getKey())
.findFirst()
.orElseThrow(() -> new IllegalStateException("Can not find default zero symbol for " + defaultZero))
);
}
public TemporalAmountParser<T> withUnit(String symbol, ChronoUnit chronoUnit) {
if (this.units.containsKey(symbol)) {
throw new IllegalArgumentException("Symbol " + symbol + " is already used");
}
if (!this.validCharacters(symbol, Character::isLetter)) {
throw new IllegalArgumentException("Symbol " + symbol + " contains non-letter characters");
}
Map<String, ChronoUnit> newUnits = new LinkedHashMap<>(this.units);
newUnits.put(symbol, chronoUnit);
return clone(this.defaultZero, newUnits, this.modifiers, this.baseForTimeEstimation);
}
public TemporalAmountParser<T> withLocalDateTimeProvider(LocalDateTimeProvider baseForTimeEstimation) {
return clone(this.defaultZero, this.units, this.modifiers, baseForTimeEstimation);
}
public TemporalAmountParser<T> withDefaultZero(ChronoUnit defaultZero) {
return clone(defaultZero, this.units, this.modifiers, this.baseForTimeEstimation);
}
public TemporalAmountParser<T> withRounded(ChronoUnit unit, RoundingMode roundingMode) {
return withTimeModifier(duration -> {
BigInteger nanosInUnit = UNIT_TO_NANO.get(unit);
BigInteger nanos = durationToNano(duration);
BigInteger rounded = round(roundingMode, nanos, nanosInUnit);
return Duration.ofNanos(rounded.longValue());
});
}
private static BigInteger round(RoundingMode roundingMode, BigInteger nanos, BigInteger nanosInUnit) {
BigInteger remainder = nanos.remainder(nanosInUnit);
BigInteger subtract = nanos.subtract(remainder);
BigInteger add = subtract.add(nanosInUnit);
BigInteger roundedUp = remainder.equals(BigInteger.ZERO) ? nanos : (nanos.signum() > 0 ? add : subtract.subtract(nanosInUnit));
BigInteger roundedDown = remainder.equals(BigInteger.ZERO) ? nanos : (nanos.signum() > 0 ? subtract : add.subtract(nanosInUnit));
int compare = remainder.abs().multiply(BigInteger.valueOf(2)).compareTo(nanosInUnit);
switch (roundingMode) {
case UP:
return roundedUp;
case DOWN:
return roundedDown;
case CEILING:
return nanos.signum() >= 0 ? roundedUp : roundedDown;
case FLOOR:
return nanos.signum() >= 0 ? roundedDown : roundedUp;
case HALF_UP:
return compare >= 0 ? roundedUp : roundedDown;
case HALF_DOWN:
return (compare > 0) ? roundedUp : roundedDown;
default: throw new IllegalArgumentException("Unsupported rounding mode " + roundingMode);
}
}
private TemporalAmountParser<T> withTimeModifier(TimeModifier modifier) {
Set<TimeModifier> newRoundedUnits = new HashSet<>(this.modifiers);
newRoundedUnits.add(modifier);
return clone(this.defaultZero, this.units, newRoundedUnits, this.baseForTimeEstimation);
}
protected abstract TemporalAmountParser<T> clone(ChronoUnit defaultZeroUnit, Map<String, ChronoUnit> units, Set<TimeModifier> modifiers, LocalDateTimeProvider baseForTimeEstimation);
private boolean validCharacters(String content, Predicate<Character> predicate) {
for (int i = 0; i < content.length(); i++) {
if (predicate.test(content.charAt(i))) {
continue;
}
return false;
}
return true;
}
/**
* Parses the given string and returns the estimated temporal amount.]
* <p>
* Examples:
* <ul>
* <li>{@code 1ns} - 1 nanosecond</li>
* <li>{@code 1us} - 1 microsecond</li>
* <li>{@code 1ms} - 1 millisecond</li>
* <li>{@code 1s} - 1 second</li>
* <li>{@code 1m} - 1 minute</li>
* <li>{@code 1h} - 1 hour</li>
* <li>{@code 1d} - 1 day</li>
* <li>{@code 1w} - 1 week</li>
* <li>{@code 1mo} - 1 month</li>
* <li>{@code 1y} - 1 year</li>
* <li>{@code 1d2h} - 1 day and 2 hours</li>
* <li>{@code 1d2h3m} - 1 day, 2 hours and 3 minutes</li>
* <li>{@code 1d2h3m4s} - 1 day, 2 hours, 3 minutes and 4 seconds</li>
* <li>{@code 1y2mo3w4d5h6m7s} - 1 year, 2 months, 3 weeks, 4 days, 5 hours, 6 minutes and 7 seconds</li>
* </ul>
*
* @param input the input to parse. Must not be null or empty. Must be in the format of {@code <number><unit>}.
* The string can not contain any characters that are not part of the number or the unit.
* The only exception is the minus sign, which is allowed at the start of the string.
* The unit must be one of the units that are configured for this parser.
* The number must be a valid number that can be parsed by {@link Long#parseLong(String)}.
*
* @return the estimated temporal amount
* @throws IllegalArgumentException if the input is null or empty,
* if the input is not in the format of {@code <number><unit>},
* if the unit is not a valid unit,
* if the number is not a valid number,
* if the number is decimal
*/
public T parse(String input) {
if (input.isEmpty()) {
throw new IllegalArgumentException("Input is empty");
}
T total = this.getZero();
boolean negative = false;
StringBuilder number = new StringBuilder();
StringBuilder unit = new StringBuilder();
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if (c == '-') {
if (i != 0) {
throw new IllegalArgumentException("Minus sign is only allowed at the start of the input");
}
negative = true;
continue;
}
if (Character.isDigit(c)) {
number.append(c);
continue;
}
if (Character.isLetter(c)) {
unit.append(c);
}
else {
throw new IllegalArgumentException("Invalid character " + c + " in input");
}
if (i == input.length() - 1 || Character.isDigit(input.charAt(i + 1))) {
TemporalEntry temporalEntry = this.parseTemporal(number.toString(), unit.toString());
total = this.plus(this.baseForTimeEstimation, total, temporalEntry);
number.setLength(0);
unit.setLength(0);
}
}
if (number.length() > 0 || unit.length() > 0) {
throw new IllegalArgumentException("Input is not in the format of <number><unit>");
}
if (negative) {
total = this.negate(total);
}
return total;
}
protected abstract T plus(LocalDateTimeProvider baseForTimeEstimation, T temporalAmount, TemporalEntry temporalEntry);
protected abstract T negate(T temporalAmount);
protected abstract T getZero();
private TemporalEntry parseTemporal(String number, String unit) {
if (number.isEmpty()) {
throw new IllegalArgumentException("Missing number before unit " + unit);
}
ChronoUnit chronoUnit = this.units.get(unit);
if (chronoUnit == null) {
throw new IllegalArgumentException("Unknown unit " + unit);
}
try {
long count = Long.parseLong(number);
return new TemporalEntry(count, chronoUnit);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Invalid number " + number);
}
}
protected static class TemporalEntry {
private final long count;
private final ChronoUnit unit;
public TemporalEntry(long count, ChronoUnit unit) {
this.count = count;
this.unit = unit;
}
public long getCount() {
return count;
}
public ChronoUnit getUnit() {
return unit;
}
}
public TimeResult prepare(T temporalAmount) {
List<TimePart> parts = new ArrayList<>();
Duration duration = this.toDuration(this.baseForTimeEstimation, temporalAmount);
for (TimeModifier modifier : this.modifiers) {
duration = modifier.modify(duration);
}
boolean isNegative = duration.isNegative();
if (duration.isNegative()) {
duration = duration.negated();
}
List<String> keys = new ArrayList<>(this.units.keySet());
Collections.reverse(keys);
for (String key : keys) {
ChronoUnit unit = this.units.get(key);
BigInteger nanosInOneUnit = UNIT_TO_NANO.get(unit);
if (nanosInOneUnit == null) {
throw new IllegalArgumentException("Unsupported unit " + unit);
}
BigInteger nanosCount = this.durationToNano(duration);
BigInteger count = nanosCount.divide(nanosInOneUnit);
if (count.equals(BigInteger.ZERO)) {
continue;
}
BigInteger nanosCountCleared = count.multiply(nanosInOneUnit);
parts.add(new TimePart(count, key, unit));
duration = duration.minusNanos(nanosCountCleared.longValue());
}
return new TimeResult(parts, isNegative);
}
/**
* Formats the given estimated temporal amount to a string.
* <p>
* Examples:
* </p>
* <ul>
* <li>Duration of 30 seconds: {@code 30s}</li>
* <li>Duration of 25 hours: {@code 1d1h}</li>
* <li>Duration of 1 year, 2 months, 3 weeks, 4 days, 5 hours, 6 minutes and 7 seconds: {@code 1y2mo3w4d5h6m7s}</li>
* <li>Duration of 1 hours and 61 minutes: {@code 2h1m}</li>
* <li>Past duration of 1 hours and 61 minutes: {@code -2h1m}</li>
* <li>Period of 1 year, 2 months, 4 days: {@code 1y2mo4d}</li>
* <li>Past period of 1 year, 2 months, 4 days: {@code -1y2mo4d}</li>
* </ul>
*
* @param temporalAmount the temporal amount to format. Must not be null.
* @return the formatted string
*/
public String format(T temporalAmount) {
TimeResult result = this.prepare(temporalAmount);
if (result.parts().isEmpty()) {
String defaultSymbol = this.defaultZeroSymbol.get();
return "0" + defaultSymbol;
}
StringBuilder builder = new StringBuilder();
if (result.isNegative()) {
builder.append('-');
}
for (TimePart part : result.parts()) {
if (part.count().equals(BigInteger.ZERO)) {
continue;
}
builder.append(part.count()).append(part.name());
}
return builder.toString();
}
protected abstract Duration toDuration(LocalDateTimeProvider baseForTimeEstimation, T temporalAmount);
/**
* A provider for {@link LocalDateTime}.
* It is used to calculate the estimated time.
* Depending on the basis, calculations of {@link TemporalAmountParser} may be different.
* For example, if the basis is {@link LocalDateTimeProvider#now}, then the estimated time is calculated from the current time.
*/
public interface LocalDateTimeProvider {
LocalDateTime get();
static LocalDateTimeProvider now() {
return LocalDateTime::now;
}
static LocalDateTimeProvider startOfToday() {
return of(LocalDate.now());
}
static LocalDateTimeProvider of(LocalDateTime localDateTime) {
return () -> localDateTime;
}
static LocalDateTimeProvider of(LocalDate localDate) {
return localDate::atStartOfDay;
}
}
protected interface TimeModifier {
Duration modify(Duration duration);
}
private BigInteger durationToNano(Duration duration) {
return BigInteger.valueOf(duration.getSeconds())
.multiply(BigInteger.valueOf(1_000_000_000))
.add(BigInteger.valueOf(duration.getNano()));
}
}