RelativeDateTimeParser.java

  1. /*
  2.  *
  3.  * The DbUnit Database Testing Framework
  4.  * Copyright (C)2002-2004, DbUnit.org
  5.  *
  6.  * This library is free software; you can redistribute it and/or
  7.  * modify it under the terms of the GNU Lesser General Public
  8.  * License as published by the Free Software Foundation; either
  9.  * version 2.1 of the License, or (at your option) any later version.
  10.  *
  11.  * This library is distributed in the hope that it will be useful,
  12.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  14.  * Lesser General Public License for more details.
  15.  *
  16.  * You should have received a copy of the GNU Lesser General Public
  17.  * License along with this library; if not, write to the Free Software
  18.  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  19.  *
  20.  */

  21. package org.dbunit.util;

  22. import java.time.Clock;
  23. import java.time.Instant;
  24. import java.time.LocalDateTime;
  25. import java.time.LocalTime;
  26. import java.time.ZoneId;
  27. import java.time.temporal.ChronoUnit;
  28. import java.time.temporal.TemporalUnit;
  29. import java.util.regex.Matcher;
  30. import java.util.regex.Pattern;

  31. /**
  32.  * <p>
  33.  * A parser for relative date time string.<br>
  34.  * The basic format is <code>[now{diff...}{time}]</code>.<br>
  35.  * 'diff' consists of two parts 1) a number with a leading plus or minus sign
  36.  * and 2) a character represents temporal unit. See the table below for the
  37.  * supported units. There can be multiple 'diff's and they can be specified in
  38.  * any order.<br>
  39.  * 'time' is a string that can be parsed by
  40.  * <code>LocalTime#parse()</cde>. If specified, it is used instead of the current time.<br>
  41.  * Both 'diff' and 'time' are optional.<br>
  42.  * Whitespaces are allowed before and after each 'diff'.
  43.  * </p>
  44.  * <h3>Unit</h3>
  45.  * <ul>
  46.  * <li>y : years</li>
  47.  * <li>M : months</li>
  48.  * <li>d : days</li>
  49.  * <li>h : hours</li>
  50.  * <li>m : minutes</li>
  51.  * <li>s : seconds</li>
  52.  * </ul>
  53.  * <p>
  54.  * Here are some examples.
  55.  * </p>
  56.  * <ul>
  57.  * <li><code>[now]</code> : current date time.</li>
  58.  * <li><code>[now-1d]</code> : the same time yesterday.</li>
  59.  * <li><code>[now+1y+1M-2h]</code> : a year and a month from today, two hours
  60.  * earlier.</li>
  61.  * <li><code>[now+1d 10:00]</code> : 10 o'clock tomorrow.</li>
  62.  * </ul>
  63.  */
  64. public class RelativeDateTimeParser
  65. {
  66.     private static final Pattern inputPattern = Pattern.compile(
  67.             "^\\[[nN][oO][wW]\\s*(([-+][0-9]+[yMdhms]\\s*)*)([0-9:]*)?\\]$");
  68.     private static final int GROUP_DIFFS = 1;
  69.     private static final int GROUP_TIME = 3;
  70.     private static final Pattern diffPattern =
  71.             Pattern.compile("([+-][0-9]+[yMdhms])");

  72.     private Clock clock;
  73.     private LocalDateTime now;

  74.     public RelativeDateTimeParser()
  75.     {
  76.         // Use fixed clock to provide consistent 'now' values.
  77.         this(Clock.fixed(Instant.now(), ZoneId.systemDefault()));
  78.     }

  79.     public RelativeDateTimeParser(Clock clock)
  80.     {
  81.         this.clock = clock;
  82.         cacheLocalDateTime(clock);
  83.     }

  84.     public LocalDateTime parse(String input)
  85.     {
  86.         if (input == null || input.isEmpty())
  87.         {
  88.             throw new IllegalArgumentException(
  89.                     "Relative datetime input must not be null or empty.");
  90.         }

  91.         Matcher matcher = inputPattern.matcher(input);
  92.         if (!matcher.matches())
  93.         {
  94.             throw new IllegalArgumentException("'" + input
  95.                     + "' does not match the expected pattern [now{diff}{time}]. "
  96.                     + "Please see the data types documentation for the details. "
  97.                     + "http://dbunit.sourceforge.net/datatypes.html#relativedatetime");
  98.         }

  99.         LocalDateTime datetime = initLocalDateTime(matcher);

  100.         String diffStr = matcher.group(GROUP_DIFFS);
  101.         if (diffStr.isEmpty())
  102.         {
  103.             return datetime;
  104.         }

  105.         Matcher diffMatcher = diffPattern.matcher(diffStr);
  106.         while (diffMatcher.find())
  107.         {
  108.             String diff = diffMatcher.group();
  109.             int amountLength = diff.length() - 1;
  110.             TemporalUnit unit = resolveUnit(diff.charAt(amountLength));
  111.             long amount = Long.parseLong(diff.substring(0, amountLength));
  112.             datetime = datetime.plus(amount, unit);
  113.         }
  114.         return datetime;
  115.     }

  116.     public Clock getClock()
  117.     {
  118.         return clock;
  119.     }

  120.     public void setClock(Clock clock)
  121.     {
  122.         this.clock = clock;
  123.         cacheLocalDateTime(clock);
  124.     }

  125.     private LocalDateTime initLocalDateTime(Matcher matcher)
  126.     {
  127.         String timeStr = matcher.group(GROUP_TIME);
  128.         if (timeStr.isEmpty())
  129.         {
  130.             return now;
  131.         } else
  132.         {
  133.             LocalTime time = LocalTime.parse(timeStr);
  134.             return LocalDateTime.of(now.toLocalDate(), time);
  135.         }
  136.     }

  137.     private static TemporalUnit resolveUnit(char c)
  138.     {
  139.         switch (c)
  140.         {
  141.         case 'y':
  142.             return ChronoUnit.YEARS;
  143.         case 'M':
  144.             return ChronoUnit.MONTHS;
  145.         case 'd':
  146.             return ChronoUnit.DAYS;
  147.         case 'h':
  148.             return ChronoUnit.HOURS;
  149.         case 'm':
  150.             return ChronoUnit.MINUTES;
  151.         case 's':
  152.             return ChronoUnit.SECONDS;
  153.         default:
  154.             throw new IllegalArgumentException("'" + c
  155.                     + "' is not a valid unit. It has to be one of 'yMdhms'.");
  156.         }
  157.     }

  158.     private void cacheLocalDateTime(Clock clock)
  159.     {
  160.         this.now = LocalDateTime.now(clock);
  161.     }
  162. }