1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.lang3.time;
18
19 import java.io.IOException;
20 import java.io.ObjectInputStream;
21 import java.io.Serializable;
22 import java.text.DateFormatSymbols;
23 import java.text.ParseException;
24 import java.text.ParsePosition;
25 import java.text.SimpleDateFormat;
26 import java.util.ArrayList;
27 import java.util.Calendar;
28 import java.util.Comparator;
29 import java.util.Date;
30 import java.util.GregorianCalendar;
31 import java.util.HashMap;
32 import java.util.List;
33 import java.util.ListIterator;
34 import java.util.Locale;
35 import java.util.Map;
36 import java.util.Objects;
37 import java.util.Set;
38 import java.util.TimeZone;
39 import java.util.TreeMap;
40 import java.util.TreeSet;
41 import java.util.concurrent.ConcurrentHashMap;
42 import java.util.concurrent.ConcurrentMap;
43 import java.util.regex.Matcher;
44 import java.util.regex.Pattern;
45 import java.util.stream.Stream;
46
47 import org.apache.commons.lang3.CharUtils;
48 import org.apache.commons.lang3.LocaleUtils;
49 import org.apache.commons.lang3.SerializationUtils;
50 import org.apache.commons.lang3.StringUtils;
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 public class FastDateParser implements DateParser, Serializable {
95
96
97
98
99 private static final class CaseInsensitiveTextStrategy extends PatternStrategy {
100
101 private final int field;
102 private final Locale locale;
103 private final Map<String, Integer> lKeyValues;
104
105
106
107
108
109
110
111
112 CaseInsensitiveTextStrategy(final int field, final Calendar definingCalendar, final Locale locale) {
113 this.field = field;
114 this.locale = LocaleUtils.toLocale(locale);
115 final StringBuilder regex = new StringBuilder();
116 regex.append("((?iu)");
117 lKeyValues = appendDisplayNames(definingCalendar, locale, field, regex);
118 regex.setLength(regex.length() - 1);
119 regex.append(")");
120 createPattern(regex);
121 }
122
123
124
125
126 @Override
127 void setCalendar(final FastDateParser parser, final Calendar calendar, final String value) {
128 String lowerCase = value.toLowerCase(locale);
129 Integer iVal = lKeyValues.get(lowerCase);
130 if (iVal == null) {
131
132 iVal = lKeyValues.get(lowerCase + '.');
133 }
134 if (iVal == null) {
135
136
137
138
139 lowerCase = value.toLowerCase(Locale.ROOT);
140 iVal = lKeyValues.get(lowerCase);
141 if (iVal == null) {
142 iVal = lKeyValues.get(lowerCase + '.');
143 }
144 }
145 if (iVal == null) {
146
147
148 throw new IllegalArgumentException("Invalid display name for field " + field + ": '" + value + "'");
149 }
150
151 if (Calendar.AM_PM != this.field || iVal <= 1) {
152 calendar.set(field, iVal.intValue());
153 }
154 }
155
156
157
158
159
160
161 @Override
162 public String toString() {
163 return "CaseInsensitiveTextStrategy [field=" + field + ", locale=" + locale + ", lKeyValues=" + lKeyValues + ", pattern=" + pattern + "]";
164 }
165 }
166
167
168
169
170 private static final class CopyQuotedStrategy extends Strategy {
171
172 private final String formatField;
173
174
175
176
177
178
179 CopyQuotedStrategy(final String formatField) {
180 this.formatField = formatField;
181 }
182
183
184
185
186 @Override
187 boolean isNumber() {
188 return false;
189 }
190
191 @Override
192 boolean parse(final FastDateParser parser, final Calendar calendar, final String source, final ParsePosition pos, final int maxWidth) {
193 for (int idx = 0; idx < formatField.length(); ++idx) {
194 final int sIdx = idx + pos.getIndex();
195 if (sIdx == source.length() || formatField.charAt(idx) != source.charAt(sIdx)) {
196 pos.setErrorIndex(sIdx);
197 return false;
198 }
199 }
200 pos.setIndex(formatField.length() + pos.getIndex());
201 return true;
202 }
203
204
205
206
207
208
209 @Override
210 public String toString() {
211 return "CopyQuotedStrategy [formatField=" + formatField + "]";
212 }
213 }
214
215 private static final class ISO8601TimeZoneStrategy extends PatternStrategy {
216
217
218 private static final Strategy ISO_8601_1_STRATEGY = new ISO8601TimeZoneStrategy("(Z|(?:[+-](?:2[0-3]|[01]\\d)))");
219
220 private static final Strategy ISO_8601_2_STRATEGY = new ISO8601TimeZoneStrategy("(Z|(?:[+-](?:2[0-3]|[01]\\d)[0-5]\\d))");
221
222 private static final Strategy ISO_8601_3_STRATEGY = new ISO8601TimeZoneStrategy("(Z|(?:[+-](?:2[0-3]|[01]\\d)(?::)[0-5]\\d))");
223
224
225
226
227
228
229
230
231 static Strategy getStrategy(final int tokenLen) {
232 switch (tokenLen) {
233 case 1:
234 return ISO_8601_1_STRATEGY;
235 case 2:
236 return ISO_8601_2_STRATEGY;
237 case 3:
238 return ISO_8601_3_STRATEGY;
239 default:
240 throw new IllegalArgumentException("Invalid number of X");
241 }
242 }
243
244
245
246
247
248
249 ISO8601TimeZoneStrategy(final String pattern) {
250 createPattern(pattern);
251 }
252
253
254
255
256 @Override
257 void setCalendar(final FastDateParser parser, final Calendar calendar, final String value) {
258 calendar.setTimeZone(FastTimeZone.getGmtTimeZone(value));
259 }
260 }
261
262
263
264
265 private static class NumberStrategy extends Strategy {
266
267 private final int field;
268
269
270
271
272
273
274 NumberStrategy(final int field) {
275 this.field = field;
276 }
277
278
279
280
281 @Override
282 boolean isNumber() {
283 return true;
284 }
285
286
287
288
289
290
291
292
293 int modify(final FastDateParser parser, final int iValue) {
294 return iValue;
295 }
296
297 @Override
298 boolean parse(final FastDateParser parser, final Calendar calendar, final String source, final ParsePosition pos, final int maxWidth) {
299 int idx = pos.getIndex();
300 int last = source.length();
301 if (maxWidth == 0) {
302
303 for (; idx < last; ++idx) {
304 final char c = source.charAt(idx);
305 if (!Character.isWhitespace(c)) {
306 break;
307 }
308 }
309 pos.setIndex(idx);
310 } else {
311 final int end = idx + maxWidth;
312 if (last > end) {
313 last = end;
314 }
315 }
316 for (; idx < last; ++idx) {
317 final char c = source.charAt(idx);
318 if (!Character.isDigit(c)) {
319 break;
320 }
321 }
322 if (pos.getIndex() == idx) {
323 pos.setErrorIndex(idx);
324 return false;
325 }
326 final int value;
327 try {
328 value = Integer.parseInt(source.substring(pos.getIndex(), idx));
329 } catch (final NumberFormatException nfe) {
330
331
332 pos.setErrorIndex(pos.getIndex());
333 return false;
334 }
335 pos.setIndex(idx);
336 calendar.set(field, modify(parser, value));
337 return true;
338 }
339
340
341
342
343
344
345 @Override
346 public String toString() {
347 return getClass().getSimpleName() + " [field=" + field + "]";
348 }
349 }
350
351
352
353
354 private abstract static class PatternStrategy extends Strategy {
355
356 Pattern pattern;
357
358 void createPattern(final String regex) {
359 this.pattern = Pattern.compile(regex);
360 }
361
362 void createPattern(final StringBuilder regex) {
363 createPattern(regex.toString());
364 }
365
366
367
368
369
370
371 @Override
372 boolean isNumber() {
373 return false;
374 }
375
376 @Override
377 boolean parse(final FastDateParser parser, final Calendar calendar, final String source, final ParsePosition pos, final int maxWidth) {
378 final Matcher matcher = pattern.matcher(source.substring(pos.getIndex()));
379 if (!matcher.lookingAt()) {
380 pos.setErrorIndex(pos.getIndex());
381 return false;
382 }
383 try {
384 setCalendar(parser, calendar, matcher.group(1));
385 } catch (final IllegalArgumentException e) {
386
387
388
389
390 pos.setErrorIndex(pos.getIndex());
391 return false;
392 }
393 pos.setIndex(pos.getIndex() + matcher.end(1));
394 return true;
395 }
396
397 abstract void setCalendar(FastDateParser parser, Calendar calendar, String value);
398
399
400
401
402
403
404 @Override
405 public String toString() {
406 return getClass().getSimpleName() + " [pattern=" + pattern + "]";
407 }
408
409 }
410
411
412
413
414 private abstract static class Strategy {
415
416
417
418
419
420
421 boolean isNumber() {
422 return false;
423 }
424
425 abstract boolean parse(FastDateParser parser, Calendar calendar, String source, ParsePosition pos, int maxWidth);
426 }
427
428
429
430
431 private static final class StrategyAndWidth {
432
433 final Strategy strategy;
434 final int width;
435
436 StrategyAndWidth(final Strategy strategy, final int width) {
437 this.strategy = Objects.requireNonNull(strategy, "strategy");
438 this.width = width;
439 }
440
441 int getMaxWidth(final ListIterator<StrategyAndWidth> lt) {
442 if (!strategy.isNumber() || !lt.hasNext()) {
443 return 0;
444 }
445 final Strategy nextStrategy = lt.next().strategy;
446 lt.previous();
447 return nextStrategy.isNumber() ? width : 0;
448 }
449
450 @Override
451 public String toString() {
452 return "StrategyAndWidth [strategy=" + strategy + ", width=" + width + "]";
453 }
454 }
455
456
457
458
459
460
461
462
463 private final class StrategyParser {
464 private final Calendar definingCalendar;
465 private int currentIdx;
466
467 StrategyParser(final Calendar definingCalendar) {
468 this.definingCalendar = Objects.requireNonNull(definingCalendar, "definingCalendar");
469 }
470
471 StrategyAndWidth getNextStrategy() {
472 if (currentIdx >= pattern.length()) {
473 return null;
474 }
475 final char c = pattern.charAt(currentIdx);
476 if (CharUtils.isAsciiAlpha(c)) {
477 return letterPattern(c);
478 }
479 return literal();
480 }
481
482 private StrategyAndWidth letterPattern(final char c) {
483 final int begin = currentIdx;
484 while (++currentIdx < pattern.length()) {
485 if (pattern.charAt(currentIdx) != c) {
486 break;
487 }
488 }
489 final int width = currentIdx - begin;
490 return new StrategyAndWidth(getStrategy(c, width, definingCalendar), width);
491 }
492
493 private StrategyAndWidth literal() {
494 boolean activeQuote = false;
495 final StringBuilder sb = new StringBuilder();
496 while (currentIdx < pattern.length()) {
497 final char c = pattern.charAt(currentIdx);
498 if (!activeQuote && CharUtils.isAsciiAlpha(c)) {
499 break;
500 }
501 if (c == '\'' && (++currentIdx == pattern.length() || pattern.charAt(currentIdx) != '\'')) {
502 activeQuote = !activeQuote;
503 continue;
504 }
505 ++currentIdx;
506 sb.append(c);
507 }
508 if (activeQuote) {
509 throw new IllegalArgumentException("Unterminated quote");
510 }
511 final String formatField = sb.toString();
512 return new StrategyAndWidth(new CopyQuotedStrategy(formatField), formatField.length());
513 }
514 }
515
516
517
518
519 static class TimeZoneStrategy extends PatternStrategy {
520
521 private static final class TzInfo {
522 final TimeZone zone;
523 final int dstOffset;
524
525 TzInfo(final TimeZone tz, final boolean useDst) {
526 zone = tz;
527 dstOffset = useDst ? tz.getDSTSavings() : 0;
528 }
529
530 @Override
531 public String toString() {
532 return "TzInfo [zone=" + zone + ", dstOffset=" + dstOffset + "]";
533 }
534 }
535
536
537 private static final String RFC_822_TIME_ZONE = "[+-](?:2[0-3]|[01]\\d)[0-5]\\d";
538
539
540
541
542 private static final String ISO_8601_EXTENDED_TIME_ZONE = "[+-](?:2[0-3]|[01]\\d):?[0-5]\\d";
543
544
545
546
547
548 private static final ConcurrentMap<Locale, Strategy> ISO_EXTENDED_ZONE_CACHE = new ConcurrentHashMap<>(3);
549
550 private static final String GMT_OPTION = TimeZones.GMT_ID + "[+-]\\d{1,2}:\\d{2}";
551
552
553
554
555 private static final int ID = 0;
556
557 static void clearIsoExtendedCache() {
558 ISO_EXTENDED_ZONE_CACHE.clear();
559 }
560
561
562
563
564
565
566
567 static Strategy getIsoExtendedStrategy(final Locale locale) {
568 return ISO_EXTENDED_ZONE_CACHE.computeIfAbsent(LocaleUtils.toLocale(locale), k -> new TimeZoneStrategy(k, true));
569 }
570
571
572
573
574
575
576
577
578
579
580
581
582
583 static boolean skipTimeZone(final String tzId) {
584 return tzId.equalsIgnoreCase(TimeZones.GMT_ID);
585 }
586
587 private final Locale locale;
588
589
590
591
592
593 private final Map<String, TzInfo> tzNames = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
594
595
596
597
598
599
600
601
602 TimeZoneStrategy(final Locale locale, final boolean iso8601Extended) {
603 this.locale = LocaleUtils.toLocale(locale);
604 final StringBuilder sb = new StringBuilder();
605 sb.append("((?iu)" + (iso8601Extended ? ISO_8601_EXTENDED_TIME_ZONE : RFC_822_TIME_ZONE) + "|" + GMT_OPTION);
606 final Set<String> sorted = new TreeSet<>(LONGER_FIRST_LOWERCASE);
607
608
609 final String[][] zones = DateFormatSymbols.getInstance(locale).getZoneStrings();
610 for (final String[] zoneNames : zones) {
611
612 final String tzId = zoneNames[ID];
613 if (skipTimeZone(tzId)) {
614 continue;
615 }
616 final TimeZone tz = TimeZones.getTimeZone(tzId);
617
618
619 final TzInfo standard = new TzInfo(tz, false);
620 TzInfo tzInfo = standard;
621 for (int i = 1; i < zoneNames.length; ++i) {
622 switch (i) {
623 case 3:
624
625 tzInfo = new TzInfo(tz, true);
626 break;
627 case 5:
628 tzInfo = standard;
629 break;
630 default:
631 break;
632 }
633 final String zoneName = zoneNames[i];
634
635 if (zoneName != null && sorted.add(zoneName)) {
636 tzNames.put(zoneName, tzInfo);
637 }
638 }
639 }
640
641 for (final String tzId : TimeZones.SORTED_AVAILABLE_IDS) {
642 if (skipTimeZone(tzId)) {
643 continue;
644 }
645 final TimeZone tz = TimeZones.getTimeZone(tzId);
646 final String zoneName = tz.getDisplayName(locale);
647 if (sorted.add(zoneName)) {
648 tzNames.put(zoneName, new TzInfo(tz, tz.observesDaylightTime()));
649 }
650 }
651
652
653 sorted.forEach(zoneName -> simpleQuote(sb.append('|'), zoneName));
654 sb.append(")");
655 createPattern(sb);
656 }
657
658
659
660
661 @Override
662 void setCalendar(final FastDateParser parser, final Calendar calendar, final String timeZone) {
663 final TimeZone tz = FastTimeZone.getGmtTimeZone(timeZone);
664 if (tz != null) {
665 calendar.setTimeZone(tz);
666 } else {
667 TzInfo tzInfo = tzNames.get(timeZone);
668 if (tzInfo == null) {
669
670 tzInfo = tzNames.get(timeZone + '.');
671 if (tzInfo == null) {
672
673
674
675 throw new IllegalArgumentException(
676 String.format("Can't find time zone '%s' (%d chars)", timeZone, timeZone.length()));
677 }
678 }
679 calendar.set(Calendar.DST_OFFSET, tzInfo.dstOffset);
680 calendar.set(Calendar.ZONE_OFFSET, tzInfo.zone.getRawOffset());
681 }
682 }
683
684
685
686
687
688
689 @Override
690 public String toString() {
691 return "TimeZoneStrategy [locale=" + locale + ", tzNames=" + tzNames + ", pattern=" + pattern + "]";
692 }
693
694 }
695
696
697
698
699
700
701
702
703 private static final class WeekDateRecorder extends GregorianCalendar {
704
705 private static final long serialVersionUID = 1L;
706
707
708 private final Calendar target;
709
710 private transient int weekYearValue;
711 private transient boolean weekYearSet;
712 private transient int weekOfYearValue;
713 private transient boolean weekOfYearSet;
714 private transient int dayOfWeekValue;
715 private transient boolean dayOfWeekSet;
716
717 WeekDateRecorder(final Calendar target) {
718 this.target = target;
719 }
720
721
722
723
724
725
726
727
728 void applyWeekDate() {
729 if (!weekYearSet) {
730 return;
731 }
732 int weekOfYear = weekOfYearSet ? weekOfYearValue : 1;
733 int dayOfWeek = dayOfWeekSet ? dayOfWeekValue : target.getFirstDayOfWeek();
734 if (!isValidDayOfWeek(dayOfWeek) && target.isLenient()) {
735
736
737 if (dayOfWeek >= 8) {
738 dayOfWeek--;
739 weekOfYear += dayOfWeek / 7;
740 dayOfWeek = dayOfWeek % 7 + 1;
741 } else {
742 while (dayOfWeek <= 0) {
743 dayOfWeek += 7;
744 weekOfYear--;
745 }
746 }
747 dayOfWeek = toCalendarDayOfWeek(dayOfWeek);
748 }
749 target.setWeekDate(weekYearValue, weekOfYear, dayOfWeek);
750 }
751
752 @Override
753 public void set(final int field, final int value) {
754 if (target == null) {
755
756 super.set(field, value);
757 return;
758 }
759 switch (field) {
760 case Calendar.YEAR:
761 weekYearValue = value;
762 weekYearSet = true;
763 break;
764 case Calendar.WEEK_OF_YEAR:
765 weekOfYearValue = value;
766 weekOfYearSet = true;
767 break;
768 case Calendar.DAY_OF_WEEK:
769 dayOfWeekValue = value;
770 dayOfWeekSet = true;
771 break;
772 default:
773 break;
774 }
775 target.set(field, value);
776 }
777
778 @Override
779 public void setTimeZone(final TimeZone zone) {
780 if (target == null) {
781
782 super.setTimeZone(zone);
783 return;
784 }
785 target.setTimeZone(zone);
786 }
787 }
788
789
790
791
792
793
794 private static final long serialVersionUID = 3L;
795
796 static final Locale JAPANESE_IMPERIAL = new Locale("ja", "JP", "JP");
797
798
799
800
801
802
803
804 private static final Comparator<String> LONGER_FIRST_LOWERCASE = Comparator.reverseOrder();
805
806 @SuppressWarnings("unchecked")
807 private static final ConcurrentMap<Locale, Strategy>[] CACHES = new ConcurrentMap[Calendar.FIELD_COUNT];
808
809 private static final Strategy ABBREVIATED_YEAR_STRATEGY = new NumberStrategy(Calendar.YEAR) {
810
811
812
813
814 @Override
815 int modify(final FastDateParser parser, final int iValue) {
816 return iValue < 100 ? parser.adjustYear(iValue) : iValue;
817 }
818 };
819
820 private static final Strategy NUMBER_MONTH_STRATEGY = new NumberStrategy(Calendar.MONTH) {
821 @Override
822 int modify(final FastDateParser parser, final int iValue) {
823 return iValue - 1;
824 }
825 };
826
827 private static final Strategy LITERAL_YEAR_STRATEGY = new NumberStrategy(Calendar.YEAR);
828
829 private static final Strategy WEEK_OF_YEAR_STRATEGY = new NumberStrategy(Calendar.WEEK_OF_YEAR);
830
831 private static final Strategy WEEK_OF_MONTH_STRATEGY = new NumberStrategy(Calendar.WEEK_OF_MONTH);
832
833 private static final Strategy DAY_OF_YEAR_STRATEGY = new NumberStrategy(Calendar.DAY_OF_YEAR);
834
835 private static final Strategy DAY_OF_MONTH_STRATEGY = new NumberStrategy(Calendar.DAY_OF_MONTH);
836
837 private static final Strategy DAY_OF_WEEK_STRATEGY = new NumberStrategy(Calendar.DAY_OF_WEEK) {
838 @Override
839 int modify(final FastDateParser parser, final int iValue) {
840 return toCalendarDayOfWeek(iValue);
841 }
842 };
843
844 private static final Strategy DAY_OF_WEEK_IN_MONTH_STRATEGY = new NumberStrategy(Calendar.DAY_OF_WEEK_IN_MONTH);
845
846 private static final Strategy HOUR_OF_DAY_STRATEGY = new NumberStrategy(Calendar.HOUR_OF_DAY);
847
848 private static final Strategy HOUR24_OF_DAY_STRATEGY = new NumberStrategy(Calendar.HOUR_OF_DAY) {
849 @Override
850 int modify(final FastDateParser parser, final int iValue) {
851 return iValue == 24 ? 0 : iValue;
852 }
853 };
854
855 private static final Strategy HOUR12_STRATEGY = new NumberStrategy(Calendar.HOUR) {
856 @Override
857 int modify(final FastDateParser parser, final int iValue) {
858 return iValue == 12 ? 0 : iValue;
859 }
860 };
861
862 private static final Strategy HOUR_STRATEGY = new NumberStrategy(Calendar.HOUR);
863
864 private static final Strategy MINUTE_STRATEGY = new NumberStrategy(Calendar.MINUTE);
865
866 private static final Strategy SECOND_STRATEGY = new NumberStrategy(Calendar.SECOND);
867
868 private static final Strategy MILLISECOND_STRATEGY = new NumberStrategy(Calendar.MILLISECOND);
869
870
871
872
873
874
875
876
877
878
879 private static Map<String, Integer> appendDisplayNames(final Calendar calendar, final Locale locale, final int field, final StringBuilder regex) {
880 Objects.requireNonNull(calendar, "calendar");
881 final Map<String, Integer> values = new HashMap<>();
882 final Locale actualLocale = LocaleUtils.toLocale(locale);
883 final Map<String, Integer> displayNames = calendar.getDisplayNames(field, Calendar.ALL_STYLES, actualLocale);
884 final TreeSet<String> sorted = new TreeSet<>(LONGER_FIRST_LOWERCASE);
885 displayNames.forEach((k, v) -> {
886 final String keyLc = k.toLowerCase(actualLocale);
887 if (sorted.add(keyLc)) {
888 values.put(keyLc, v);
889 }
890 });
891 sorted.forEach(symbol -> simpleQuote(regex, symbol).append('|'));
892 return values;
893 }
894
895
896
897
898 static void clear() {
899 Stream.of(CACHES).filter(Objects::nonNull).forEach(ConcurrentMap::clear);
900 TimeZoneStrategy.clearIsoExtendedCache();
901 }
902
903
904
905
906
907
908
909 private static ConcurrentMap<Locale, Strategy> getCache(final int field) {
910 synchronized (CACHES) {
911 if (CACHES[field] == null) {
912 CACHES[field] = new ConcurrentHashMap<>(3);
913 }
914 return CACHES[field];
915 }
916 }
917
918
919
920
921
922
923
924 private static boolean isValidDayOfWeek(final int dayOfWeek) {
925 return dayOfWeek >= Calendar.SUNDAY && dayOfWeek <= Calendar.SATURDAY;
926 }
927
928 private static StringBuilder simpleQuote(final StringBuilder sb, final String value) {
929 for (int i = 0; i < value.length(); ++i) {
930 final char c = value.charAt(i);
931 switch (c) {
932 case '\\':
933 case '^':
934 case '$':
935 case '.':
936 case '|':
937 case '?':
938 case '*':
939 case '+':
940 case '(':
941 case ')':
942 case '[':
943 case '{':
944 sb.append('\\');
945
946 default:
947 sb.append(c);
948 }
949 }
950 if (sb.charAt(sb.length() - 1) == '.') {
951
952 sb.append('?');
953 }
954 return sb;
955 }
956
957
958
959
960
961
962
963
964
965
966
967
968 private static int toCalendarDayOfWeek(final int isoDayOfWeek) {
969 if (!isValidDayOfWeek(isoDayOfWeek)) {
970 return isoDayOfWeek;
971 }
972 return isoDayOfWeek == 7 ? Calendar.SUNDAY : isoDayOfWeek + 1;
973 }
974
975
976 private final String pattern;
977
978
979 private final TimeZone timeZone;
980
981
982 private final Locale locale;
983
984
985
986
987 private final int century;
988
989
990
991
992 private final int startYear;
993
994
995 private transient List<StrategyAndWidth> patterns;
996
997
998
999
1000
1001 private transient volatile boolean weekYear;
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013 protected FastDateParser(final String pattern, final TimeZone timeZone, final Locale locale) {
1014 this(pattern, timeZone, locale, null);
1015 }
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026 protected FastDateParser(final String pattern, final TimeZone timeZone, final Locale locale, final Date centuryStart) {
1027 this.pattern = Objects.requireNonNull(pattern, "pattern");
1028
1029 this.timeZone = (TimeZone) Objects.requireNonNull(timeZone, "timeZone").clone();
1030 this.locale = LocaleUtils.toLocale(locale);
1031 final Calendar definingCalendar = Calendar.getInstance(timeZone, this.locale);
1032 final int centuryStartYear;
1033 if (centuryStart != null) {
1034 definingCalendar.setTime(centuryStart);
1035 centuryStartYear = definingCalendar.get(Calendar.YEAR);
1036 } else if (this.locale.equals(JAPANESE_IMPERIAL)) {
1037 centuryStartYear = 0;
1038 } else {
1039
1040 definingCalendar.setTime(new Date());
1041 centuryStartYear = definingCalendar.get(Calendar.YEAR) - 80;
1042 }
1043 century = centuryStartYear / 100 * 100;
1044 startYear = centuryStartYear - century;
1045 init(definingCalendar);
1046 }
1047
1048
1049
1050
1051
1052
1053
1054 private int adjustYear(final int twoDigitYear) {
1055 final int trial = century + twoDigitYear;
1056 return twoDigitYear >= startYear ? trial : trial + 100;
1057 }
1058
1059 private boolean checkLength(final String source, final ParsePosition pos) {
1060 final int startIndex = pos.getIndex();
1061 if (startIndex > source.length()) {
1062 pos.setErrorIndex(startIndex);
1063 return false;
1064 }
1065 return true;
1066 }
1067
1068
1069
1070
1071
1072
1073
1074 @Override
1075 public boolean equals(final Object obj) {
1076 if (!(obj instanceof FastDateParser)) {
1077 return false;
1078 }
1079 final FastDateParser other = (FastDateParser) obj;
1080 return pattern.equals(other.pattern) && timeZone.equals(other.timeZone) && locale.equals(other.locale);
1081 }
1082
1083
1084
1085
1086
1087
1088 @Override
1089 public Locale getLocale() {
1090 return locale;
1091 }
1092
1093
1094
1095
1096
1097
1098
1099
1100 private Strategy getLocaleSpecificStrategy(final int field, final Calendar definingCalendar) {
1101 return getCache(field).computeIfAbsent(locale,
1102 k -> field == Calendar.ZONE_OFFSET ? new TimeZoneStrategy(locale, false)
1103 : new CaseInsensitiveTextStrategy(field, definingCalendar, locale));
1104 }
1105
1106
1107
1108
1109
1110
1111 @Override
1112 public String getPattern() {
1113 return pattern;
1114 }
1115
1116 List<StrategyAndWidth> getPatterns() {
1117 return patterns;
1118 }
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128 private Strategy getStrategy(final char f, final int width, final Calendar definingCalendar) {
1129 switch (f) {
1130 case 'D':
1131 return DAY_OF_YEAR_STRATEGY;
1132 case 'E':
1133 return getLocaleSpecificStrategy(Calendar.DAY_OF_WEEK, definingCalendar);
1134 case 'F':
1135 return DAY_OF_WEEK_IN_MONTH_STRATEGY;
1136 case 'G':
1137 return getLocaleSpecificStrategy(Calendar.ERA, definingCalendar);
1138 case 'H':
1139 return HOUR_OF_DAY_STRATEGY;
1140 case 'K':
1141 return HOUR_STRATEGY;
1142 case 'M':
1143 case 'L':
1144 return width >= 3 ? getLocaleSpecificStrategy(Calendar.MONTH, definingCalendar) : NUMBER_MONTH_STRATEGY;
1145 case 'S':
1146 return MILLISECOND_STRATEGY;
1147 case 'W':
1148 return WEEK_OF_MONTH_STRATEGY;
1149 case 'a':
1150 return getLocaleSpecificStrategy(Calendar.AM_PM, definingCalendar);
1151 case 'd':
1152 return DAY_OF_MONTH_STRATEGY;
1153 case 'h':
1154 return HOUR12_STRATEGY;
1155 case 'k':
1156 return HOUR24_OF_DAY_STRATEGY;
1157 case 'm':
1158 return MINUTE_STRATEGY;
1159 case 's':
1160 return SECOND_STRATEGY;
1161 case 'u':
1162 return DAY_OF_WEEK_STRATEGY;
1163 case 'w':
1164 return WEEK_OF_YEAR_STRATEGY;
1165 case 'y':
1166 return width > 2 ? LITERAL_YEAR_STRATEGY : ABBREVIATED_YEAR_STRATEGY;
1167 case 'Y':
1168
1169
1170
1171
1172
1173
1174
1175 weekYear = true;
1176 return width > 2 ? LITERAL_YEAR_STRATEGY : ABBREVIATED_YEAR_STRATEGY;
1177 case 'X':
1178 return ISO8601TimeZoneStrategy.getStrategy(width);
1179 case 'Z':
1180 if (width == 2) {
1181 return ISO8601TimeZoneStrategy.ISO_8601_3_STRATEGY;
1182 }
1183 if (width >= 3) {
1184
1185
1186 return TimeZoneStrategy.getIsoExtendedStrategy(locale);
1187 }
1188
1189 case 'z':
1190 return getLocaleSpecificStrategy(Calendar.ZONE_OFFSET, definingCalendar);
1191 default:
1192 throw new IllegalArgumentException("Format '" + f + "' not supported");
1193 }
1194 }
1195
1196
1197
1198
1199
1200
1201 @Override
1202 public TimeZone getTimeZone() {
1203 return (TimeZone) timeZone.clone();
1204 }
1205
1206
1207
1208
1209
1210
1211 @Override
1212 public int hashCode() {
1213 return pattern.hashCode() + 13 * (timeZone.hashCode() + 13 * locale.hashCode());
1214 }
1215
1216
1217
1218
1219
1220
1221 private void init(final Calendar definingCalendar) {
1222 patterns = new ArrayList<>();
1223
1224 final StrategyParser strategyParser = new StrategyParser(definingCalendar);
1225 for (;;) {
1226 final StrategyAndWidth field = strategyParser.getNextStrategy();
1227 if (field == null) {
1228 break;
1229 }
1230 patterns.add(field);
1231 }
1232 }
1233
1234
1235
1236
1237
1238
1239 @Override
1240 public Date parse(final String source) throws ParseException {
1241 final ParsePosition pp = new ParsePosition(0);
1242 final Date date = parse(source, pp);
1243 if (date == null) {
1244
1245 final int errorIndex = pp.getErrorIndex();
1246 final String msg = String.format("Unparseable date: '%s', parse position = %s", source, pp);
1247 if (locale.equals(JAPANESE_IMPERIAL)) {
1248 throw new ParseException(String.format("%s; the %s locale does not support dates before 1868-01-01.", msg, locale), errorIndex);
1249 }
1250 throw new ParseException(msg, errorIndex);
1251 }
1252 return date;
1253 }
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265 @Override
1266 public Date parse(final String source, final ParsePosition pos) {
1267 if (!checkLength(source, pos)) {
1268 return null;
1269 }
1270
1271 final Calendar cal = Calendar.getInstance(timeZone, locale);
1272 cal.clear();
1273 return parse(source, pos, cal) ? cal.getTime() : null;
1274 }
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287 @Override
1288 public boolean parse(final String source, final ParsePosition pos, final Calendar calendar) {
1289 if (!checkLength(source, pos)) {
1290 return false;
1291 }
1292 final WeekDateRecorder recorder = weekYear && calendar.isWeekDateSupported() ? new WeekDateRecorder(calendar) : null;
1293 final Calendar sink = recorder != null ? recorder : calendar;
1294 final ListIterator<StrategyAndWidth> lt = patterns.listIterator();
1295 while (lt.hasNext()) {
1296 final StrategyAndWidth strategyAndWidth = lt.next();
1297 final int maxWidth = strategyAndWidth.getMaxWidth(lt);
1298 if (!strategyAndWidth.strategy.parse(this, sink, source, pos, maxWidth)) {
1299 return false;
1300 }
1301 }
1302 if (recorder != null) {
1303 recorder.applyWeekDate();
1304 }
1305 return true;
1306 }
1307
1308
1309
1310
1311
1312
1313 @Override
1314 public Object parseObject(final String source) throws ParseException {
1315 return parse(source);
1316 }
1317
1318
1319
1320
1321
1322
1323 @Override
1324 public Object parseObject(final String source, final ParsePosition pos) {
1325 return parse(source, pos);
1326 }
1327
1328
1329
1330
1331
1332
1333
1334
1335 private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
1336 in.defaultReadObject();
1337 SerializationUtils.requireNonNull(pattern, "pattern null");
1338 SerializationUtils.requireNonNull(timeZone, "timeZone null");
1339 init(Calendar.getInstance(timeZone, locale));
1340 }
1341
1342
1343
1344
1345
1346
1347 @Override
1348 public String toString() {
1349 return "FastDateParser[" + pattern + ", " + locale + ", " + timeZone.getID() + "]";
1350 }
1351
1352
1353
1354
1355
1356
1357
1358
1359 public String toStringAll() {
1360 return "FastDateParser [pattern=" + pattern + ", timeZone=" + timeZone + ", locale=" + locale + ", century=" + century + ", startYear=" + startYear
1361 + ", patterns=" + StringUtils.join(patterns, ", " + System.lineSeparator() + "\t") + "]";
1362 }
1363 }