PageRenderTime 897ms CodeModel.GetById 222ms app.highlight 446ms RepoModel.GetById 198ms app.codeStats 1ms

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

https://github.com/langley/Play20
Java | 1589 lines | 1115 code | 156 blank | 318 comment | 454 complexity | e7c6ee9c6280d17cba89b772cbb450ff MD5 | raw file

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

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

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