PageRenderTime 1580ms CodeModel.GetById 181ms app.highlight 644ms RepoModel.GetById 740ms app.codeStats 1ms

/framework/src/play-java/src/main/java/play/libs/Time.java

https://github.com/schleichardt/Play20
Java | 1591 lines | 1115 code | 156 blank | 320 comment | 454 complexity | 3d233dcb061e37456b2123688e368c8b MD5 | raw file

Large files files are truncated, but you can click here to view the full file

   1/*
   2 * Copyright (C) 2009-2013 Typesafe Inc. <http://www.typesafe.com>
   3 */
   4package play.libs;
   5
   6import java.io.Serializable;
   7import java.text.ParseException;
   8import java.util.Calendar;
   9import java.util.Date;
  10import java.util.HashMap;
  11import java.util.Iterator;
  12import java.util.Locale;
  13import java.util.Map;
  14import java.util.SortedSet;
  15import java.util.StringTokenizer;
  16import java.util.TimeZone;
  17import java.util.TreeSet;
  18import java.util.regex.Matcher;
  19import java.util.regex.Pattern;
  20
  21/**
  22 * Time utilities.
  23 */
  24public class Time {
  25
  26    static Pattern days = Pattern.compile("^([0-9]+)d$");
  27    static Pattern hours = Pattern.compile("^([0-9]+)h$");
  28    static Pattern minutes = Pattern.compile("^([0-9]+)mi?n$");
  29    static Pattern seconds = Pattern.compile("^([0-9]+)s$");
  30
  31    /**
  32     * Parses a duration.
  33     * 
  34     * @param duration a quantity of time, such as 3h, 2mn, 7s
  35     * @return the length of the duration in seconds
  36     */
  37    public static int parseDuration(String duration) {
  38        if (duration == null) {
  39            return 60 * 60 * 24 * 30;
  40        }
  41        int toAdd = -1;
  42        if (days.matcher(duration).matches()) {
  43            Matcher matcher = days.matcher(duration);
  44            matcher.matches();
  45            toAdd = Integer.parseInt(matcher.group(1)) * (60 * 60) * 24;
  46        } else if (hours.matcher(duration).matches()) {
  47            Matcher matcher = hours.matcher(duration);
  48            matcher.matches();
  49            toAdd = Integer.parseInt(matcher.group(1)) * (60 * 60);
  50        } else if (minutes.matcher(duration).matches()) {
  51            Matcher matcher = minutes.matcher(duration);
  52            matcher.matches();
  53            toAdd = Integer.parseInt(matcher.group(1)) * (60);
  54        } else if (seconds.matcher(duration).matches()) {
  55            Matcher matcher = seconds.matcher(duration);
  56            matcher.matches();
  57            toAdd = Integer.parseInt(matcher.group(1));
  58        }
  59        if (toAdd == -1) {
  60            throw new IllegalArgumentException("Invalid duration pattern : " + duration);
  61        }
  62        return toAdd;
  63    }
  64
  65    /**
  66     * Parses a CRON expression.
  67     *
  68     * @param cron the CRON String
  69     * @return the next <code>Date</code> that satisfies the expression
  70     */
  71    public static Date parseCRONExpression(String cron) {
  72        try {
  73            return new CronExpression(cron).getNextValidTimeAfter(new Date());
  74        } catch (Exception e) {
  75            throw new IllegalArgumentException("Invalid CRON pattern : " + cron, e);
  76        }
  77    }
  78
  79    /**
  80     * Computes the number of milliseconds between the next valid date and the one after.
  81     * 
  82     * @param cron the CRON String
  83     * @return the number of milliseconds between the next valid date and the one after,
  84     * with an invalid interval between
  85     */
  86    public static long cronInterval(String cron) {
  87        return cronInterval(cron, new Date());
  88    }
  89
  90    /**
  91     * Compute the number of milliseconds between the next valid date and the one after.
  92     * 
  93     * @param cron the CRON String
  94     * @param date the date to start search
  95     * @return the number of milliseconds between the next valid date and the one after,
  96     * with an invalid interval between
  97     */
  98    public static long cronInterval(String cron, Date date) {
  99        try {
 100            return new CronExpression(cron).getNextInterval(date);
 101        } catch (Exception e) {
 102            throw new IllegalArgumentException("Invalid CRON pattern : " + cron, e);
 103        }
 104    }
 105
 106    /**
 107     * Thanks to Quartz project, https://quartz.dev.java.net
 108     * <P>
 109     * Provides a parser and evaluator for unix-like cron expressions. Cron 
 110     * expressions provide the ability to specify complex time combinations such as
 111     * &quot;At 8:00am every Monday through Friday&quot; or &quot;At 1:30am every 
 112     * last Friday of the month&quot;. 
 113     * <P>
 114     * Cron expressions are comprised of 6 required fields and one optional field
 115     * separated by white space. The fields respectively are described as follows:
 116     * 
 117     * <table cellspacing="8" summary="cron expression examples">
 118     * <tr>
 119     * <th align="left">Field Name</th>
 120     * <th align="left">&nbsp;</th>
 121     * <th align="left">Allowed Values</th>
 122     * <th align="left">&nbsp;</th>
 123     * <th align="left">Allowed Special Characters</th>
 124     * </tr>
 125     * <tr>
 126     * <td align="left"><code>Seconds</code></td>
 127     * <td align="left">&nbsp;</td>
 128     * <td align="left"><code>0-59</code></td>
 129     * <td align="left">&nbsp;</td>
 130     * <td align="left"><code>, - * /</code></td>
 131     * </tr>
 132     * <tr>
 133     * <td align="left"><code>Minutes</code></td>
 134     * <td align="left">&nbsp;</td>
 135     * <td align="left"><code>0-59</code></td>
 136     * <td align="left">&nbsp;</td>
 137     * <td align="left"><code>, - * /</code></td>
 138     * </tr>
 139     * <tr>
 140     * <td align="left"><code>Hours</code></td>
 141     * <td align="left">&nbsp;</td>
 142     * <td align="left"><code>0-23</code></td>
 143     * <td align="left">&nbsp;</td>
 144     * <td align="left"><code>, - * /</code></td>
 145     * </tr>
 146     * <tr>
 147     * <td align="left"><code>Day-of-month</code></td>
 148     * <td align="left">&nbsp;</td>
 149     * <td align="left"><code>1-31</code></td>
 150     * <td align="left">&nbsp;</td>
 151     * <td align="left"><code>, - * ? / L W</code></td>
 152     * </tr>
 153     * <tr>
 154     * <td align="left"><code>Month</code></td>
 155     * <td align="left">&nbsp;</td>
 156     * <td align="left"><code>1-12 or JAN-DEC</code></td>
 157     * <td align="left">&nbsp;</td>
 158     * <td align="left"><code>, - * /</code></td>
 159     * </tr>
 160     * <tr>
 161     * <td align="left"><code>Day-of-Week</code></td>
 162     * <td align="left">&nbsp;</td>
 163     * <td align="left"><code>1-7 or SUN-SAT</code></td>
 164     * <td align="left">&nbsp;</td>
 165     * <td align="left"><code>, - * ? / L #</code></td>
 166     * </tr>
 167     * <tr>
 168     * <td align="left"><code>Year (Optional)</code></td>
 169     * <td align="left">&nbsp;</td>
 170     * <td align="left"><code>empty, 1970-2099</code></td>
 171     * <td align="left">&nbsp;</td>
 172     * <td align="left"><code>, - * /</code></td>
 173     * </tr>
 174     * </table>
 175     * <P>
 176     * The '*' character is used to specify all values. For example, &quot;*&quot; 
 177     * in the minute field means &quot;every minute&quot;.
 178     * <P>
 179     * The '?' character is allowed for the day-of-month and day-of-week fields. It
 180     * is used to specify 'no specific value'. This is useful when you need to
 181     * specify something in one of the two fileds, but not the other.
 182     * <P>
 183     * The '-' character is used to specify ranges For example &quot;10-12&quot; in
 184     * the hour field means &quot;the hours 10, 11 and 12&quot;.
 185     * <P>
 186     * The ',' character is used to specify additional values. For example
 187     * &quot;MON,WED,FRI&quot; in the day-of-week field means &quot;the days Monday,
 188     * Wednesday, and Friday&quot;.
 189     * <P>
 190     * The '/' character is used to specify increments. For example &quot;0/15&quot;
 191     * in the seconds field means &quot;the seconds 0, 15, 30, and 45&quot;. And 
 192     * &quot;5/15&quot; in the seconds field means &quot;the seconds 5, 20, 35, and
 193     * 50&quot;.  Specifying '*' before the  '/' is equivalent to specifying 0 is
 194     * the value to start with. Essentially, for each field in the expression, there
 195     * is a set of numbers that can be turned on or off. For seconds and minutes, 
 196     * the numbers range from 0 to 59. For hours 0 to 23, for days of the month 0 to
 197     * 31, and for months 1 to 12. The &quot;/&quot; character simply helps you turn
 198     * on every &quot;nth&quot; value in the given set. Thus &quot;7/6&quot; in the
 199     * month field only turns on month &quot;7&quot;, it does NOT mean every 6th 
 200     * month, please note that subtlety.  
 201     * <P>
 202     * The 'L' character is allowed for the day-of-month and day-of-week fields.
 203     * This character is short-hand for &quot;last&quot;, but it has different 
 204     * meaning in each of the two fields. For example, the value &quot;L&quot; in 
 205     * the day-of-month field means &quot;the last day of the month&quot; - day 31 
 206     * for January, day 28 for February on non-leap years. If used in the 
 207     * day-of-week field by itself, it simply means &quot;7&quot; or 
 208     * &quot;SAT&quot;. But if used in the day-of-week field after another value, it
 209     * means &quot;the last xxx day of the month&quot; - for example &quot;6L&quot;
 210     * means &quot;the last friday of the month&quot;. When using the 'L' option, it
 211     * is important not to specify lists, or ranges of values, as you'll get 
 212     * confusing results.
 213     * <P>
 214     * The 'W' character is allowed for the day-of-month field.  This character 
 215     * is used to specify the weekday (Monday-Friday) nearest the given day.  As an 
 216     * example, if you were to specify &quot;15W&quot; as the value for the 
 217     * day-of-month field, the meaning is: &quot;the nearest weekday to the 15th of
 218     * the month&quot;. So if the 15th is a Saturday, the trigger will fire on 
 219     * Friday the 14th. If the 15th is a Sunday, the trigger will fire on Monday the
 220     * 16th. If the 15th is a Tuesday, then it will fire on Tuesday the 15th. 
 221     * However if you specify &quot;1W&quot; as the value for day-of-month, and the
 222     * 1st is a Saturday, the trigger will fire on Monday the 3rd, as it will not 
 223     * 'jump' over the boundary of a month's days.  The 'W' character can only be 
 224     * specified when the day-of-month is a single day, not a range or list of days.
 225     * <P>
 226     * The 'L' and 'W' characters can also be combined for the day-of-month 
 227     * expression to yield 'LW', which translates to &quot;last weekday of the 
 228     * month&quot;.
 229     * <P>
 230     * The '#' character is allowed for the day-of-week field. This character is
 231     * used to specify &quot;the nth&quot; xxx day of the month. For example, the 
 232     * value of &quot;6#3&quot; in the day-of-week field means the third Friday of 
 233     * the month (day 6 = Friday and &quot;#3&quot; = the 3rd one in the month). 
 234     * Other examples: &quot;2#1&quot; = the first Monday of the month and 
 235     * &quot;4#5&quot; = the fifth Wednesday of the month. Note that if you specify
 236     * &quot;#5&quot; and there is not 5 of the given day-of-week in the month, then
 237     * no firing will occur that month.
 238     * <P>
 239     * <!--The 'C' character is allowed for the day-of-month and day-of-week fields.
 240     * This character is short-hand for "calendar". This means values are
 241     * calculated against the associated calendar, if any. If no calendar is
 242     * associated, then it is equivalent to having an all-inclusive calendar. A
 243     * value of "5C" in the day-of-month field means "the first day included by the
 244     * calendar on or after the 5th". A value of "1C" in the day-of-week field
 245     * means "the first day included by the calendar on or after sunday".-->
 246     * <P>
 247     * The legal characters and the names of months and days of the week are not
 248     * case sensitive.
 249     * 
 250     * <p>
 251     * <b>NOTES:</b>
 252     * <ul>
 253     * <li>Support for specifying both a day-of-week and a day-of-month value is
 254     * not complete (you'll need to use the '?' character in on of these fields).
 255     * </li>
 256     * </ul>
 257     *
 258     * 
 259     * @author Sharada Jambula, James House
 260     * @author Contributions from Mads Henderson
 261     * @author Refactoring from CronTrigger to CronExpression by Aaron Craven
 262     */
 263    public static class CronExpression implements Serializable, Cloneable {
 264
 265        private static final long serialVersionUID = 12423409423L;
 266        protected static final int SECOND = 0;
 267        protected static final int MINUTE = 1;
 268        protected static final int HOUR = 2;
 269        protected static final int DAY_OF_MONTH = 3;
 270        protected static final int MONTH = 4;
 271        protected static final int DAY_OF_WEEK = 5;
 272        protected static final int YEAR = 6;
 273        protected static final int ALL_SPEC_INT = 99; // '*'
 274        protected static final int NO_SPEC_INT = 98; // '?'
 275        protected static final Integer ALL_SPEC = new Integer(ALL_SPEC_INT);
 276        protected static final Integer NO_SPEC = new Integer(NO_SPEC_INT);
 277        protected static Map<String, Integer> monthMap = new HashMap<String, Integer>(20);
 278        protected static Map<String, Integer> dayMap = new HashMap<String, Integer>(60);
 279
 280        static {
 281            monthMap.put("JAN", new Integer(0));
 282            monthMap.put("FEB", new Integer(1));
 283            monthMap.put("MAR", new Integer(2));
 284            monthMap.put("APR", new Integer(3));
 285            monthMap.put("MAY", new Integer(4));
 286            monthMap.put("JUN", new Integer(5));
 287            monthMap.put("JUL", new Integer(6));
 288            monthMap.put("AUG", new Integer(7));
 289            monthMap.put("SEP", new Integer(8));
 290            monthMap.put("OCT", new Integer(9));
 291            monthMap.put("NOV", new Integer(10));
 292            monthMap.put("DEC", new Integer(11));
 293
 294            dayMap.put("SUN", new Integer(1));
 295            dayMap.put("MON", new Integer(2));
 296            dayMap.put("TUE", new Integer(3));
 297            dayMap.put("WED", new Integer(4));
 298            dayMap.put("THU", new Integer(5));
 299            dayMap.put("FRI", new Integer(6));
 300            dayMap.put("SAT", new Integer(7));
 301        }
 302        private String cronExpression = null;
 303        private TimeZone timeZone = null;
 304        protected transient TreeSet<Integer> seconds;
 305        protected transient TreeSet<Integer> minutes;
 306        protected transient TreeSet<Integer> hours;
 307        protected transient TreeSet<Integer> daysOfMonth;
 308        protected transient TreeSet<Integer> months;
 309        protected transient TreeSet<Integer> daysOfWeek;
 310        protected transient TreeSet<Integer> years;
 311        protected transient boolean lastdayOfWeek = false;
 312        protected transient int nthdayOfWeek = 0;
 313        protected transient boolean lastdayOfMonth = false;
 314        protected transient boolean nearestWeekday = false;
 315        protected transient boolean expressionParsed = false;
 316
 317        /**
 318         * Constructs a new <CODE>CronExpression</CODE> based on the specified 
 319         * parameter.
 320         * 
 321         * @param cronExpression String representation of the cron expression the
 322         *                       new object should represent
 323         * @throws java.text.ParseException
 324         *         if the string expression cannot be parsed into a valid 
 325         *         <CODE>CronExpression</CODE>
 326         */
 327        public CronExpression(String cronExpression) throws ParseException {
 328            if (cronExpression == null) {
 329                throw new IllegalArgumentException("cronExpression cannot be null");
 330            }
 331
 332            this.cronExpression = cronExpression;
 333
 334            buildExpression(cronExpression.toUpperCase(Locale.US));
 335        }
 336
 337        /**
 338         * Indicates whether the given date satisfies the cron expression. Note that
 339         * milliseconds are ignored, so two Dates falling on different milliseconds
 340         * of the same second will always have the same result here.
 341         * 
 342         * @param date the date to evaluate
 343         * @return a boolean indicating whether the given date satisfies the cron
 344         *         expression
 345         */
 346        public boolean isSatisfiedBy(Date date) {
 347            Calendar testDateCal = Calendar.getInstance();
 348            testDateCal.setTime(date);
 349            testDateCal.set(Calendar.MILLISECOND, 0);
 350            Date originalDate = testDateCal.getTime();
 351
 352            testDateCal.add(Calendar.SECOND, -1);
 353
 354            Date timeAfter = getTimeAfter(testDateCal.getTime());
 355
 356            return ((timeAfter != null) && (timeAfter.equals(originalDate)));
 357        }
 358
 359        /**
 360         * Returns the next date/time <I>after</I> the given date/time which
 361         * satisfies the cron expression.
 362         * 
 363         * @param date the date/time at which to begin the search for the next valid
 364         *             date/time
 365         * @return the next valid date/time
 366         */
 367        public Date getNextValidTimeAfter(Date date) {
 368            return getTimeAfter(date);
 369        }
 370
 371        /**
 372         * Returns the next date/time <I>after</I> the given date/time which does
 373         * <I>not</I> satisfy the expression
 374         * 
 375         * @param date the date/time at which to begin the search for the next 
 376         *             invalid date/time
 377         * @return the next valid date/time
 378         */
 379        public Date getNextInvalidTimeAfter(Date date) {
 380            long difference = 1000;
 381
 382            //move back to the nearest second so differences will be accurate
 383            Calendar adjustCal = Calendar.getInstance();
 384            adjustCal.setTime(date);
 385            adjustCal.set(Calendar.MILLISECOND, 0);
 386            Date lastDate = adjustCal.getTime();
 387
 388            Date newDate = null;
 389
 390            //keep getting the next included time until it's farther than one second
 391            // apart. At that point, lastDate is the last valid fire time. We return
 392            // the second immediately following it.
 393            while (difference == 1000) {
 394                newDate = getTimeAfter(lastDate);
 395
 396                difference = newDate.getTime() - lastDate.getTime();
 397
 398                if (difference == 1000) {
 399                    lastDate = newDate;
 400                }
 401            }
 402
 403            return new Date(lastDate.getTime() + 1000);
 404        }
 405
 406        /**
 407         * Return the interval between the next valid date and the one after
 408         * @param date the date/time at which to begin the search
 409         * @return the number of milliseconds between the next valid and the one after
 410         */
 411        public long getNextInterval(Date date) {
 412            Date nextValid = getNextValidTimeAfter(date);
 413            Date nextInvalid = getNextInvalidTimeAfter(nextValid);
 414            Date nextNextValid = getNextValidTimeAfter(nextInvalid);
 415            return nextNextValid.getTime() - nextValid.getTime();
 416        }
 417
 418        /**
 419         * Returns the time zone for which this <code>CronExpression</code> 
 420         * will be resolved.
 421         */
 422        public TimeZone getTimeZone() {
 423            if (timeZone == null) {
 424                timeZone = TimeZone.getDefault();
 425            }
 426
 427            return timeZone;
 428        }
 429
 430        /**
 431         * Sets the time zone for which  this <code>CronExpression</code> 
 432         * will be resolved.
 433         */
 434        public void setTimeZone(TimeZone timeZone) {
 435            this.timeZone = timeZone;
 436        }
 437
 438        /**
 439         * Returns the string representation of the <CODE>CronExpression</CODE>
 440         * 
 441         * @return a string representation of the <CODE>CronExpression</CODE>
 442         */
 443        @Override
 444        public String toString() {
 445            return cronExpression;
 446        }
 447
 448        /**
 449         * Indicates whether the specified cron expression can be parsed into a 
 450         * valid cron expression
 451         * 
 452         * @param cronExpression the expression to evaluate
 453         * @return a boolean indicating whether the given expression is a valid cron
 454         *         expression
 455         */
 456        public static boolean isValidExpression(String cronExpression) {
 457
 458            try {
 459                new CronExpression(cronExpression);
 460            } catch (ParseException pe) {
 461                return false;
 462            }
 463
 464            return true;
 465        }
 466        ////////////////////////////////////////////////////////////////////////////
 467        //
 468        // Expression Parsing Functions
 469        //
 470        ////////////////////////////////////////////////////////////////////////////
 471        protected void buildExpression(String expression) throws ParseException {
 472            expressionParsed = true;
 473
 474            try {
 475
 476                if (seconds == null) {
 477                    seconds = new TreeSet<Integer>();
 478                }
 479                if (minutes == null) {
 480                    minutes = new TreeSet<Integer>();
 481                }
 482                if (hours == null) {
 483                    hours = new TreeSet<Integer>();
 484                }
 485                if (daysOfMonth == null) {
 486                    daysOfMonth = new TreeSet<Integer>();
 487                }
 488                if (months == null) {
 489                    months = new TreeSet<Integer>();
 490                }
 491                if (daysOfWeek == null) {
 492                    daysOfWeek = new TreeSet<Integer>();
 493                }
 494                if (years == null) {
 495                    years = new TreeSet<Integer>();
 496                }
 497
 498                int exprOn = SECOND;
 499
 500                StringTokenizer exprsTok = new StringTokenizer(expression, " \t",
 501                        false);
 502
 503                while (exprsTok.hasMoreTokens() && exprOn <= YEAR) {
 504                    String expr = exprsTok.nextToken().trim();
 505                    StringTokenizer vTok = new StringTokenizer(expr, ",");
 506                    while (vTok.hasMoreTokens()) {
 507                        String v = vTok.nextToken();
 508                        storeExpressionVals(0, v, exprOn);
 509                    }
 510
 511                    exprOn++;
 512                }
 513
 514                if (exprOn <= DAY_OF_WEEK) {
 515                    throw new ParseException("Unexpected end of expression.",
 516                            expression.length());
 517                }
 518
 519                if (exprOn <= YEAR) {
 520                    storeExpressionVals(0, "*", YEAR);
 521                }
 522
 523            } catch (ParseException pe) {
 524                throw pe;
 525            } catch (Exception e) {
 526                throw new ParseException("Illegal cron expression format (" + e.toString() + ")", 0);
 527            }
 528        }
 529
 530        protected int storeExpressionVals(int pos, String s, int type)
 531        throws ParseException {
 532
 533            int incr = 0;
 534            int i = skipWhiteSpace(pos, s);
 535            if (i >= s.length()) {
 536                return i;
 537            }
 538            char c = s.charAt(i);
 539            if ((c >= 'A') && (c <= 'Z') && (!s.equals("L")) && (!s.equals("LW"))) {
 540                String sub = s.substring(i, i + 3);
 541                int sval = -1;
 542                int eval = -1;
 543                if (type == MONTH) {
 544                    sval = getMonthNumber(sub) + 1;
 545                    if (sval < 0) {
 546                        throw new ParseException("Invalid Month value: '" + sub + "'", i);
 547                    }
 548                    if (s.length() > i + 3) {
 549                        c = s.charAt(i + 3);
 550                        if (c == '-') {
 551                            i += 4;
 552                            sub = s.substring(i, i + 3);
 553                            eval = getMonthNumber(sub) + 1;
 554                            if (eval < 0) {
 555                                throw new ParseException("Invalid Month value: '" + sub + "'", i);
 556                            }
 557                        }
 558                    }
 559                } else if (type == DAY_OF_WEEK) {
 560                    sval = getDayOfWeekNumber(sub);
 561                    if (sval < 0) {
 562                        throw new ParseException("Invalid Day-of-Week value: '" + sub + "'", i);
 563                    }
 564                    if (s.length() > i + 3) {
 565                        c = s.charAt(i + 3);
 566                        if (c == '-') {
 567                            i += 4;
 568                            sub = s.substring(i, i + 3);
 569                            eval = getDayOfWeekNumber(sub);
 570                            if (eval < 0) {
 571                                throw new ParseException(
 572                                        "Invalid Day-of-Week value: '" + sub + "'", i);
 573                            }
 574                            if (sval > eval) {
 575                                throw new ParseException(
 576                                        "Invalid Day-of-Week sequence: " + sval + " > " + eval, i);
 577                            }
 578                        } else if (c == '#') {
 579                            try {
 580                                i += 4;
 581                                nthdayOfWeek = Integer.parseInt(s.substring(i));
 582                                if (nthdayOfWeek < 1 || nthdayOfWeek > 5) {
 583                                    throw new Exception();
 584                                }
 585                            } catch (Exception e) {
 586                                throw new ParseException(
 587                                        "A numeric value between 1 and 5 must follow the '#' option",
 588                                        i);
 589                            }
 590                        } else if (c == 'L') {
 591                            lastdayOfWeek = true;
 592                            i++;
 593                        }
 594                    }
 595
 596                } else {
 597                    throw new ParseException(
 598                            "Illegal characters for this position: '" + sub + "'",
 599                            i);
 600                }
 601                if (eval != -1) {
 602                    incr = 1;
 603                }
 604                addToSet(sval, eval, incr, type);
 605                return (i + 3);
 606            }
 607
 608            if (c == '?') {
 609                i++;
 610                if ((i + 1) < s.length() && (s.charAt(i) != ' ' && s.charAt(i + 1) != '\t')) {
 611                    throw new ParseException("Illegal character after '?': " + s.charAt(i), i);
 612                }
 613                if (type != DAY_OF_WEEK && type != DAY_OF_MONTH) {
 614                    throw new ParseException(
 615                            "'?' can only be specfied for Day-of-Month or Day-of-Week.",
 616                            i);
 617                }
 618                if (type == DAY_OF_WEEK && !lastdayOfMonth) {
 619                    int val = daysOfMonth.last().intValue();
 620                    if (val == NO_SPEC_INT) {
 621                        throw new ParseException(
 622                                "'?' can only be specfied for Day-of-Month -OR- Day-of-Week.",
 623                                i);
 624                    }
 625                }
 626
 627                addToSet(NO_SPEC_INT, -1, 0, type);
 628                return i;
 629            }
 630
 631            if (c == '*' || c == '/') {
 632                if (c == '*' && (i + 1) >= s.length()) {
 633                    addToSet(ALL_SPEC_INT, -1, incr, type);
 634                    return i + 1;
 635                } else if (c == '/' && ((i + 1) >= s.length() || s.charAt(i + 1) == ' ' || s.charAt(i + 1) == '\t')) {
 636                    throw new ParseException("'/' must be followed by an integer.", i);
 637                } else if (c == '*') {
 638                    i++;
 639                }
 640                c = s.charAt(i);
 641                if (c == '/') { // is an increment specified?
 642                    i++;
 643                    if (i >= s.length()) {
 644                        throw new ParseException("Unexpected end of string.", i);
 645                    }
 646
 647                    incr = getNumericValue(s, i);
 648
 649                    i++;
 650                    if (incr > 10) {
 651                        i++;
 652                    }
 653                    if (incr > 59 && (type == SECOND || type == MINUTE)) {
 654                        throw new ParseException("Increment > 60 : " + incr, i);
 655                    } else if (incr > 23 && (type == HOUR)) {
 656                        throw new ParseException("Increment > 24 : " + incr, i);
 657                    } else if (incr > 31 && (type == DAY_OF_MONTH)) {
 658                        throw new ParseException("Increment > 31 : " + incr, i);
 659                    } else if (incr > 7 && (type == DAY_OF_WEEK)) {
 660                        throw new ParseException("Increment > 7 : " + incr, i);
 661                    } else if (incr > 12 && (type == MONTH)) {
 662                        throw new ParseException("Increment > 12 : " + incr, i);
 663                    }
 664                } else {
 665                    incr = 1;
 666                }
 667
 668                addToSet(ALL_SPEC_INT, -1, incr, type);
 669                return i;
 670            } else if (c == 'L') {
 671                i++;
 672                if (type == DAY_OF_MONTH) {
 673                    lastdayOfMonth = true;
 674                }
 675                if (type == DAY_OF_WEEK) {
 676                    addToSet(7, 7, 0, type);
 677                }
 678                if (type == DAY_OF_MONTH && s.length() > i) {
 679                    c = s.charAt(i);
 680                    if (c == 'W') {
 681                        nearestWeekday = true;
 682                        i++;
 683                    }
 684                }
 685                return i;
 686            } else if (c >= '0' && c <= '9') {
 687                int val = Integer.parseInt(String.valueOf(c));
 688                i++;
 689                if (i >= s.length()) {
 690                    addToSet(val, -1, -1, type);
 691                } else {
 692                    c = s.charAt(i);
 693                    if (c >= '0' && c <= '9') {
 694                        ValueSet vs = getValue(val, s, i);
 695                        val = vs.value;
 696                        i = vs.pos;
 697                    }
 698                    i = checkNext(i, s, val, type);
 699                    return i;
 700                }
 701            } else {
 702                throw new ParseException("Unexpected character: " + c, i);
 703            }
 704
 705            return i;
 706        }
 707
 708        protected int checkNext(int pos, String s, int val, int type)
 709        throws ParseException {
 710
 711            int end = -1;
 712            int i = pos;
 713
 714            if (i >= s.length()) {
 715                addToSet(val, end, -1, type);
 716                return i;
 717            }
 718
 719            char c = s.charAt(pos);
 720
 721            if (c == 'L') {
 722                if (type == DAY_OF_WEEK) {
 723                    lastdayOfWeek = true;
 724                } else {
 725                    throw new ParseException("'L' option is not valid here. (pos=" + i + ")", i);
 726                }
 727                TreeSet<Integer> set = getSet(type);
 728                set.add(new Integer(val));
 729                i++;
 730                return i;
 731            }
 732
 733            if (c == 'W') {
 734                if (type == DAY_OF_MONTH) {
 735                    nearestWeekday = true;
 736                } else {
 737                    throw new ParseException("'W' option is not valid here. (pos=" + i + ")", i);
 738                }
 739                TreeSet<Integer> set = getSet(type);
 740                set.add(new Integer(val));
 741                i++;
 742                return i;
 743            }
 744
 745            if (c == '#') {
 746                if (type != DAY_OF_WEEK) {
 747                    throw new ParseException("'#' option is not valid here. (pos=" + i + ")", i);
 748                }
 749                i++;
 750                try {
 751                    nthdayOfWeek = Integer.parseInt(s.substring(i));
 752                    if (nthdayOfWeek < 1 || nthdayOfWeek > 5) {
 753                        throw new Exception();
 754                    }
 755                } catch (Exception e) {
 756                    throw new ParseException(
 757                            "A numeric value between 1 and 5 must follow the '#' option",
 758                            i);
 759                }
 760
 761                TreeSet<Integer> set = getSet(type);
 762                set.add(new Integer(val));
 763                i++;
 764                return i;
 765            }
 766
 767            if (c == '-') {
 768                i++;
 769                c = s.charAt(i);
 770                int v = Integer.parseInt(String.valueOf(c));
 771                end = v;
 772                i++;
 773                if (i >= s.length()) {
 774                    addToSet(val, end, 1, type);
 775                    return i;
 776                }
 777                c = s.charAt(i);
 778                if (c >= '0' && c <= '9') {
 779                    ValueSet vs = getValue(v, s, i);
 780                    int v1 = vs.value;
 781                    end = v1;
 782                    i = vs.pos;
 783                }
 784                if (i < s.length() && ((c = s.charAt(i)) == '/')) {
 785                    i++;
 786                    c = s.charAt(i);
 787                    int v2 = Integer.parseInt(String.valueOf(c));
 788                    i++;
 789                    if (i >= s.length()) {
 790                        addToSet(val, end, v2, type);
 791                        return i;
 792                    }
 793                    c = s.charAt(i);
 794                    if (c >= '0' && c <= '9') {
 795                        ValueSet vs = getValue(v2, s, i);
 796                        int v3 = vs.value;
 797                        addToSet(val, end, v3, type);
 798                        i = vs.pos;
 799                        return i;
 800                    } else {
 801                        addToSet(val, end, v2, type);
 802                        return i;
 803                    }
 804                } else {
 805                    addToSet(val, end, 1, type);
 806                    return i;
 807                }
 808            }
 809
 810            if (c == '/') {
 811                i++;
 812                c = s.charAt(i);
 813                int v2 = Integer.parseInt(String.valueOf(c));
 814                i++;
 815                if (i >= s.length()) {
 816                    addToSet(val, end, v2, type);
 817                    return i;
 818                }
 819                c = s.charAt(i);
 820                if (c >= '0' && c <= '9') {
 821                    ValueSet vs = getValue(v2, s, i);
 822                    int v3 = vs.value;
 823                    addToSet(val, end, v3, type);
 824                    i = vs.pos;
 825                    return i;
 826                } else {
 827                    throw new ParseException("Unexpected character '" + c + "' after '/'", i);
 828                }
 829            }
 830
 831            addToSet(val, end, 0, type);
 832            i++;
 833            return i;
 834        }
 835
 836        public String getCronExpression() {
 837            return cronExpression;
 838        }
 839
 840        public String getExpressionSummary() {
 841            StringBuffer buf = new StringBuffer();
 842
 843            buf.append("seconds: ");
 844            buf.append(getExpressionSetSummary(seconds));
 845            buf.append("\n");
 846            buf.append("minutes: ");
 847            buf.append(getExpressionSetSummary(minutes));
 848            buf.append("\n");
 849            buf.append("hours: ");
 850            buf.append(getExpressionSetSummary(hours));
 851            buf.append("\n");
 852            buf.append("daysOfMonth: ");
 853            buf.append(getExpressionSetSummary(daysOfMonth));
 854            buf.append("\n");
 855            buf.append("months: ");
 856            buf.append(getExpressionSetSummary(months));
 857            buf.append("\n");
 858            buf.append("daysOfWeek: ");
 859            buf.append(getExpressionSetSummary(daysOfWeek));
 860            buf.append("\n");
 861            buf.append("lastdayOfWeek: ");
 862            buf.append(lastdayOfWeek);
 863            buf.append("\n");
 864            buf.append("nearestWeekday: ");
 865            buf.append(nearestWeekday);
 866            buf.append("\n");
 867            buf.append("NthDayOfWeek: ");
 868            buf.append(nthdayOfWeek);
 869            buf.append("\n");
 870            buf.append("lastdayOfMonth: ");
 871            buf.append(lastdayOfMonth);
 872            buf.append("\n");
 873            buf.append("years: ");
 874            buf.append(getExpressionSetSummary(years));
 875            buf.append("\n");
 876
 877            return buf.toString();
 878        }
 879
 880        protected String getExpressionSetSummary(java.util.Set<Integer> set) {
 881
 882            if (set.contains(NO_SPEC)) {
 883                return "?";
 884            }
 885            if (set.contains(ALL_SPEC)) {
 886                return "*";
 887            }
 888
 889            StringBuffer buf = new StringBuffer();
 890
 891            Iterator<Integer> itr = set.iterator();
 892            boolean first = true;
 893            while (itr.hasNext()) {
 894                Integer iVal = itr.next();
 895                String val = iVal.toString();
 896                if (!first) {
 897                    buf.append(",");
 898                }
 899                buf.append(val);
 900                first = false;
 901            }
 902
 903            return buf.toString();
 904        }
 905
 906        protected String getExpressionSetSummary(java.util.ArrayList<Integer> list) {
 907
 908            if (list.contains(NO_SPEC)) {
 909                return "?";
 910            }
 911            if (list.contains(ALL_SPEC)) {
 912                return "*";
 913            }
 914
 915            StringBuffer buf = new StringBuffer();
 916
 917            Iterator<Integer> itr = list.iterator();
 918            boolean first = true;
 919            while (itr.hasNext()) {
 920                Integer iVal = itr.next();
 921                String val = iVal.toString();
 922                if (!first) {
 923                    buf.append(",");
 924                }
 925                buf.append(val);
 926                first = false;
 927            }
 928
 929            return buf.toString();
 930        }
 931
 932        protected int skipWhiteSpace(int i, String s) {
 933            for (; i < s.length() && (s.charAt(i) == ' ' || s.charAt(i) == '\t'); i++) {
 934            }
 935
 936            return i;
 937        }
 938
 939        protected int findNextWhiteSpace(int i, String s) {
 940            for (; i < s.length() && (s.charAt(i) != ' ' || s.charAt(i) != '\t'); i++) {
 941            }
 942
 943            return i;
 944        }
 945
 946        protected void addToSet(int val, int end, int incr, int type)
 947        throws ParseException {
 948
 949            TreeSet<Integer> set = getSet(type);
 950
 951            if (type == SECOND || type == MINUTE) {
 952                if ((val < 0 || val > 59 || end > 59) && (val != ALL_SPEC_INT)) {
 953                    throw new ParseException(
 954                            "Minute and Second values must be between 0 and 59",
 955                            -1);
 956                }
 957            } else if (type == HOUR) {
 958                if ((val < 0 || val > 23 || end > 23) && (val != ALL_SPEC_INT)) {
 959                    throw new ParseException(
 960                            "Hour values must be between 0 and 23", -1);
 961                }
 962            } else if (type == DAY_OF_MONTH) {
 963                if ((val < 1 || val > 31 || end > 31) && (val != ALL_SPEC_INT) && (val != NO_SPEC_INT)) {
 964                    throw new ParseException(
 965                            "Day of month values must be between 1 and 31", -1);
 966                }
 967            } else if (type == MONTH) {
 968                if ((val < 1 || val > 12 || end > 12) && (val != ALL_SPEC_INT)) {
 969                    throw new ParseException(
 970                            "Month values must be between 1 and 12", -1);
 971                }
 972            } else if (type == DAY_OF_WEEK) {
 973                if ((val == 0 || val > 7 || end > 7) && (val != ALL_SPEC_INT) && (val != NO_SPEC_INT)) {
 974                    throw new ParseException(
 975                            "Day-of-Week values must be between 1 and 7", -1);
 976                }
 977            }
 978
 979            if ((incr == 0 || incr == -1) && val != ALL_SPEC_INT) {
 980                if (val != -1) {
 981                    set.add(new Integer(val));
 982                } else {
 983                    set.add(NO_SPEC);
 984                }
 985
 986                return;
 987            }
 988
 989            int startAt = val;
 990            int stopAt = end;
 991
 992            if (val == ALL_SPEC_INT && incr <= 0) {
 993                incr = 1;
 994                set.add(ALL_SPEC); // put in a marker, but also fill values
 995            }
 996
 997            if (type == SECOND || type == MINUTE) {
 998                if (stopAt == -1) {
 999                    stopAt = 59;
1000                }
1001                if (startAt == -1 || startAt == ALL_SPEC_INT) {
1002                    startAt = 0;
1003                }
1004            } else if (type == HOUR) {
1005                if (stopAt == -1) {
1006                    stopAt = 23;
1007                }
1008                if (startAt == -1 || startAt == ALL_SPEC_INT) {
1009                    startAt = 0;
1010                }
1011            } else if (type == DAY_OF_MONTH) {
1012                if (stopAt == -1) {
1013                    stopAt = 31;
1014                }
1015                if (startAt == -1 || startAt == ALL_SPEC_INT) {
1016                    startAt = 1;
1017                }
1018            } else if (type == MONTH) {
1019                if (stopAt == -1) {
1020                    stopAt = 12;
1021                }
1022                if (startAt == -1 || startAt == ALL_SPEC_INT) {
1023                    startAt = 1;
1024                }
1025            } else if (type == DAY_OF_WEEK) {
1026                if (stopAt == -1) {
1027                    stopAt = 7;
1028                }
1029                if (startAt == -1 || startAt == ALL_SPEC_INT) {
1030                    startAt = 1;
1031                }
1032            } else if (type == YEAR) {
1033                if (stopAt == -1) {
1034                    stopAt = 2099;
1035                }
1036                if (startAt == -1 || startAt == ALL_SPEC_INT) {
1037                    startAt = 1970;
1038                }
1039            }
1040
1041            for (int i = startAt; i <= stopAt; i += incr) {
1042                set.add(new Integer(i));
1043            }
1044        }
1045
1046        protected TreeSet<Integer> getSet(int type) {
1047            switch (type) {
1048            case SECOND:
1049                return seconds;
1050            case MINUTE:
1051                return minutes;
1052            case HOUR:
1053                return hours;
1054            case DAY_OF_MONTH:
1055                return daysOfMonth;
1056            case MONTH:
1057                return months;
1058            case DAY_OF_WEEK:
1059                return daysOfWeek;
1060            case YEAR:
1061                return years;
1062            default:
1063                return null;
1064            }
1065        }
1066
1067        protected ValueSet getValue(int v, String s, int i) {
1068            char c = s.charAt(i);
1069            String s1 = String.valueOf(v);
1070            while (c >= '0' && c <= '9') {
1071                s1 += c;
1072                i++;
1073                if (i >= s.length()) {
1074                    break;
1075                }
1076                c = s.charAt(i);
1077            }
1078            ValueSet val = new ValueSet();
1079
1080            val.pos = (i < s.length()) ? i : i + 1;
1081            val.value = Integer.parseInt(s1);
1082            return val;
1083        }
1084
1085        protected int getNumericValue(String s, int i) {
1086            int endOfVal = findNextWhiteSpace(i, s);
1087            String val = s.substring(i, endOfVal);
1088            return Integer.parseInt(val);
1089        }
1090
1091        protected int getMonthNumber(String s) {
1092            Integer integer = monthMap.get(s);
1093
1094            if (integer == null) {
1095                return -1;
1096            }
1097
1098            return integer.intValue();
1099        }
1100
1101        protected int getDayOfWeekNumber(String s) {
1102            Integer integer = dayMap.get(s);
1103
1104            if (integer == null) {
1105                return -1;
1106            }
1107
1108            return integer.intValue();
1109        }
1110
1111        ////////////////////////////////////////////////////////////////////////////
1112        //
1113        // Computation Functions
1114        //
1115        ////////////////////////////////////////////////////////////////////////////
1116        protected Date getTimeAfter(Date afterTime) {
1117
1118            Calendar cl = Calendar.getInstance(getTimeZone());
1119
1120            // move ahead one second, since we're computing the time *after* the
1121            // given time
1122            afterTime = new Date(afterTime.getTime() + 1000);
1123            // CronTrigger does not deal with milliseconds
1124            cl.setTime(afterTime);
1125            cl.set(Calendar.MILLISECOND, 0);
1126
1127            boolean gotOne = false;
1128            // loop until we've computed the next time, or we've past the endTime
1129            while (!gotOne) {
1130
1131                //if (endTime != null && cl.getTime().after(endTime)) return null;
1132
1133                SortedSet<Integer> st = null;
1134                int t = 0;
1135
1136                int sec = cl.get(Calendar.SECOND);
1137                int min = cl.get(Calendar.MINUTE);
1138
1139                // get second.................................................
1140                st = seconds.tailSet(new Integer(sec));
1141                if (st != null && st.size() != 0) {
1142                    sec = st.first().intValue();
1143                } else {
1144                    sec = seconds.first().intValue();
1145                    min++;
1146                    cl.set(Calendar.MINUTE, min);
1147                }
1148                cl.set(Calendar.SECOND, sec);
1149
1150                min = cl.get(Calendar.MINUTE);
1151                int hr = cl.get(Calendar.HOUR_OF_DAY);
1152                t = -1;
1153
1154                // get minute.................................................
1155                st = minutes.tailSet(new Integer(min));
1156                if (st != null && st.size() != 0) {
1157                    t = min;
1158                    min = st.first().intValue();
1159                } else {
1160                    min = minutes.first().intValue();
1161                    hr++;
1162                }
1163                if (min != t) {
1164                    cl.set(Calendar.SECOND, 0);
1165                    cl.set(Calendar.MINUTE, min);
1166                    setCalendarHour(cl, hr);
1167                    continue;
1168                }
1169                cl.set(Calendar.MINUTE, min);
1170
1171                hr = cl.get(Calendar.HOUR_OF_DAY);
1172                int day = cl.get(Calendar.DAY_OF_MONTH);
1173                t = -1;
1174
1175                // get hour...................................................
1176                st = hours.tailSet(new Integer(hr));
1177                if (st != null && st.size() != 0) {
1178                    t = hr;
1179                    hr = st.first().intValue();
1180                } else {
1181                    hr = hours.first().intValue();
1182                    day++;
1183                }
1184                if (hr != t) {
1185                    cl.set(Calendar.SECOND, 0);
1186                    cl.set(Calendar.MINUTE, 0);
1187                    cl.set(Calendar.DAY_OF_MONTH, day);
1188                    setCalendarHour(cl, hr);
1189                    continue;
1190                }
1191                cl.set(Calendar.HOUR_OF_DAY, hr);
1192
1193                day = cl.get(Calendar.DAY_OF_MONTH);
1194                int mon = cl.get(Calendar.MONTH) + 1;
1195                // '+ 1' because calendar is 0-based for this field, and we are
1196                // 1-based
1197                t = -1;
1198                int tmon = mon;
1199
1200                // get day...................................................
1201                boolean dayOfMSpec = !daysOfMonth.contains(NO_SPEC);
1202                boolean dayOfWSpec = !daysOfWeek.contains(NO_SPEC);
1203                if (dayOfMSpec && !dayOfWSpec) { // get day by day of month rule
1204                    st = daysOfMonth.tailSet(new Integer(day));
1205                    if (lastdayOfMonth) {
1206                        if (!nearestWeekday) {
1207                            t = day;
1208                            day = getLastDayOfMonth(mon, cl.get(Calendar.YEAR));
1209                        } else {
1210                            t = day;
1211                            day = getLastDayOfMonth(mon, cl.get(Calendar.YEAR));
1212
1213                            java.util.Calendar tcal = java.util.Calendar.getInstance();
1214                            tcal.set(Calendar.SECOND, 0);
1215                            tcal.set(Calendar.MINUTE, 0);
1216                            tcal.set(Calendar.HOUR_OF_DAY, 0);
1217                            tcal.set(Calendar.DAY_OF_MONTH, day);
1218                            tcal.set(Calendar.MONTH, mon - 1);
1219                            tcal.set(Calendar.YEAR, cl.get(Calendar.YEAR));
1220
1221                            int ldom = getLastDayOfMonth(mon, cl.get(Calendar.YEAR));
1222                            int dow = tcal.get(Calendar.DAY_OF_WEEK);
1223
1224                            if (dow == Calendar.SATURDAY && day == 1) {
1225                                day += 2;
1226                            } else if (dow == Calendar.SATURDAY) {
1227                                day -= 1;
1228                            } else if (dow == Calendar.SUNDAY && day == ldom) {
1229                                day -= 2;
1230                            } else if (dow == Calendar.SUNDAY) {
1231                                day += 1;
1232                            }
1233
1234                            tcal.set(Calendar.SECOND, sec);
1235                            tcal.set(Calendar.MINUTE, min);
1236                            tcal.set(Calendar.HOUR_OF_DAY, hr);
1237                            tcal.set(Calendar.DAY_OF_MONTH, day);
1238                            tcal.set(Calendar.MONTH, mon - 1);
1239                            Date nTime = tcal.getTime();
1240                            if (nTime.before(afterTime)) {
1241                                day = 1;
1242                                mon++;
1243                            }
1244                        }
1245                    } else if (nearestWeekday) {
1246                        t = day;
1247                        day = daysOfMonth.first().intValue();
1248
1249                        java.util.Calendar tcal = java.util.Calendar.getInstance();
1250                        tcal.set(Calendar.SECOND, 0);
1251                        tcal.set(Calendar.MINUTE, 0);
1252                        tcal.set(Calendar.HOUR_OF_DAY, 0);
1253                        tcal.set(Calendar.DAY_OF_MONTH, day);
1254                        tcal.set(Calendar.MONTH, mon - 1);
1255                        tcal.set(Calendar.YEAR, cl.get(Calendar.YEAR));
1256
1257                        int ldom = getLastDayOfMonth(mon, cl.get(Calendar.YEAR));
1258                        int dow = tcal.get(Calendar.DAY_OF_WEEK);
1259
1260                        if (dow == Calendar.SATURDAY && day == 1) {
1261                            day += 2;
1262                        } else if (dow == Calendar.SATURDAY) {
1263                            day -= 1;
1264                        } else if (dow == Calendar.SUNDAY && day == ldom) {
1265                            day -= 2;
1266                        } else if (dow == Calendar.SUNDAY) {
1267                            day += 1;
1268                        }
1269
1270
1271                        tcal.set(Calendar.SECOND, sec);
1272                        tcal.set(Calendar.MINUTE, min);
1273                        tcal.set(Calendar.HOUR_OF_DAY, hr);
1274                        tcal.set(Calendar.DAY_OF_MONTH, day);
1275                        tcal.set(Calendar.MONTH, mon - 1);
1276                        Date nTime = tcal.getTime();
1277                        if (nTime.before(afterTime)) {
1278                        

Large files files are truncated, but you can click here to view the full file