PageRenderTime 56ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

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

https://github.com/pdecat/play
Java | 1553 lines | 1099 code | 154 blank | 300 comment | 454 complexity | 909e91f0e5b4aec4b2b7676895251a88 MD5 | raw file
Possible License(s): Apache-2.0

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

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

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