Clover coverage report -
Coverage timestamp: So Nov 6 2005 14:19:51 CET
file stats: LOC: 1.042   Methods: 18
NCLOC: 611   Classes: 2
 
 Source file Conditionals Statements Methods TOTAL
FastCronParser.java 94,8% 97,6% 94,4% 96,5%
coverage coverage
 1    /*
 2    * Copyright (c) 2002-2003 by OpenSymphony
 3    * All rights reserved.
 4    */
 5    package com.opensymphony.oscache.util;
 6   
 7    import java.text.ParseException;
 8   
 9    import java.util.*;
 10    import java.util.Calendar;
 11   
 12    /**
 13    * Parses cron expressions and determines at what time in the past is the
 14    * most recent match for the supplied expression.
 15    *
 16    * @author <a href="&#109;a&#105;&#108;&#116;&#111;:chris&#64;swebtec.&#99;&#111;&#109;">Chris Miller</a>
 17    * @author $Author: dres $
 18    * @version $Revision: 1.1 $
 19    */
 20    public class FastCronParser {
 21    private static final int NUMBER_OF_CRON_FIELDS = 5;
 22    private static final int MINUTE = 0;
 23    private static final int HOUR = 1;
 24    private static final int DAY_OF_MONTH = 2;
 25    private static final int MONTH = 3;
 26    private static final int DAY_OF_WEEK = 4;
 27   
 28    // Lookup tables that hold the min/max/size of each of the above field types.
 29    // These tables are precalculated for performance.
 30    private static final int[] MIN_VALUE = {0, 0, 1, 1, 0};
 31    private static final int[] MAX_VALUE = {59, 23, 31, 12, 6};
 32   
 33    /**
 34    * A lookup table holding the number of days in each month (with the obvious exception
 35    * that February requires special handling).
 36    */
 37    private static final int[] DAYS_IN_MONTH = {
 38    31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
 39    };
 40   
 41    /**
 42    * Holds the raw cron expression that this parser is handling.
 43    */
 44    private String cronExpression = null;
 45   
 46    /**
 47    * This is the main lookup table that holds a parsed cron expression. each long
 48    * represents one of the above field types. Bits in each long value correspond
 49    * to one of the possbile field values - eg, for the minute field, bits 0 -> 59 in
 50    * <code>lookup[MINUTE]</code> map to minutes 0 -> 59 respectively. Bits are set if
 51    * the corresponding value is enabled. So if the minute field in the cron expression
 52    * was <code>"0,2-8,50"</code>, bits 0, 2, 3, 4, 5, 6, 7, 8 and 50 will be set.
 53    * If the cron expression is <code>"*"</code>, the long value is set to
 54    * <code>Long.MAX_VALUE</code>.
 55    */
 56    private long[] lookup = {
 57    Long.MAX_VALUE, Long.MAX_VALUE, Long.MAX_VALUE, Long.MAX_VALUE,
 58    Long.MAX_VALUE
 59    };
 60   
 61    /**
 62    * This is based on the contents of the <code>lookup</code> table. It holds the
 63    * <em>highest</em> valid field value for each field type.
 64    */
 65    private int[] lookupMax = {-1, -1, -1, -1, -1};
 66   
 67    /**
 68    * This is based on the contents of the <code>lookup</code> table. It holds the
 69    * <em>lowest</em> valid field value for each field type.
 70    */
 71    private int[] lookupMin = {
 72    Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE,
 73    Integer.MAX_VALUE, Integer.MAX_VALUE
 74    };
 75   
 76    /**
 77    * Creates a FastCronParser that uses a default cron expression of <code>"* * * * *"</cron>.
 78    * This will match any time that is supplied.
 79    */
 80  20 public FastCronParser() {
 81    }
 82   
 83    /**
 84    * Constructs a new FastCronParser based on the supplied expression.
 85    *
 86    * @throws ParseException if the supplied expression is not a valid cron expression.
 87    */
 88  316 public FastCronParser(String cronExpression) throws ParseException {
 89  316 setCronExpression(cronExpression);
 90    }
 91   
 92    /**
 93    * Resets the cron expression to the value supplied.
 94    *
 95    * @param cronExpression the new cron expression.
 96    *
 97    * @throws ParseException if the supplied expression is not a valid cron expression.
 98    */
 99  8040332 public void setCronExpression(String cronExpression) throws ParseException {
 100  8040332 if (cronExpression == null) {
 101  4 throw new IllegalArgumentException("Cron time expression cannot be null");
 102    }
 103   
 104  8040328 this.cronExpression = cronExpression;
 105  8040328 parseExpression(cronExpression);
 106    }
 107   
 108    /**
 109    * Retrieves the current cron expression.
 110    *
 111    * @return the current cron expression.
 112    */
 113  12 public String getCronExpression() {
 114  12 return this.cronExpression;
 115    }
 116   
 117    /**
 118    * Determines whether this cron expression matches a date/time that is more recent
 119    * than the one supplied.
 120    *
 121    * @param time The time to compare the cron expression against.
 122    *
 123    * @return <code>true</code> if the cron expression matches a time that is closer
 124    * to the current time than the supplied time is, <code>false</code> otherwise.
 125    */
 126  0 public boolean hasMoreRecentMatch(long time) {
 127  0 return time < getTimeBefore(System.currentTimeMillis());
 128    }
 129   
 130    /**
 131    * Find the most recent time that matches this cron expression. This time will
 132    * always be in the past, ie a lower value than the supplied time.
 133    *
 134    * @param time The time (in milliseconds) that we're using as our upper bound.
 135    *
 136    * @return The time (in milliseconds) when this cron event last occurred.
 137    */
 138  16040168 public long getTimeBefore(long time) {
 139    // It would be nice to get rid of the Calendar class for speed, but it's a lot of work...
 140    // We create this
 141  16040168 Calendar cal = new GregorianCalendar();
 142  16040168 cal.setTime(new Date(time));
 143   
 144  16040168 int minute = cal.get(Calendar.MINUTE);
 145  16040168 int hour = cal.get(Calendar.HOUR_OF_DAY);
 146  16040168 int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
 147  16040168 int month = cal.get(Calendar.MONTH) + 1; // Calendar is 0-based for this field, and we are 1-based
 148  16040168 int year = cal.get(Calendar.YEAR);
 149   
 150  16040168 long validMinutes = lookup[MINUTE];
 151  16040168 long validHours = lookup[HOUR];
 152  16040168 long validDaysOfMonth = lookup[DAY_OF_MONTH];
 153  16040168 long validMonths = lookup[MONTH];
 154  16040168 long validDaysOfWeek = lookup[DAY_OF_WEEK];
 155   
 156    // Find out if we have a Day of Week or Day of Month field
 157  16040168 boolean haveDOM = validDaysOfMonth != Long.MAX_VALUE;
 158  16040168 boolean haveDOW = validDaysOfWeek != Long.MAX_VALUE;
 159   
 160  16040168 boolean skippedNonLeapYear = false;
 161   
 162  16040168 while (true) {
 163  16040316 boolean retry = false;
 164   
 165    // Clean up the month if it was wrapped in a previous iteration
 166  16040316 if (month < 1) {
 167  28 month += 12;
 168  28 year--;
 169    }
 170   
 171    // get month...................................................
 172  16040316 boolean found = false;
 173   
 174  16040316 if (validMonths != Long.MAX_VALUE) {
 175  8040108 for (int i = month + 11; i > (month - 1); i--) {
 176  88480756 int testMonth = (i % 12) + 1;
 177   
 178    // Check if the month is valid
 179  88480756 if (((1L << (testMonth - 1)) & validMonths) != 0) {
 180  8040108 if ((testMonth > month) || skippedNonLeapYear) {
 181  8040060 year--;
 182    }
 183   
 184    // Check there are enough days in this month (catches non leap-years trying to match the 29th Feb)
 185  8040108 int numDays = numberOfDaysInMonth(testMonth, year);
 186   
 187  8040108 if (!haveDOM || (numDays >= lookupMin[DAY_OF_MONTH])) {
 188  8040072 if ((month != testMonth) || skippedNonLeapYear) {
 189    // New DOM = min(maxDOM, prevDays); ie, the highest valid value
 190  8040056 dayOfMonth = (numDays <= lookupMax[DAY_OF_MONTH]) ? numDays : lookupMax[DAY_OF_MONTH];
 191  8040056 hour = lookupMax[HOUR];
 192  8040056 minute = lookupMax[MINUTE];
 193  8040056 month = testMonth;
 194    }
 195   
 196  8040072 found = true;
 197  8040072 break;
 198    }
 199    }
 200    }
 201   
 202  8040108 skippedNonLeapYear = false;
 203   
 204  8040108 if (!found) {
 205    // The only time we drop out here is when we're searching for the 29th of February and no other date!
 206  36 skippedNonLeapYear = true;
 207  36 continue;
 208    }
 209    }
 210   
 211    // Clean up if the dayOfMonth was wrapped. This takes leap years into account.
 212  16040280 if (dayOfMonth < 1) {
 213  20 month--;
 214  20 dayOfMonth += numberOfDaysInMonth(month, year);
 215  20 hour = lookupMax[HOUR];
 216  20 continue;
 217    }
 218   
 219    // get day...................................................
 220  16040260 if (haveDOM && !haveDOW) { // get day using just the DAY_OF_MONTH token
 221   
 222  8040072 int daysInThisMonth = numberOfDaysInMonth(month, year);
 223  8040072 int daysInPreviousMonth = numberOfDaysInMonth(month - 1, year);
 224   
 225    // Find the highest valid day that is below the current day
 226  8040332 for (int i = dayOfMonth + 30; i > (dayOfMonth - 1); i--) {
 227  8040332 int testDayOfMonth = (i % 31) + 1;
 228   
 229    // Skip over any days that don't actually exist (eg 31st April)
 230  8040332 if ((testDayOfMonth <= dayOfMonth) && (testDayOfMonth > daysInThisMonth)) {
 231  0 continue;
 232    }
 233   
 234  8040332 if ((testDayOfMonth > dayOfMonth) && (testDayOfMonth > daysInPreviousMonth)) {
 235  4 continue;
 236    }
 237   
 238  8040328 if (((1L << (testDayOfMonth - 1)) & validDaysOfMonth) != 0) {
 239  8040072 if (testDayOfMonth > dayOfMonth) {
 240    // We've found a valid day, but we had to move back a month
 241  24 month--;
 242  24 retry = true;
 243    }
 244   
 245  8040072 if (dayOfMonth != testDayOfMonth) {
 246  28 hour = lookupMax[HOUR];
 247  28 minute = lookupMax[MINUTE];
 248    }
 249   
 250  8040072 dayOfMonth = testDayOfMonth;
 251  8040072 break;
 252    }
 253    }
 254   
 255  8040072 if (retry) {
 256  24 continue;
 257    }
 258  8000188 } else if (haveDOW && !haveDOM) { // get day using just the DAY_OF_WEEK token
 259   
 260  60 int daysLost = 0;
 261  60 int currentDOW = dayOfWeek(dayOfMonth, month, year);
 262   
 263  208 for (int i = currentDOW + 7; i > currentDOW; i--) {
 264  208 int testDOW = i % 7;
 265   
 266  208 if (((1L << testDOW) & validDaysOfWeek) != 0) {
 267  60 dayOfMonth -= daysLost;
 268   
 269  60 if (dayOfMonth < 1) {
 270    // We've wrapped back a month
 271  16 month--;
 272  16 dayOfMonth += numberOfDaysInMonth(month, year);
 273  16 retry = true;
 274    }
 275   
 276  60 if (currentDOW != testDOW) {
 277  40 hour = lookupMax[HOUR];
 278  40 minute = lookupMax[MINUTE];
 279    }
 280   
 281  60 break;
 282    }
 283   
 284  148 daysLost++;
 285    }
 286   
 287  60 if (retry) {
 288  16 continue;
 289    }
 290    }
 291   
 292    // Clean up if the hour has been wrapped
 293  16040220 if (hour < 0) {
 294  12 hour += 24;
 295  12 dayOfMonth--;
 296  12 continue;
 297    }
 298   
 299    // get hour...................................................
 300  16040208 if (validHours != Long.MAX_VALUE) {
 301    // Find the highest valid hour that is below the current hour
 302  8040496 for (int i = hour + 24; i > hour; i--) {
 303  8040496 int testHour = i % 24;
 304   
 305  8040496 if (((1L << testHour) & validHours) != 0) {
 306  8040120 if (testHour > hour) {
 307    // We've found an hour, but we had to move back a day
 308  16 dayOfMonth--;
 309  16 retry = true;
 310    }
 311   
 312  8040120 if (hour != testHour) {
 313  32 minute = lookupMax[MINUTE];
 314    }
 315   
 316  8040120 hour = testHour;
 317  8040120 break;
 318    }
 319    }
 320   
 321  8040120 if (retry) {
 322  16 continue;
 323    }
 324    }
 325   
 326    // get minute.................................................
 327  16040192 if (validMinutes != Long.MAX_VALUE) {
 328    // Find the highest valid minute that is below the current minute
 329  8040844 for (int i = minute + 60; i > minute; i--) {
 330  8040844 int testMinute = i % 60;
 331   
 332  8040844 if (((1L << testMinute) & validMinutes) != 0) {
 333  8040120 if (testMinute > minute) {
 334    // We've found a minute, but we had to move back an hour
 335  24 hour--;
 336  24 retry = true;
 337    }
 338   
 339  8040120 minute = testMinute;
 340  8040120 break;
 341    }
 342    }
 343   
 344  8040120 if (retry) {
 345  24 continue;
 346    }
 347    }
 348   
 349  16040168 break;
 350    }
 351   
 352    // OK, all done. Return the adjusted time value (adjusting this is faster than creating a new Calendar object)
 353  16040168 cal.set(Calendar.YEAR, year);
 354  16040168 cal.set(Calendar.MONTH, month - 1); // Calendar is 0-based for this field, and we are 1-based
 355  16040168 cal.set(Calendar.DAY_OF_MONTH, dayOfMonth);
 356  16040168 cal.set(Calendar.HOUR_OF_DAY, hour);
 357  16040168 cal.set(Calendar.MINUTE, minute);
 358  16040168 cal.set(Calendar.SECOND, 0);
 359  16040168 cal.set(Calendar.MILLISECOND, 0);
 360   
 361  16040168 return cal.getTime().getTime();
 362    }
 363   
 364    /**
 365    * Takes a cron expression as an input parameter, and extracts from it the
 366    * relevant minutes/hours/days/months that the expression matches.
 367    *
 368    * @param expression A valid cron expression.
 369    * @throws ParseException If the supplied expression could not be parsed.
 370    */
 371  8040328 private void parseExpression(String expression) throws ParseException {
 372  8040328 try {
 373    // Reset all the lookup data
 374  8040328 for (int i = 0; i < lookup.length; lookup[i++] = 0) {
 375  40201640 lookupMin[i] = Integer.MAX_VALUE;
 376  40201640 lookupMax[i] = -1;
 377    }
 378   
 379    // Create some character arrays to hold the extracted field values
 380  8040328 char[][] token = new char[NUMBER_OF_CRON_FIELDS][];
 381   
 382    // Extract the supplied expression into another character array
 383    // for speed
 384  8040328 int length = expression.length();
 385  8040328 char[] expr = new char[length];
 386  8040328 expression.getChars(0, length, expr, 0);
 387   
 388  8040328 int field = 0;
 389  8040328 int startIndex = 0;
 390  8040328 boolean inWhitespace = true;
 391   
 392    // Extract the various cron fields from the expression
 393  8040328 for (int i = 0; (i < length) && (field < NUMBER_OF_CRON_FIELDS);
 394    i++) {
 395  200524544 boolean haveChar = (expr[i] != ' ') && (expr[i] != '\t');
 396   
 397  200524544 if (haveChar) {
 398    // We have a text character of some sort
 399  168363220 if (inWhitespace) {
 400  40201616 startIndex = i; // Remember the start of this token
 401  40201616 inWhitespace = false;
 402    }
 403    }
 404   
 405  200524544 if (i == (length - 1)) { // Adjustment for when we reach the end of the expression
 406  8040324 i++;
 407    }
 408   
 409  200524544 if (!(haveChar || inWhitespace) || (i == length)) {
 410    // We've reached the end of a token. Copy it into a new char array
 411  40201616 token[field] = new char[i - startIndex];
 412  40201616 System.arraycopy(expr, startIndex, token[field], 0, i - startIndex);
 413  40201616 inWhitespace = true;
 414  40201616 field++;
 415    }
 416    }
 417   
 418  8040328 if (field < NUMBER_OF_CRON_FIELDS) {
 419  8 throw new ParseException("Unexpected end of expression while parsing \"" + expression + "\". Cron expressions require 5 separate fields.", length);
 420    }
 421   
 422    // OK, we've broken the string up into the 5 cron fields, now lets add
 423    // each field to their lookup table.
 424  8040320 for (field = 0; field < NUMBER_OF_CRON_FIELDS; field++) {
 425  40201456 startIndex = 0;
 426   
 427  40201456 boolean inDelimiter = true;
 428   
 429    // We add each comma-delimited element seperately.
 430  40201456 int elementLength = token[field].length;
 431   
 432  40201456 for (int i = 0; i < elementLength; i++) {
 433  168363052 boolean haveElement = token[field][i] != ',';
 434   
 435  168363052 if (haveElement) {
 436    // We have a character from an element in the token
 437  136362896 if (inDelimiter) {
 438  72201612 startIndex = i;
 439  72201612 inDelimiter = false;
 440    }
 441    }
 442   
 443  168363052 if (i == (elementLength - 1)) { // Adjustment for when we reach the end of the token
 444  40201456 i++;
 445    }
 446   
 447  168363052 if (!(haveElement || inDelimiter) || (i == elementLength)) {
 448    // We've reached the end of an element. Copy it into a new char array
 449  72201612 char[] element = new char[i - startIndex];
 450  72201612 System.arraycopy(token[field], startIndex, element, 0, i - startIndex);
 451   
 452    // Add the element to our datastructure.
 453  72201612 storeExpressionValues(element, field);
 454   
 455  72201496 inDelimiter = true;
 456    }
 457    }
 458   
 459  40201340 if (lookup[field] == 0) {
 460  0 throw new ParseException("Token " + new String(token[field]) + " contains no valid entries for this field.", 0);
 461    }
 462    }
 463   
 464    // Remove any months that will never be valid
 465  8040204 switch (lookupMin[DAY_OF_MONTH]) {
 466  4 case 31:
 467  4 lookup[MONTH] &= (0xFFF - 0x528); // Binary 010100101000 - the months that have 30 days
 468  8 case 30:
 469  12 lookup[MONTH] &= (0xFFF - 0x2); // Binary 000000000010 - February
 470   
 471  12 if (lookup[MONTH] == 0) {
 472  8 throw new ParseException("The cron expression \"" + expression + "\" will never match any months - the day of month field is out of range.", 0);
 473    }
 474    }
 475   
 476    // Check that we don't have both a day of month and a day of week field.
 477  8040196 if ((lookup[DAY_OF_MONTH] != Long.MAX_VALUE) && (lookup[DAY_OF_WEEK] != Long.MAX_VALUE)) {
 478  4 throw new ParseException("The cron expression \"" + expression + "\" is invalid. Having both a day-of-month and day-of-week field is not supported.", 0);
 479    }
 480    } catch (Exception e) {
 481  136 if (e instanceof ParseException) {
 482  136 throw (ParseException) e;
 483    } else {
 484  0 throw new ParseException("Illegal cron expression format (" + e.toString() + ")", 0);
 485    }
 486    }
 487    }
 488   
 489    /**
 490    * Stores the values for the supplied cron element into the specified field.
 491    *
 492    * @param element The cron element to store. A cron element is a single component
 493    * of a cron expression. For example, the complete set of elements for the cron expression
 494    * <code>30 0,6,12,18 * * *</code> would be <code>{"30", "0", "6", "12", "18", "*", "*", "*"}</code>.
 495    * @param field The field that this expression belongs to. Valid values are {@link #MINUTE},
 496    * {@link #HOUR}, {@link #DAY_OF_MONTH}, {@link #MONTH} and {@link #DAY_OF_WEEK}.
 497    *
 498    * @throws ParseException if there was a problem parsing the supplied element.
 499    */
 500  72201612 private void storeExpressionValues(char[] element, int field) throws ParseException {
 501  72201612 int i = 0;
 502   
 503  72201612 int start = -99;
 504  72201612 int end = -99;
 505  72201612 int interval = -1;
 506  72201612 boolean wantValue = true;
 507  72201612 boolean haveInterval = false;
 508   
 509  72201612 while ((interval < 0) && (i < element.length)) {
 510  104201932 char ch = element[i++];
 511   
 512    // Handle the wildcard character - it can only ever occur at the start of an element
 513  104201932 if ((i == 1) && (ch == '*')) {
 514    // Handle the special case where we have '*' and nothing else
 515  24040932 if (i >= element.length) {
 516  24040928 addToLookup(-1, -1, field, 1);
 517  24040928 return;
 518    }
 519   
 520  4 start = -1;
 521  4 end = -1;
 522  4 wantValue = false;
 523  4 continue;
 524    }
 525   
 526  80161000 if (wantValue) {
 527    // Handle any numbers
 528  64160836 if ((ch >= '0') && (ch <= '9')) {
 529  64160644 ValueSet vs = getValue(ch - '0', element, i);
 530   
 531  64160644 if (start == -99) {
 532  48160520 start = vs.value;
 533  16000124 } else if (!haveInterval) {
 534  16000080 end = vs.value;
 535    } else {
 536  44 if (end == -99) {
 537  24 end = MAX_VALUE[field];
 538    }
 539   
 540  44 interval = vs.value;
 541    }
 542   
 543  64160644 i = vs.pos;
 544  64160644 wantValue = false;
 545  64160644 continue;
 546    }
 547   
 548  192 if (!haveInterval && (end == -99)) {
 549    // Handle any months that have been suplied as words
 550  192 if (field == MONTH) {
 551  108 if (start == -99) {
 552  96 start = getMonthVal(ch, element, i++);
 553    } else {
 554  12 end = getMonthVal(ch, element, i++);
 555    }
 556   
 557  68 wantValue = false;
 558   
 559    // Skip past the rest of the month name
 560  68 while (++i < element.length) {
 561  108 int c = element[i] | 0x20;
 562   
 563  108 if ((c < 'a') || (c > 'z')) {
 564  16 break;
 565    }
 566    }
 567   
 568  68 continue;
 569  84 } else if (field == DAY_OF_WEEK) {
 570  72 if (start == -99) {
 571  56 start = getDayOfWeekVal(ch, element, i++);
 572    } else {
 573  16 end = getDayOfWeekVal(ch, element, i++);
 574    }
 575   
 576  48 wantValue = false;
 577   
 578    // Skip past the rest of the day name
 579  48 while (++i < element.length) {
 580  96 int c = element[i] | 0x20;
 581   
 582  96 if ((c < 'a') || (c > 'z')) {
 583  16 break;
 584    }
 585    }
 586   
 587  48 continue;
 588    }
 589    }
 590    } else {
 591    // Handle the range character. A range character is only valid if we have a start but no end value
 592  16000164 if ((ch == '-') && (start != -99) && (end == -99)) {
 593  16000112 wantValue = true;
 594  16000112 continue;
 595    }
 596   
 597    // Handle an interval. An interval is valid as long as we have a start value
 598  52 if ((ch == '/') && (start != -99)) {
 599  44 wantValue = true;
 600  44 haveInterval = true;
 601  44 continue;
 602    }
 603    }
 604   
 605  20 throw makeParseException("Invalid character encountered while parsing element", element, i);
 606    }
 607   
 608  48160600 if (element.length > i) {
 609  4 throw makeParseException("Extraneous characters found while parsing element", element, i);
 610    }
 611   
 612  48160596 if (end == -99) {
 613  32160472 end = start;
 614    }
 615   
 616  48160596 if (interval < 0) {
 617  48160556 interval = 1;
 618    }
 619   
 620  48160596 addToLookup(start, end, field, interval);
 621    }
 622   
 623    /**
 624    * Extracts a numerical value from inside a character array.
 625    *
 626    * @param value The value of the first character
 627    * @param element The character array we're extracting the value from
 628    * @param i The index into the array of the next character to process
 629    *
 630    * @return the new index and the extracted value
 631    */
 632  64160644 private ValueSet getValue(int value, char[] element, int i) {
 633  64160644 ValueSet result = new ValueSet();
 634  64160644 result.value = value;
 635   
 636  64160644 if (i >= element.length) {
 637  24000292 result.pos = i;
 638  24000292 return result;
 639    }
 640   
 641  40160352 char ch = element[i];
 642   
 643  40160352 while ((ch >= '0') && (ch <= '9')) {
 644  32160264 result.value = (result.value * 10) + (ch - '0');
 645   
 646  32160264 if (++i >= element.length) {
 647  24160220 break;
 648    }
 649   
 650  8000044 ch = element[i];
 651    }
 652   
 653  40160352 result.pos = i;
 654   
 655  40160352 return result;
 656    }
 657   
 658    /**
 659    * Adds a group of valid values to the lookup table for the specified field. This method
 660    * handles ranges that increase in arbitrary step sizes. It is also possible to add a single
 661    * value by specifying a range with the same start and end values.
 662    *
 663    * @param start The starting value for the range. Supplying a value that is less than zero
 664    * will cause the minimum allowable value for the specified field to be used as the start value.
 665    * @param end The maximum value that can be added (ie the upper bound). If the step size is
 666    * greater than one, this maximum value may not necessarily end up being added. Supplying a
 667    * value that is less than zero will cause the maximum allowable value for the specified field
 668    * to be used as the upper bound.
 669    * @param field The field that the values should be added to.
 670    * @param interval Specifies the step size for the range. Any values less than one will be
 671    * treated as a single step interval.
 672    */
 673  72201524 private void addToLookup(int start, int end, int field, int interval) throws ParseException {
 674    // deal with the supplied range
 675  72201524 if (start == end) {
 676  56201404 if (start < 0) {
 677    // We're setting the entire range of values
 678  24040932 start = lookupMin[field] = MIN_VALUE[field];
 679  24040932 end = lookupMax[field] = MAX_VALUE[field];
 680   
 681  24040932 if (interval <= 1) {
 682  24040928 lookup[field] = Long.MAX_VALUE;
 683  24040928 return;
 684    }
 685    } else {
 686    // We're only setting a single value - check that it is in range
 687  32160472 if (start < MIN_VALUE[field]) {
 688  4 throw new ParseException("Value " + start + " in field " + field + " is lower than the minimum allowable value for this field (min=" + MIN_VALUE[field] + ")", 0);
 689  32160468 } else if (start > MAX_VALUE[field]) {
 690  8 throw new ParseException("Value " + start + " in field " + field + " is higher than the maximum allowable value for this field (max=" + MAX_VALUE[field] + ")", 0);
 691    }
 692    }
 693    } else {
 694    // For ranges, if the start is bigger than the end value then swap them over
 695  16000120 if (start > end) {
 696  8 end ^= start;
 697  8 start ^= end;
 698  8 end ^= start;
 699    }
 700   
 701  16000120 if (start < 0) {
 702  0 start = MIN_VALUE[field];
 703  16000120 } else if (start < MIN_VALUE[field]) {
 704  8 throw new ParseException("Value " + start + " in field " + field + " is lower than the minimum allowable value for this field (min=" + MIN_VALUE[field] + ")", 0);
 705    }
 706   
 707  16000112 if (end < 0) {
 708  0 end = MAX_VALUE[field];
 709  16000112 } else if (end > MAX_VALUE[field]) {
 710  8 throw new ParseException("Value " + end + " in field " + field + " is higher than the maximum allowable value for this field (max=" + MAX_VALUE[field] + ")", 0);
 711    }
 712    }
 713   
 714  48160568 if (interval < 1) {
 715  0 interval = 1;
 716    }
 717   
 718  48160568 int i = start - MIN_VALUE[field];
 719   
 720    // Populate the lookup table by setting all the bits corresponding to the valid field values
 721  48160568 for (i = start - MIN_VALUE[field]; i <= (end - MIN_VALUE[field]);
 722    i += interval) {
 723  348161276 lookup[field] |= (1L << i);
 724    }
 725   
 726    // Make sure we remember the minimum value set so far
 727    // Keep track of the highest and lowest values that have been added to this field so far
 728  48160568 if (lookupMin[field] > start) {
 729  16160416 lookupMin[field] = start;
 730    }
 731   
 732  48160568 i += (MIN_VALUE[field] - interval);
 733   
 734  48160568 if (lookupMax[field] < i) {
 735  20160524 lookupMax[field] = i;
 736    }
 737    }
 738   
 739    /**
 740    * Indicates if a year is a leap year or not.
 741    *
 742    * @param year The year to check
 743    *
 744    * @return <code>true</code> if the year is a leap year, <code>false</code> otherwise.
 745    */
 746  8080092 private boolean isLeapYear(int year) {
 747  8080092 return (((year % 4) == 0) && ((year % 100) != 0)) || ((year % 400) == 0);
 748    }
 749   
 750    /**
 751    * Calculate the day of the week. Sunday = 0, Monday = 1, ... , Saturday = 6. The formula
 752    * used is an optimized version of Zeller's Congruence.
 753    *
 754    * @param day The day of the month (1-31)
 755    * @param month The month (1 - 12)
 756    * @param year The year
 757    * @return
 758    */
 759  60 private int dayOfWeek(int day, int month, int year) {
 760  60 day += ((month < 3) ? year-- : (year - 2));
 761  60 return ((((23 * month) / 9) + day + 4 + (year / 4)) - (year / 100) + (year / 400)) % 7;
 762    }
 763   
 764    /**
 765    * Retrieves the number of days in the supplied month, taking into account leap years.
 766    * If the month value is outside the range <code>MIN_VALUE[MONTH] - MAX_VALUE[MONTH]</code>
 767    * then the year will be adjusted accordingly and the correct number of days will still
 768    * be returned.
 769    *
 770    * @param month The month of interest.
 771    * @param year The year we are checking.
 772    *
 773    * @return The number of days in the month.
 774    */
 775  24120288 private int numberOfDaysInMonth(int month, int year) {
 776  24120288 while (month < 1) {
 777  32 month += 12;
 778  32 year--;
 779    }
 780   
 781  24120288 while (month > 12) {
 782  0 month -= 12;
 783  0 year++;
 784    }
 785   
 786  24120288 if (month == 2) {
 787  8080092 return isLeapYear(year) ? 29 : 28;
 788    } else {
 789  16040196 return DAYS_IN_MONTH[month - 1];
 790    }
 791    }
 792   
 793    /**
 794    * Quickly retrieves the day of week value (Sun = 0, ... Sat = 6) that corresponds to the
 795    * day name that is specified in the character array. Only the first 3 characters are taken
 796    * into account; the rest are ignored.
 797    *
 798    * @param element The character array
 799    * @param i The index to start looking at
 800    * @return The day of week value
 801    */
 802  72 private int getDayOfWeekVal(char ch1, char[] element, int i) throws ParseException {
 803  72 if ((i + 1) >= element.length) {
 804  4 throw makeParseException("Unexpected end of element encountered while parsing a day name", element, i);
 805    }
 806   
 807  68 int ch2 = element[i] | 0x20;
 808  68 int ch3 = element[i + 1] | 0x20;
 809   
 810  68 switch (ch1 | 0x20) {
 811  24 case 's': // Sunday, Saturday
 812   
 813  24 if ((ch2 == 'u') && (ch3 == 'n')) {
 814  12 return 0;
 815    }
 816   
 817  12 if ((ch2 == 'a') && (ch3 == 't')) {
 818  8 return 6;
 819    }
 820   
 821  4 break;
 822  8 case 'm': // Monday
 823   
 824  8 if ((ch2 == 'o') && (ch3 == 'n')) {
 825  4 return 1;
 826    }
 827   
 828  4 break;
 829  20 case 't': // Tuesday, Thursday
 830   
 831  20 if ((ch2 == 'u') && (ch3 == 'e')) {
 832  8 return 2;
 833    }
 834   
 835  12 if ((ch2 == 'h') && (ch3 == 'u')) {
 836  8 return 4;
 837    }
 838   
 839  4 break;
 840  8 case 'w': // Wednesday
 841   
 842  8 if ((ch2 == 'e') && (ch3 == 'd')) {
 843  4 return 3;
 844    }
 845   
 846  4 break;
 847  8 case 'f': // Friday
 848   
 849  8 if ((ch2 == 'r') && (ch3 == 'i')) {
 850  4 return 5;
 851    }
 852   
 853  4 break;
 854    }
 855   
 856  20 throw makeParseException("Unexpected character while parsing a day name", element, i - 1);
 857    }
 858   
 859    /**
 860    * Quickly retrieves the month value (Jan = 1, ..., Dec = 12) that corresponds to the month
 861    * name that is specified in the character array. Only the first 3 characters are taken
 862    * into account; the rest are ignored.
 863    *
 864    * @param element The character array
 865    * @param i The index to start looking at
 866    * @return The month value
 867    */
 868  108 private int getMonthVal(char ch1, char[] element, int i) throws ParseException {
 869  108 if ((i + 1) >= element.length) {
 870  0 throw makeParseException("Unexpected end of element encountered while parsing a month name", element, i);
 871    }
 872   
 873  108 int ch2 = element[i] | 0x20;
 874  108 int ch3 = element[i + 1] | 0x20;
 875   
 876  108 switch (ch1 | 0x20) {
 877  28 case 'j': // January, June, July
 878   
 879  28 if ((ch2 == 'a') && (ch3 == 'n')) {
 880  8 return 1;
 881    }
 882   
 883  20 if (ch2 == 'u') {
 884  16 if (ch3 == 'n') {
 885  8 return 6;
 886    }
 887   
 888  8 if (ch3 == 'l') {
 889  4 return 7;
 890    }
 891    }
 892   
 893  8 break;
 894  12 case 'f': // February
 895   
 896  12 if ((ch2 == 'e') && (ch3 == 'b')) {
 897  8 return 2;
 898    }
 899   
 900  4 break;
 901  16 case 'm': // March, May
 902   
 903  16 if (ch2 == 'a') {
 904  12 if (ch3 == 'r') {
 905  4 return 3;
 906    }
 907   
 908  8 if (ch3 == 'y') {
 909  4 return 5;
 910    }
 911    }
 912   
 913  8 break;
 914  20 case 'a': // April, August
 915   
 916  20 if ((ch2 == 'p') && (ch3 == 'r')) {
 917  8 return 4;
 918    }
 919   
 920  12 if ((ch2 == 'u') && (ch3 == 'g')) {
 921  8 return 8;
 922    }
 923   
 924  4 break;
 925  8 case 's': // September
 926   
 927  8 if ((ch2 == 'e') && (ch3 == 'p')) {
 928  4 return 9;
 929    }
 930   
 931  4 break;
 932  8 case 'o': // October
 933   
 934  8 if ((ch2 == 'c') && (ch3 == 't')) {
 935  4 return 10;
 936    }
 937   
 938  4 break;
 939  8 case 'n': // November
 940   
 941  8 if ((ch2 == 'o') && (ch3 == 'v')) {
 942  4 return 11;
 943    }
 944   
 945  4 break;
 946  8 case 'd': // December
 947   
 948  8 if ((ch2 == 'e') && (ch3 == 'c')) {
 949  4 return 12;
 950    }
 951   
 952  4 break;
 953    }
 954   
 955  40 throw makeParseException("Unexpected character while parsing a month name", element, i - 1);
 956    }
 957   
 958    /**
 959    * Recreates the original human-readable cron expression based on the internal
 960    * datastructure values.
 961    *
 962    * @return A cron expression that corresponds to the current state of the
 963    * internal data structure.
 964    */
 965  16 public String getExpressionSummary() {
 966  16 StringBuffer buf = new StringBuffer();
 967   
 968  16 buf.append(getExpressionSetSummary(MINUTE)).append(' ');
 969  16 buf.append(getExpressionSetSummary(HOUR)).append(' ');
 970  16 buf.append(getExpressionSetSummary(DAY_OF_MONTH)).append(' ');
 971  16 buf.append(getExpressionSetSummary(MONTH)).append(' ');
 972  16 buf.append(getExpressionSetSummary(DAY_OF_WEEK));
 973   
 974  16 return buf.toString();
 975    }
 976   
 977    /**
 978    * <p>Converts the internal datastructure that holds a particular cron field into
 979    * a human-readable list of values of the field's contents. For example, if the
 980    * <code>DAY_OF_WEEK</code> field was submitted that had Sunday and Monday specified,
 981    * the string <code>0,1</code> would be returned.</p>
 982    *
 983    * <p>If the field contains all possible values, <code>*</code> will be returned.
 984    *
 985    * @param field The field.
 986    *
 987    * @return A human-readable string representation of the field's contents.
 988    */
 989  80 private String getExpressionSetSummary(int field) {
 990  80 if (lookup[field] == Long.MAX_VALUE) {
 991  52 return "*";
 992    }
 993   
 994  28 StringBuffer buf = new StringBuffer();
 995   
 996  28 boolean first = true;
 997   
 998  28 for (int i = MIN_VALUE[field]; i <= MAX_VALUE[field]; i++) {
 999  988 if ((lookup[field] & (1L << (i - MIN_VALUE[field]))) != 0) {
 1000  136 if (!first) {
 1001  108 buf.append(",");
 1002    } else {
 1003  28 first = false;
 1004    }
 1005   
 1006  136 buf.append(String.valueOf(i));
 1007    }
 1008    }
 1009   
 1010  28 return buf.toString();
 1011    }
 1012   
 1013    /**
 1014    * Makes a <code>ParseException</code>. The exception message is constructed by
 1015    * taking the given message parameter and appending the supplied character data
 1016    * to the end of it. for example, if <code>msg == "Invalid character
 1017    * encountered"</code> and <code>data == {'A','g','u','s','t'}</code>, the resultant
 1018    * error message would be <code>"Invalid character encountered [Agust]"</code>.
 1019    *
 1020    * @param msg The error message
 1021    * @param data The data that the message
 1022    * @param offset The offset into the data where the error was encountered.
 1023    *
 1024    * @return a newly created <code>ParseException</code> object.
 1025    */
 1026  88 private ParseException makeParseException(String msg, char[] data, int offset) {
 1027  88 char[] buf = new char[msg.length() + data.length + 3];
 1028  88 int msgLen = msg.length();
 1029  88 System.arraycopy(msg.toCharArray(), 0, buf, 0, msgLen);
 1030  88 buf[msgLen] = ' ';
 1031  88 buf[msgLen + 1] = '[';
 1032  88 System.arraycopy(data, 0, buf, msgLen + 2, data.length);
 1033  88 buf[buf.length - 1] = ']';
 1034  88 return new ParseException(new String(buf), offset);
 1035    }
 1036    }
 1037   
 1038   
 1039    class ValueSet {
 1040    public int pos;
 1041    public int value;
 1042    }