@Override public int parseInto(ReadWritablePeriod period, String text, int position, Locale locale) { int bestValidPos = position; ReadWritablePeriod bestValidPeriod = null; int bestInvalidPos = position; for (PeriodParser parser : parsers) { ReadWritablePeriod parsedPeriod = new MutablePeriod(); int parsePos = parser.parseInto(parsedPeriod, text, position, locale); if (parsePos >= position) { if (parsePos > bestValidPos) { bestValidPos = parsePos; bestValidPeriod = parsedPeriod; if (parsePos >= text.length()) { break; } } } else if (parsePos < 0) { parsePos = ~parsePos; if (parsePos > bestInvalidPos) { bestInvalidPos = parsePos; } } } if (bestValidPos > position || (bestValidPos == position)) { // Restore the state to the best valid parse. if (bestValidPeriod != null) { period.setPeriod(bestValidPeriod); } return bestValidPos; } return ~bestInvalidPos; }
private static PeriodFormatter cretePeriodFormatter(IntervalField startField, IntervalField endField) { if (endField == null) { endField = startField; } List<PeriodParser> parsers = new ArrayList<>(); PeriodFormatterBuilder builder = new PeriodFormatterBuilder(); //CHECKSTYLE.OFF switch (startField) { case YEAR: builder.appendYears(); parsers.add(builder.toParser()); if (endField == IntervalField.YEAR) { break; } builder.appendLiteral("-"); case MONTH: builder.appendMonths(); parsers.add(builder.toParser()); if (endField != IntervalField.MONTH) { throw new IllegalArgumentException("Invalid interval qualifier: " + startField + " to " + endField); } break; case DAY: builder.appendDays(); parsers.add(builder.toParser()); if (endField == IntervalField.DAY) { break; } builder.appendLiteral(" "); case HOUR: builder.appendHours(); parsers.add(builder.toParser()); if (endField == IntervalField.HOUR) { break; } builder.appendLiteral(":"); case MINUTE: builder.appendMinutes(); parsers.add(builder.toParser()); if (endField == IntervalField.MINUTE) { break; } builder.appendLiteral(":"); case SECOND: builder.appendSecondsWithOptionalMillis(); parsers.add(builder.toParser()); } //CHECKSTYLE.ON return new PeriodFormatter(builder.toPrinter(), new OrderedPeriodParser(parsers)); }
private OrderedPeriodParser(List<PeriodParser> parsers) { this.parsers = parsers; }