393f2fae270831c1e20f0d121d81badfa4f37696.svn-base 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666
  1. /*
  2. * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  5. * use this file except in compliance with the License. You may obtain a copy
  6. * of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. * License for the specific language governing permissions and limitations
  14. * under the License.
  15. *
  16. */
  17. package com.xxl.job.admin.core.cron;
  18. import java.io.Serializable;
  19. import java.text.ParseException;
  20. import java.util.Calendar;
  21. import java.util.Date;
  22. import java.util.HashMap;
  23. import java.util.Iterator;
  24. import java.util.Locale;
  25. import java.util.Map;
  26. import java.util.SortedSet;
  27. import java.util.StringTokenizer;
  28. import java.util.TimeZone;
  29. import java.util.TreeSet;
  30. /**
  31. * Provides a parser and evaluator for unix-like cron expressions. Cron
  32. * expressions provide the ability to specify complex time combinations such as
  33. * "At 8:00am every Monday through Friday" or "At 1:30am every
  34. * last Friday of the month".
  35. * <P>
  36. * Cron expressions are comprised of 6 required fields and one optional field
  37. * separated by white space. The fields respectively are described as follows:
  38. *
  39. * <table cellspacing="8">
  40. * <tr>
  41. * <th align="left">Field Name</th>
  42. * <th align="left">&nbsp;</th>
  43. * <th align="left">Allowed Values</th>
  44. * <th align="left">&nbsp;</th>
  45. * <th align="left">Allowed Special Characters</th>
  46. * </tr>
  47. * <tr>
  48. * <td align="left"><code>Seconds</code></td>
  49. * <td align="left">&nbsp;</th>
  50. * <td align="left"><code>0-59</code></td>
  51. * <td align="left">&nbsp;</th>
  52. * <td align="left"><code>, - * /</code></td>
  53. * </tr>
  54. * <tr>
  55. * <td align="left"><code>Minutes</code></td>
  56. * <td align="left">&nbsp;</th>
  57. * <td align="left"><code>0-59</code></td>
  58. * <td align="left">&nbsp;</th>
  59. * <td align="left"><code>, - * /</code></td>
  60. * </tr>
  61. * <tr>
  62. * <td align="left"><code>Hours</code></td>
  63. * <td align="left">&nbsp;</th>
  64. * <td align="left"><code>0-23</code></td>
  65. * <td align="left">&nbsp;</th>
  66. * <td align="left"><code>, - * /</code></td>
  67. * </tr>
  68. * <tr>
  69. * <td align="left"><code>Day-of-month</code></td>
  70. * <td align="left">&nbsp;</th>
  71. * <td align="left"><code>1-31</code></td>
  72. * <td align="left">&nbsp;</th>
  73. * <td align="left"><code>, - * ? / L W</code></td>
  74. * </tr>
  75. * <tr>
  76. * <td align="left"><code>Month</code></td>
  77. * <td align="left">&nbsp;</th>
  78. * <td align="left"><code>0-11 or JAN-DEC</code></td>
  79. * <td align="left">&nbsp;</th>
  80. * <td align="left"><code>, - * /</code></td>
  81. * </tr>
  82. * <tr>
  83. * <td align="left"><code>Day-of-Week</code></td>
  84. * <td align="left">&nbsp;</th>
  85. * <td align="left"><code>1-7 or SUN-SAT</code></td>
  86. * <td align="left">&nbsp;</th>
  87. * <td align="left"><code>, - * ? / L #</code></td>
  88. * </tr>
  89. * <tr>
  90. * <td align="left"><code>Year (Optional)</code></td>
  91. * <td align="left">&nbsp;</th>
  92. * <td align="left"><code>empty, 1970-2199</code></td>
  93. * <td align="left">&nbsp;</th>
  94. * <td align="left"><code>, - * /</code></td>
  95. * </tr>
  96. * </table>
  97. * <P>
  98. * The '*' character is used to specify all values. For example, &quot;*&quot;
  99. * in the minute field means &quot;every minute&quot;.
  100. * <P>
  101. * The '?' character is allowed for the day-of-month and day-of-week fields. It
  102. * is used to specify 'no specific value'. This is useful when you need to
  103. * specify something in one of the two fields, but not the other.
  104. * <P>
  105. * The '-' character is used to specify ranges For example &quot;10-12&quot; in
  106. * the hour field means &quot;the hours 10, 11 and 12&quot;.
  107. * <P>
  108. * The ',' character is used to specify additional values. For example
  109. * &quot;MON,WED,FRI&quot; in the day-of-week field means &quot;the days Monday,
  110. * Wednesday, and Friday&quot;.
  111. * <P>
  112. * The '/' character is used to specify increments. For example &quot;0/15&quot;
  113. * in the seconds field means &quot;the seconds 0, 15, 30, and 45&quot;. And
  114. * &quot;5/15&quot; in the seconds field means &quot;the seconds 5, 20, 35, and
  115. * 50&quot;. Specifying '*' before the '/' is equivalent to specifying 0 is
  116. * the value to start with. Essentially, for each field in the expression, there
  117. * is a set of numbers that can be turned on or off. For seconds and minutes,
  118. * the numbers range from 0 to 59. For hours 0 to 23, for days of the month 0 to
  119. * 31, and for months 0 to 11 (JAN to DEC). The &quot;/&quot; character simply helps you turn
  120. * on every &quot;nth&quot; value in the given set. Thus &quot;7/6&quot; in the
  121. * month field only turns on month &quot;7&quot;, it does NOT mean every 6th
  122. * month, please note that subtlety.
  123. * <P>
  124. * The 'L' character is allowed for the day-of-month and day-of-week fields.
  125. * This character is short-hand for &quot;last&quot;, but it has different
  126. * meaning in each of the two fields. For example, the value &quot;L&quot; in
  127. * the day-of-month field means &quot;the last day of the month&quot; - day 31
  128. * for January, day 28 for February on non-leap years. If used in the
  129. * day-of-week field by itself, it simply means &quot;7&quot; or
  130. * &quot;SAT&quot;. But if used in the day-of-week field after another value, it
  131. * means &quot;the last xxx day of the month&quot; - for example &quot;6L&quot;
  132. * means &quot;the last friday of the month&quot;. You can also specify an offset
  133. * from the last day of the month, such as "L-3" which would mean the third-to-last
  134. * day of the calendar month. <i>When using the 'L' option, it is important not to
  135. * specify lists, or ranges of values, as you'll get confusing/unexpected results.</i>
  136. * <P>
  137. * The 'W' character is allowed for the day-of-month field. This character
  138. * is used to specify the weekday (Monday-Friday) nearest the given day. As an
  139. * example, if you were to specify &quot;15W&quot; as the value for the
  140. * day-of-month field, the meaning is: &quot;the nearest weekday to the 15th of
  141. * the month&quot;. So if the 15th is a Saturday, the trigger will fire on
  142. * Friday the 14th. If the 15th is a Sunday, the trigger will fire on Monday the
  143. * 16th. If the 15th is a Tuesday, then it will fire on Tuesday the 15th.
  144. * However if you specify &quot;1W&quot; as the value for day-of-month, and the
  145. * 1st is a Saturday, the trigger will fire on Monday the 3rd, as it will not
  146. * 'jump' over the boundary of a month's days. The 'W' character can only be
  147. * specified when the day-of-month is a single day, not a range or list of days.
  148. * <P>
  149. * The 'L' and 'W' characters can also be combined for the day-of-month
  150. * expression to yield 'LW', which translates to &quot;last weekday of the
  151. * month&quot;.
  152. * <P>
  153. * The '#' character is allowed for the day-of-week field. This character is
  154. * used to specify &quot;the nth&quot; XXX day of the month. For example, the
  155. * value of &quot;6#3&quot; in the day-of-week field means the third Friday of
  156. * the month (day 6 = Friday and &quot;#3&quot; = the 3rd one in the month).
  157. * Other examples: &quot;2#1&quot; = the first Monday of the month and
  158. * &quot;4#5&quot; = the fifth Wednesday of the month. Note that if you specify
  159. * &quot;#5&quot; and there is not 5 of the given day-of-week in the month, then
  160. * no firing will occur that month. If the '#' character is used, there can
  161. * only be one expression in the day-of-week field (&quot;3#1,6#3&quot; is
  162. * not valid, since there are two expressions).
  163. * <P>
  164. * <!--The 'C' character is allowed for the day-of-month and day-of-week fields.
  165. * This character is short-hand for "calendar". This means values are
  166. * calculated against the associated calendar, if any. If no calendar is
  167. * associated, then it is equivalent to having an all-inclusive calendar. A
  168. * value of "5C" in the day-of-month field means "the first day included by the
  169. * calendar on or after the 5th". A value of "1C" in the day-of-week field
  170. * means "the first day included by the calendar on or after Sunday".-->
  171. * <P>
  172. * The legal characters and the names of months and days of the week are not
  173. * case sensitive.
  174. *
  175. * <p>
  176. * <b>NOTES:</b>
  177. * <ul>
  178. * <li>Support for specifying both a day-of-week and a day-of-month value is
  179. * not complete (you'll need to use the '?' character in one of these fields).
  180. * </li>
  181. * <li>Overflowing ranges is supported - that is, having a larger number on
  182. * the left hand side than the right. You might do 22-2 to catch 10 o'clock
  183. * at night until 2 o'clock in the morning, or you might have NOV-FEB. It is
  184. * very important to note that overuse of overflowing ranges creates ranges
  185. * that don't make sense and no effort has been made to determine which
  186. * interpretation CronExpression chooses. An example would be
  187. * "0 0 14-6 ? * FRI-MON". </li>
  188. * </ul>
  189. * </p>
  190. *
  191. *
  192. * @author Sharada Jambula, James House
  193. * @author Contributions from Mads Henderson
  194. * @author Refactoring from CronTrigger to CronExpression by Aaron Craven
  195. *
  196. * Borrowed from quartz v2.3.1
  197. *
  198. */
  199. public final class CronExpression implements Serializable, Cloneable {
  200. private static final long serialVersionUID = 12423409423L;
  201. protected static final int SECOND = 0;
  202. protected static final int MINUTE = 1;
  203. protected static final int HOUR = 2;
  204. protected static final int DAY_OF_MONTH = 3;
  205. protected static final int MONTH = 4;
  206. protected static final int DAY_OF_WEEK = 5;
  207. protected static final int YEAR = 6;
  208. protected static final int ALL_SPEC_INT = 99; // '*'
  209. protected static final int NO_SPEC_INT = 98; // '?'
  210. protected static final Integer ALL_SPEC = ALL_SPEC_INT;
  211. protected static final Integer NO_SPEC = NO_SPEC_INT;
  212. protected static final Map<String, Integer> monthMap = new HashMap<String, Integer>(20);
  213. protected static final Map<String, Integer> dayMap = new HashMap<String, Integer>(60);
  214. static {
  215. monthMap.put("JAN", 0);
  216. monthMap.put("FEB", 1);
  217. monthMap.put("MAR", 2);
  218. monthMap.put("APR", 3);
  219. monthMap.put("MAY", 4);
  220. monthMap.put("JUN", 5);
  221. monthMap.put("JUL", 6);
  222. monthMap.put("AUG", 7);
  223. monthMap.put("SEP", 8);
  224. monthMap.put("OCT", 9);
  225. monthMap.put("NOV", 10);
  226. monthMap.put("DEC", 11);
  227. dayMap.put("SUN", 1);
  228. dayMap.put("MON", 2);
  229. dayMap.put("TUE", 3);
  230. dayMap.put("WED", 4);
  231. dayMap.put("THU", 5);
  232. dayMap.put("FRI", 6);
  233. dayMap.put("SAT", 7);
  234. }
  235. private final String cronExpression;
  236. private TimeZone timeZone = null;
  237. protected transient TreeSet<Integer> seconds;
  238. protected transient TreeSet<Integer> minutes;
  239. protected transient TreeSet<Integer> hours;
  240. protected transient TreeSet<Integer> daysOfMonth;
  241. protected transient TreeSet<Integer> months;
  242. protected transient TreeSet<Integer> daysOfWeek;
  243. protected transient TreeSet<Integer> years;
  244. protected transient boolean lastdayOfWeek = false;
  245. protected transient int nthdayOfWeek = 0;
  246. protected transient boolean lastdayOfMonth = false;
  247. protected transient boolean nearestWeekday = false;
  248. protected transient int lastdayOffset = 0;
  249. protected transient boolean expressionParsed = false;
  250. public static final int MAX_YEAR = Calendar.getInstance().get(Calendar.YEAR) + 100;
  251. /**
  252. * Constructs a new <CODE>CronExpression</CODE> based on the specified
  253. * parameter.
  254. *
  255. * @param cronExpression String representation of the cron expression the
  256. * new object should represent
  257. * @throws java.text.ParseException
  258. * if the string expression cannot be parsed into a valid
  259. * <CODE>CronExpression</CODE>
  260. */
  261. public CronExpression(String cronExpression) throws ParseException {
  262. if (cronExpression == null) {
  263. throw new IllegalArgumentException("cronExpression cannot be null");
  264. }
  265. this.cronExpression = cronExpression.toUpperCase(Locale.US);
  266. buildExpression(this.cronExpression);
  267. }
  268. /**
  269. * Constructs a new {@code CronExpression} as a copy of an existing
  270. * instance.
  271. *
  272. * @param expression
  273. * The existing cron expression to be copied
  274. */
  275. public CronExpression(CronExpression expression) {
  276. /*
  277. * We don't call the other constructor here since we need to swallow the
  278. * ParseException. We also elide some of the sanity checking as it is
  279. * not logically trippable.
  280. */
  281. this.cronExpression = expression.getCronExpression();
  282. try {
  283. buildExpression(cronExpression);
  284. } catch (ParseException ex) {
  285. throw new AssertionError();
  286. }
  287. if (expression.getTimeZone() != null) {
  288. setTimeZone((TimeZone) expression.getTimeZone().clone());
  289. }
  290. }
  291. /**
  292. * Indicates whether the given date satisfies the cron expression. Note that
  293. * milliseconds are ignored, so two Dates falling on different milliseconds
  294. * of the same second will always have the same result here.
  295. *
  296. * @param date the date to evaluate
  297. * @return a boolean indicating whether the given date satisfies the cron
  298. * expression
  299. */
  300. public boolean isSatisfiedBy(Date date) {
  301. Calendar testDateCal = Calendar.getInstance(getTimeZone());
  302. testDateCal.setTime(date);
  303. testDateCal.set(Calendar.MILLISECOND, 0);
  304. Date originalDate = testDateCal.getTime();
  305. testDateCal.add(Calendar.SECOND, -1);
  306. Date timeAfter = getTimeAfter(testDateCal.getTime());
  307. return ((timeAfter != null) && (timeAfter.equals(originalDate)));
  308. }
  309. /**
  310. * Returns the next date/time <I>after</I> the given date/time which
  311. * satisfies the cron expression.
  312. *
  313. * @param date the date/time at which to begin the search for the next valid
  314. * date/time
  315. * @return the next valid date/time
  316. */
  317. public Date getNextValidTimeAfter(Date date) {
  318. return getTimeAfter(date);
  319. }
  320. /**
  321. * Returns the next date/time <I>after</I> the given date/time which does
  322. * <I>not</I> satisfy the expression
  323. *
  324. * @param date the date/time at which to begin the search for the next
  325. * invalid date/time
  326. * @return the next valid date/time
  327. */
  328. public Date getNextInvalidTimeAfter(Date date) {
  329. long difference = 1000;
  330. //move back to the nearest second so differences will be accurate
  331. Calendar adjustCal = Calendar.getInstance(getTimeZone());
  332. adjustCal.setTime(date);
  333. adjustCal.set(Calendar.MILLISECOND, 0);
  334. Date lastDate = adjustCal.getTime();
  335. Date newDate;
  336. //FUTURE_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.
  337. //keep getting the next included time until it's farther than one second
  338. // apart. At that point, lastDate is the last valid fire time. We return
  339. // the second immediately following it.
  340. while (difference == 1000) {
  341. newDate = getTimeAfter(lastDate);
  342. if(newDate == null)
  343. break;
  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. public static void validateExpression(String cronExpression) throws ParseException {
  394. new CronExpression(cronExpression);
  395. }
  396. ////////////////////////////////////////////////////////////////////////////
  397. //
  398. // Expression Parsing Functions
  399. //
  400. ////////////////////////////////////////////////////////////////////////////
  401. protected void buildExpression(String expression) throws ParseException {
  402. expressionParsed = true;
  403. try {
  404. if (seconds == null) {
  405. seconds = new TreeSet<Integer>();
  406. }
  407. if (minutes == null) {
  408. minutes = new TreeSet<Integer>();
  409. }
  410. if (hours == null) {
  411. hours = new TreeSet<Integer>();
  412. }
  413. if (daysOfMonth == null) {
  414. daysOfMonth = new TreeSet<Integer>();
  415. }
  416. if (months == null) {
  417. months = new TreeSet<Integer>();
  418. }
  419. if (daysOfWeek == null) {
  420. daysOfWeek = new TreeSet<Integer>();
  421. }
  422. if (years == null) {
  423. years = new TreeSet<Integer>();
  424. }
  425. int exprOn = SECOND;
  426. StringTokenizer exprsTok = new StringTokenizer(expression, " \t",
  427. false);
  428. while (exprsTok.hasMoreTokens() && exprOn <= YEAR) {
  429. String expr = exprsTok.nextToken().trim();
  430. // throw an exception if L is used with other days of the month
  431. if(exprOn == DAY_OF_MONTH && expr.indexOf('L') != -1 && expr.length() > 1 && expr.contains(",")) {
  432. throw new ParseException("Support for specifying 'L' and 'LW' with other days of the month is not implemented", -1);
  433. }
  434. // throw an exception if L is used with other days of the week
  435. if(exprOn == DAY_OF_WEEK && expr.indexOf('L') != -1 && expr.length() > 1 && expr.contains(",")) {
  436. throw new ParseException("Support for specifying 'L' with other days of the week is not implemented", -1);
  437. }
  438. if(exprOn == DAY_OF_WEEK && expr.indexOf('#') != -1 && expr.indexOf('#', expr.indexOf('#') +1) != -1) {
  439. throw new ParseException("Support for specifying multiple \"nth\" days is not implemented.", -1);
  440. }
  441. StringTokenizer vTok = new StringTokenizer(expr, ",");
  442. while (vTok.hasMoreTokens()) {
  443. String v = vTok.nextToken();
  444. storeExpressionVals(0, v, exprOn);
  445. }
  446. exprOn++;
  447. }
  448. if (exprOn <= DAY_OF_WEEK) {
  449. throw new ParseException("Unexpected end of expression.",
  450. expression.length());
  451. }
  452. if (exprOn <= YEAR) {
  453. storeExpressionVals(0, "*", YEAR);
  454. }
  455. TreeSet<Integer> dow = getSet(DAY_OF_WEEK);
  456. TreeSet<Integer> dom = getSet(DAY_OF_MONTH);
  457. // Copying the logic from the UnsupportedOperationException below
  458. boolean dayOfMSpec = !dom.contains(NO_SPEC);
  459. boolean dayOfWSpec = !dow.contains(NO_SPEC);
  460. if (!dayOfMSpec || dayOfWSpec) {
  461. if (!dayOfWSpec || dayOfMSpec) {
  462. throw new ParseException(
  463. "Support for specifying both a day-of-week AND a day-of-month parameter is not implemented.", 0);
  464. }
  465. }
  466. } catch (ParseException pe) {
  467. throw pe;
  468. } catch (Exception e) {
  469. throw new ParseException("Illegal cron expression format ("
  470. + e.toString() + ")", 0);
  471. }
  472. }
  473. protected int storeExpressionVals(int pos, String s, int type)
  474. throws ParseException {
  475. int incr = 0;
  476. int i = skipWhiteSpace(pos, s);
  477. if (i >= s.length()) {
  478. return i;
  479. }
  480. char c = s.charAt(i);
  481. if ((c >= 'A') && (c <= 'Z') && (!s.equals("L")) && (!s.equals("LW")) && (!s.matches("^L-[0-9]*[W]?"))) {
  482. String sub = s.substring(i, i + 3);
  483. int sval = -1;
  484. int eval = -1;
  485. if (type == MONTH) {
  486. sval = getMonthNumber(sub) + 1;
  487. if (sval <= 0) {
  488. throw new ParseException("Invalid Month value: '" + sub + "'", i);
  489. }
  490. if (s.length() > i + 3) {
  491. c = s.charAt(i + 3);
  492. if (c == '-') {
  493. i += 4;
  494. sub = s.substring(i, i + 3);
  495. eval = getMonthNumber(sub) + 1;
  496. if (eval <= 0) {
  497. throw new ParseException("Invalid Month value: '" + sub + "'", i);
  498. }
  499. }
  500. }
  501. } else if (type == DAY_OF_WEEK) {
  502. sval = getDayOfWeekNumber(sub);
  503. if (sval < 0) {
  504. throw new ParseException("Invalid Day-of-Week value: '"
  505. + sub + "'", i);
  506. }
  507. if (s.length() > i + 3) {
  508. c = s.charAt(i + 3);
  509. if (c == '-') {
  510. i += 4;
  511. sub = s.substring(i, i + 3);
  512. eval = getDayOfWeekNumber(sub);
  513. if (eval < 0) {
  514. throw new ParseException(
  515. "Invalid Day-of-Week value: '" + sub
  516. + "'", i);
  517. }
  518. } else if (c == '#') {
  519. try {
  520. i += 4;
  521. nthdayOfWeek = Integer.parseInt(s.substring(i));
  522. if (nthdayOfWeek < 1 || nthdayOfWeek > 5) {
  523. throw new Exception();
  524. }
  525. } catch (Exception e) {
  526. throw new ParseException(
  527. "A numeric value between 1 and 5 must follow the '#' option",
  528. i);
  529. }
  530. } else if (c == 'L') {
  531. lastdayOfWeek = true;
  532. i++;
  533. }
  534. }
  535. } else {
  536. throw new ParseException(
  537. "Illegal characters for this position: '" + sub + "'",
  538. i);
  539. }
  540. if (eval != -1) {
  541. incr = 1;
  542. }
  543. addToSet(sval, eval, incr, type);
  544. return (i + 3);
  545. }
  546. if (c == '?') {
  547. i++;
  548. if ((i + 1) < s.length()
  549. && (s.charAt(i) != ' ' && s.charAt(i + 1) != '\t')) {
  550. throw new ParseException("Illegal character after '?': "
  551. + s.charAt(i), i);
  552. }
  553. if (type != DAY_OF_WEEK && type != DAY_OF_MONTH) {
  554. throw new ParseException(
  555. "'?' can only be specified for Day-of-Month or Day-of-Week.",
  556. i);
  557. }
  558. if (type == DAY_OF_WEEK && !lastdayOfMonth) {
  559. int val = daysOfMonth.last();
  560. if (val == NO_SPEC_INT) {
  561. throw new ParseException(
  562. "'?' can only be specified for Day-of-Month -OR- Day-of-Week.",
  563. i);
  564. }
  565. }
  566. addToSet(NO_SPEC_INT, -1, 0, type);
  567. return i;
  568. }
  569. if (c == '*' || c == '/') {
  570. if (c == '*' && (i + 1) >= s.length()) {
  571. addToSet(ALL_SPEC_INT, -1, incr, type);
  572. return i + 1;
  573. } else if (c == '/'
  574. && ((i + 1) >= s.length() || s.charAt(i + 1) == ' ' || s
  575. .charAt(i + 1) == '\t')) {
  576. throw new ParseException("'/' must be followed by an integer.", i);
  577. } else if (c == '*') {
  578. i++;
  579. }
  580. c = s.charAt(i);
  581. if (c == '/') { // is an increment specified?
  582. i++;
  583. if (i >= s.length()) {
  584. throw new ParseException("Unexpected end of string.", i);
  585. }
  586. incr = getNumericValue(s, i);
  587. i++;
  588. if (incr > 10) {
  589. i++;
  590. }
  591. checkIncrementRange(incr, type, i);
  592. } else {
  593. incr = 1;
  594. }
  595. addToSet(ALL_SPEC_INT, -1, incr, type);
  596. return i;
  597. } else if (c == 'L') {
  598. i++;
  599. if (type == DAY_OF_MONTH) {
  600. lastdayOfMonth = true;
  601. }
  602. if (type == DAY_OF_WEEK) {
  603. addToSet(7, 7, 0, type);
  604. }
  605. if(type == DAY_OF_MONTH && s.length() > i) {
  606. c = s.charAt(i);
  607. if(c == '-') {
  608. ValueSet vs = getValue(0, s, i+1);
  609. lastdayOffset = vs.value;
  610. if(lastdayOffset > 30)
  611. throw new ParseException("Offset from last day must be <= 30", i+1);
  612. i = vs.pos;
  613. }
  614. if(s.length() > i) {
  615. c = s.charAt(i);
  616. if(c == 'W') {
  617. nearestWeekday = true;
  618. i++;
  619. }
  620. }
  621. }
  622. return i;
  623. } else if (c >= '0' && c <= '9') {
  624. int val = Integer.parseInt(String.valueOf(c));
  625. i++;
  626. if (i >= s.length()) {
  627. addToSet(val, -1, -1, type);
  628. } else {
  629. c = s.charAt(i);
  630. if (c >= '0' && c <= '9') {
  631. ValueSet vs = getValue(val, s, i);
  632. val = vs.value;
  633. i = vs.pos;
  634. }
  635. i = checkNext(i, s, val, type);
  636. return i;
  637. }
  638. } else {
  639. throw new ParseException("Unexpected character: " + c, i);
  640. }
  641. return i;
  642. }
  643. private void checkIncrementRange(int incr, int type, int idxPos) throws ParseException {
  644. if (incr > 59 && (type == SECOND || type == MINUTE)) {
  645. throw new ParseException("Increment > 60 : " + incr, idxPos);
  646. } else if (incr > 23 && (type == HOUR)) {
  647. throw new ParseException("Increment > 24 : " + incr, idxPos);
  648. } else if (incr > 31 && (type == DAY_OF_MONTH)) {
  649. throw new ParseException("Increment > 31 : " + incr, idxPos);
  650. } else if (incr > 7 && (type == DAY_OF_WEEK)) {
  651. throw new ParseException("Increment > 7 : " + incr, idxPos);
  652. } else if (incr > 12 && (type == MONTH)) {
  653. throw new ParseException("Increment > 12 : " + incr, idxPos);
  654. }
  655. }
  656. protected int checkNext(int pos, String s, int val, int type)
  657. throws ParseException {
  658. int end = -1;
  659. int i = pos;
  660. if (i >= s.length()) {
  661. addToSet(val, end, -1, type);
  662. return i;
  663. }
  664. char c = s.charAt(pos);
  665. if (c == 'L') {
  666. if (type == DAY_OF_WEEK) {
  667. if(val < 1 || val > 7)
  668. throw new ParseException("Day-of-Week values must be between 1 and 7", -1);
  669. lastdayOfWeek = true;
  670. } else {
  671. throw new ParseException("'L' option is not valid here. (pos=" + i + ")", i);
  672. }
  673. TreeSet<Integer> set = getSet(type);
  674. set.add(val);
  675. i++;
  676. return i;
  677. }
  678. if (c == 'W') {
  679. if (type == DAY_OF_MONTH) {
  680. nearestWeekday = true;
  681. } else {
  682. throw new ParseException("'W' option is not valid here. (pos=" + i + ")", i);
  683. }
  684. if(val > 31)
  685. throw new ParseException("The 'W' option does not make sense with values larger than 31 (max number of days in a month)", i);
  686. TreeSet<Integer> set = getSet(type);
  687. set.add(val);
  688. i++;
  689. return i;
  690. }
  691. if (c == '#') {
  692. if (type != DAY_OF_WEEK) {
  693. throw new ParseException("'#' option is not valid here. (pos=" + i + ")", i);
  694. }
  695. i++;
  696. try {
  697. nthdayOfWeek = Integer.parseInt(s.substring(i));
  698. if (nthdayOfWeek < 1 || nthdayOfWeek > 5) {
  699. throw new Exception();
  700. }
  701. } catch (Exception e) {
  702. throw new ParseException(
  703. "A numeric value between 1 and 5 must follow the '#' option",
  704. i);
  705. }
  706. TreeSet<Integer> set = getSet(type);
  707. set.add(val);
  708. i++;
  709. return i;
  710. }
  711. if (c == '-') {
  712. i++;
  713. c = s.charAt(i);
  714. int v = Integer.parseInt(String.valueOf(c));
  715. end = v;
  716. i++;
  717. if (i >= s.length()) {
  718. addToSet(val, end, 1, type);
  719. return i;
  720. }
  721. c = s.charAt(i);
  722. if (c >= '0' && c <= '9') {
  723. ValueSet vs = getValue(v, s, i);
  724. end = vs.value;
  725. i = vs.pos;
  726. }
  727. if (i < s.length() && ((c = s.charAt(i)) == '/')) {
  728. i++;
  729. c = s.charAt(i);
  730. int v2 = Integer.parseInt(String.valueOf(c));
  731. i++;
  732. if (i >= s.length()) {
  733. addToSet(val, end, v2, type);
  734. return i;
  735. }
  736. c = s.charAt(i);
  737. if (c >= '0' && c <= '9') {
  738. ValueSet vs = getValue(v2, s, i);
  739. int v3 = vs.value;
  740. addToSet(val, end, v3, type);
  741. i = vs.pos;
  742. return i;
  743. } else {
  744. addToSet(val, end, v2, type);
  745. return i;
  746. }
  747. } else {
  748. addToSet(val, end, 1, type);
  749. return i;
  750. }
  751. }
  752. if (c == '/') {
  753. if ((i + 1) >= s.length() || s.charAt(i + 1) == ' ' || s.charAt(i + 1) == '\t') {
  754. throw new ParseException("'/' must be followed by an integer.", i);
  755. }
  756. i++;
  757. c = s.charAt(i);
  758. int v2 = Integer.parseInt(String.valueOf(c));
  759. i++;
  760. if (i >= s.length()) {
  761. checkIncrementRange(v2, type, i);
  762. addToSet(val, end, v2, type);
  763. return i;
  764. }
  765. c = s.charAt(i);
  766. if (c >= '0' && c <= '9') {
  767. ValueSet vs = getValue(v2, s, i);
  768. int v3 = vs.value;
  769. checkIncrementRange(v3, type, i);
  770. addToSet(val, end, v3, type);
  771. i = vs.pos;
  772. return i;
  773. } else {
  774. throw new ParseException("Unexpected character '" + c + "' after '/'", i);
  775. }
  776. }
  777. addToSet(val, end, 0, type);
  778. i++;
  779. return i;
  780. }
  781. public String getCronExpression() {
  782. return cronExpression;
  783. }
  784. public String getExpressionSummary() {
  785. StringBuilder buf = new StringBuilder();
  786. buf.append("seconds: ");
  787. buf.append(getExpressionSetSummary(seconds));
  788. buf.append("\n");
  789. buf.append("minutes: ");
  790. buf.append(getExpressionSetSummary(minutes));
  791. buf.append("\n");
  792. buf.append("hours: ");
  793. buf.append(getExpressionSetSummary(hours));
  794. buf.append("\n");
  795. buf.append("daysOfMonth: ");
  796. buf.append(getExpressionSetSummary(daysOfMonth));
  797. buf.append("\n");
  798. buf.append("months: ");
  799. buf.append(getExpressionSetSummary(months));
  800. buf.append("\n");
  801. buf.append("daysOfWeek: ");
  802. buf.append(getExpressionSetSummary(daysOfWeek));
  803. buf.append("\n");
  804. buf.append("lastdayOfWeek: ");
  805. buf.append(lastdayOfWeek);
  806. buf.append("\n");
  807. buf.append("nearestWeekday: ");
  808. buf.append(nearestWeekday);
  809. buf.append("\n");
  810. buf.append("NthDayOfWeek: ");
  811. buf.append(nthdayOfWeek);
  812. buf.append("\n");
  813. buf.append("lastdayOfMonth: ");
  814. buf.append(lastdayOfMonth);
  815. buf.append("\n");
  816. buf.append("years: ");
  817. buf.append(getExpressionSetSummary(years));
  818. buf.append("\n");
  819. return buf.toString();
  820. }
  821. protected String getExpressionSetSummary(java.util.Set<Integer> set) {
  822. if (set.contains(NO_SPEC)) {
  823. return "?";
  824. }
  825. if (set.contains(ALL_SPEC)) {
  826. return "*";
  827. }
  828. StringBuilder buf = new StringBuilder();
  829. Iterator<Integer> itr = set.iterator();
  830. boolean first = true;
  831. while (itr.hasNext()) {
  832. Integer iVal = itr.next();
  833. String val = iVal.toString();
  834. if (!first) {
  835. buf.append(",");
  836. }
  837. buf.append(val);
  838. first = false;
  839. }
  840. return buf.toString();
  841. }
  842. protected String getExpressionSetSummary(java.util.ArrayList<Integer> list) {
  843. if (list.contains(NO_SPEC)) {
  844. return "?";
  845. }
  846. if (list.contains(ALL_SPEC)) {
  847. return "*";
  848. }
  849. StringBuilder buf = new StringBuilder();
  850. Iterator<Integer> itr = list.iterator();
  851. boolean first = true;
  852. while (itr.hasNext()) {
  853. Integer iVal = itr.next();
  854. String val = iVal.toString();
  855. if (!first) {
  856. buf.append(",");
  857. }
  858. buf.append(val);
  859. first = false;
  860. }
  861. return buf.toString();
  862. }
  863. protected int skipWhiteSpace(int i, String s) {
  864. for (; i < s.length() && (s.charAt(i) == ' ' || s.charAt(i) == '\t'); i++) {
  865. }
  866. return i;
  867. }
  868. protected int findNextWhiteSpace(int i, String s) {
  869. for (; i < s.length() && (s.charAt(i) != ' ' || s.charAt(i) != '\t'); i++) {
  870. }
  871. return i;
  872. }
  873. protected void addToSet(int val, int end, int incr, int type)
  874. throws ParseException {
  875. TreeSet<Integer> set = getSet(type);
  876. if (type == SECOND || type == MINUTE) {
  877. if ((val < 0 || val > 59 || end > 59) && (val != ALL_SPEC_INT)) {
  878. throw new ParseException(
  879. "Minute and Second values must be between 0 and 59",
  880. -1);
  881. }
  882. } else if (type == HOUR) {
  883. if ((val < 0 || val > 23 || end > 23) && (val != ALL_SPEC_INT)) {
  884. throw new ParseException(
  885. "Hour values must be between 0 and 23", -1);
  886. }
  887. } else if (type == DAY_OF_MONTH) {
  888. if ((val < 1 || val > 31 || end > 31) && (val != ALL_SPEC_INT)
  889. && (val != NO_SPEC_INT)) {
  890. throw new ParseException(
  891. "Day of month values must be between 1 and 31", -1);
  892. }
  893. } else if (type == MONTH) {
  894. if ((val < 1 || val > 12 || end > 12) && (val != ALL_SPEC_INT)) {
  895. throw new ParseException(
  896. "Month values must be between 1 and 12", -1);
  897. }
  898. } else if (type == DAY_OF_WEEK) {
  899. if ((val == 0 || val > 7 || end > 7) && (val != ALL_SPEC_INT)
  900. && (val != NO_SPEC_INT)) {
  901. throw new ParseException(
  902. "Day-of-Week values must be between 1 and 7", -1);
  903. }
  904. }
  905. if ((incr == 0 || incr == -1) && val != ALL_SPEC_INT) {
  906. if (val != -1) {
  907. set.add(val);
  908. } else {
  909. set.add(NO_SPEC);
  910. }
  911. return;
  912. }
  913. int startAt = val;
  914. int stopAt = end;
  915. if (val == ALL_SPEC_INT && incr <= 0) {
  916. incr = 1;
  917. set.add(ALL_SPEC); // put in a marker, but also fill values
  918. }
  919. if (type == SECOND || type == MINUTE) {
  920. if (stopAt == -1) {
  921. stopAt = 59;
  922. }
  923. if (startAt == -1 || startAt == ALL_SPEC_INT) {
  924. startAt = 0;
  925. }
  926. } else if (type == HOUR) {
  927. if (stopAt == -1) {
  928. stopAt = 23;
  929. }
  930. if (startAt == -1 || startAt == ALL_SPEC_INT) {
  931. startAt = 0;
  932. }
  933. } else if (type == DAY_OF_MONTH) {
  934. if (stopAt == -1) {
  935. stopAt = 31;
  936. }
  937. if (startAt == -1 || startAt == ALL_SPEC_INT) {
  938. startAt = 1;
  939. }
  940. } else if (type == MONTH) {
  941. if (stopAt == -1) {
  942. stopAt = 12;
  943. }
  944. if (startAt == -1 || startAt == ALL_SPEC_INT) {
  945. startAt = 1;
  946. }
  947. } else if (type == DAY_OF_WEEK) {
  948. if (stopAt == -1) {
  949. stopAt = 7;
  950. }
  951. if (startAt == -1 || startAt == ALL_SPEC_INT) {
  952. startAt = 1;
  953. }
  954. } else if (type == YEAR) {
  955. if (stopAt == -1) {
  956. stopAt = MAX_YEAR;
  957. }
  958. if (startAt == -1 || startAt == ALL_SPEC_INT) {
  959. startAt = 1970;
  960. }
  961. }
  962. // if the end of the range is before the start, then we need to overflow into
  963. // the next day, month etc. This is done by adding the maximum amount for that
  964. // type, and using modulus max to determine the value being added.
  965. int max = -1;
  966. if (stopAt < startAt) {
  967. switch (type) {
  968. case SECOND : max = 60; break;
  969. case MINUTE : max = 60; break;
  970. case HOUR : max = 24; break;
  971. case MONTH : max = 12; break;
  972. case DAY_OF_WEEK : max = 7; break;
  973. case DAY_OF_MONTH : max = 31; break;
  974. case YEAR : throw new IllegalArgumentException("Start year must be less than stop year");
  975. default : throw new IllegalArgumentException("Unexpected type encountered");
  976. }
  977. stopAt += max;
  978. }
  979. for (int i = startAt; i <= stopAt; i += incr) {
  980. if (max == -1) {
  981. // ie: there's no max to overflow over
  982. set.add(i);
  983. } else {
  984. // take the modulus to get the real value
  985. int i2 = i % max;
  986. // 1-indexed ranges should not include 0, and should include their max
  987. if (i2 == 0 && (type == MONTH || type == DAY_OF_WEEK || type == DAY_OF_MONTH) ) {
  988. i2 = max;
  989. }
  990. set.add(i2);
  991. }
  992. }
  993. }
  994. TreeSet<Integer> getSet(int type) {
  995. switch (type) {
  996. case SECOND:
  997. return seconds;
  998. case MINUTE:
  999. return minutes;
  1000. case HOUR:
  1001. return hours;
  1002. case DAY_OF_MONTH:
  1003. return daysOfMonth;
  1004. case MONTH:
  1005. return months;
  1006. case DAY_OF_WEEK:
  1007. return daysOfWeek;
  1008. case YEAR:
  1009. return years;
  1010. default:
  1011. return null;
  1012. }
  1013. }
  1014. protected ValueSet getValue(int v, String s, int i) {
  1015. char c = s.charAt(i);
  1016. StringBuilder s1 = new StringBuilder(String.valueOf(v));
  1017. while (c >= '0' && c <= '9') {
  1018. s1.append(c);
  1019. i++;
  1020. if (i >= s.length()) {
  1021. break;
  1022. }
  1023. c = s.charAt(i);
  1024. }
  1025. ValueSet val = new ValueSet();
  1026. val.pos = (i < s.length()) ? i : i + 1;
  1027. val.value = Integer.parseInt(s1.toString());
  1028. return val;
  1029. }
  1030. protected int getNumericValue(String s, int i) {
  1031. int endOfVal = findNextWhiteSpace(i, s);
  1032. String val = s.substring(i, endOfVal);
  1033. return Integer.parseInt(val);
  1034. }
  1035. protected int getMonthNumber(String s) {
  1036. Integer integer = monthMap.get(s);
  1037. if (integer == null) {
  1038. return -1;
  1039. }
  1040. return integer;
  1041. }
  1042. protected int getDayOfWeekNumber(String s) {
  1043. Integer integer = dayMap.get(s);
  1044. if (integer == null) {
  1045. return -1;
  1046. }
  1047. return integer;
  1048. }
  1049. ////////////////////////////////////////////////////////////////////////////
  1050. //
  1051. // Computation Functions
  1052. //
  1053. ////////////////////////////////////////////////////////////////////////////
  1054. public Date getTimeAfter(Date afterTime) {
  1055. // Computation is based on Gregorian year only.
  1056. Calendar cl = new java.util.GregorianCalendar(getTimeZone());
  1057. // move ahead one second, since we're computing the time *after* the
  1058. // given time
  1059. afterTime = new Date(afterTime.getTime() + 1000);
  1060. // CronTrigger does not deal with milliseconds
  1061. cl.setTime(afterTime);
  1062. cl.set(Calendar.MILLISECOND, 0);
  1063. boolean gotOne = false;
  1064. // loop until we've computed the next time, or we've past the endTime
  1065. while (!gotOne) {
  1066. //if (endTime != null && cl.getTime().after(endTime)) return null;
  1067. if(cl.get(Calendar.YEAR) > 2999) { // prevent endless loop...
  1068. return null;
  1069. }
  1070. SortedSet<Integer> st = null;
  1071. int t = 0;
  1072. int sec = cl.get(Calendar.SECOND);
  1073. int min = cl.get(Calendar.MINUTE);
  1074. // get second.................................................
  1075. st = seconds.tailSet(sec);
  1076. if (st != null && st.size() != 0) {
  1077. sec = st.first();
  1078. } else {
  1079. sec = seconds.first();
  1080. min++;
  1081. cl.set(Calendar.MINUTE, min);
  1082. }
  1083. cl.set(Calendar.SECOND, sec);
  1084. min = cl.get(Calendar.MINUTE);
  1085. int hr = cl.get(Calendar.HOUR_OF_DAY);
  1086. t = -1;
  1087. // get minute.................................................
  1088. st = minutes.tailSet(min);
  1089. if (st != null && st.size() != 0) {
  1090. t = min;
  1091. min = st.first();
  1092. } else {
  1093. min = minutes.first();
  1094. hr++;
  1095. }
  1096. if (min != t) {
  1097. cl.set(Calendar.SECOND, 0);
  1098. cl.set(Calendar.MINUTE, min);
  1099. setCalendarHour(cl, hr);
  1100. continue;
  1101. }
  1102. cl.set(Calendar.MINUTE, min);
  1103. hr = cl.get(Calendar.HOUR_OF_DAY);
  1104. int day = cl.get(Calendar.DAY_OF_MONTH);
  1105. t = -1;
  1106. // get hour...................................................
  1107. st = hours.tailSet(hr);
  1108. if (st != null && st.size() != 0) {
  1109. t = hr;
  1110. hr = st.first();
  1111. } else {
  1112. hr = hours.first();
  1113. day++;
  1114. }
  1115. if (hr != t) {
  1116. cl.set(Calendar.SECOND, 0);
  1117. cl.set(Calendar.MINUTE, 0);
  1118. cl.set(Calendar.DAY_OF_MONTH, day);
  1119. setCalendarHour(cl, hr);
  1120. continue;
  1121. }
  1122. cl.set(Calendar.HOUR_OF_DAY, hr);
  1123. day = cl.get(Calendar.DAY_OF_MONTH);
  1124. int mon = cl.get(Calendar.MONTH) + 1;
  1125. // '+ 1' because calendar is 0-based for this field, and we are
  1126. // 1-based
  1127. t = -1;
  1128. int tmon = mon;
  1129. // get day...................................................
  1130. boolean dayOfMSpec = !daysOfMonth.contains(NO_SPEC);
  1131. boolean dayOfWSpec = !daysOfWeek.contains(NO_SPEC);
  1132. if (dayOfMSpec && !dayOfWSpec) { // get day by day of month rule
  1133. st = daysOfMonth.tailSet(day);
  1134. if (lastdayOfMonth) {
  1135. if(!nearestWeekday) {
  1136. t = day;
  1137. day = getLastDayOfMonth(mon, cl.get(Calendar.YEAR));
  1138. day -= lastdayOffset;
  1139. if(t > day) {
  1140. mon++;
  1141. if(mon > 12) {
  1142. mon = 1;
  1143. tmon = 3333; // ensure test of mon != tmon further below fails
  1144. cl.add(Calendar.YEAR, 1);
  1145. }
  1146. day = 1;
  1147. }
  1148. } else {
  1149. t = day;
  1150. day = getLastDayOfMonth(mon, cl.get(Calendar.YEAR));
  1151. day -= lastdayOffset;
  1152. java.util.Calendar tcal = java.util.Calendar.getInstance(getTimeZone());
  1153. tcal.set(Calendar.SECOND, 0);
  1154. tcal.set(Calendar.MINUTE, 0);
  1155. tcal.set(Calendar.HOUR_OF_DAY, 0);
  1156. tcal.set(Calendar.DAY_OF_MONTH, day);
  1157. tcal.set(Calendar.MONTH, mon - 1);
  1158. tcal.set(Calendar.YEAR, cl.get(Calendar.YEAR));
  1159. int ldom = getLastDayOfMonth(mon, cl.get(Calendar.YEAR));
  1160. int dow = tcal.get(Calendar.DAY_OF_WEEK);
  1161. if(dow == Calendar.SATURDAY && day == 1) {
  1162. day += 2;
  1163. } else if(dow == Calendar.SATURDAY) {
  1164. day -= 1;
  1165. } else if(dow == Calendar.SUNDAY && day == ldom) {
  1166. day -= 2;
  1167. } else if(dow == Calendar.SUNDAY) {
  1168. day += 1;
  1169. }
  1170. tcal.set(Calendar.SECOND, sec);
  1171. tcal.set(Calendar.MINUTE, min);
  1172. tcal.set(Calendar.HOUR_OF_DAY, hr);
  1173. tcal.set(Calendar.DAY_OF_MONTH, day);
  1174. tcal.set(Calendar.MONTH, mon - 1);
  1175. Date nTime = tcal.getTime();
  1176. if(nTime.before(afterTime)) {
  1177. day = 1;
  1178. mon++;
  1179. }
  1180. }
  1181. } else if(nearestWeekday) {
  1182. t = day;
  1183. day = daysOfMonth.first();
  1184. java.util.Calendar tcal = java.util.Calendar.getInstance(getTimeZone());
  1185. tcal.set(Calendar.SECOND, 0);
  1186. tcal.set(Calendar.MINUTE, 0);
  1187. tcal.set(Calendar.HOUR_OF_DAY, 0);
  1188. tcal.set(Calendar.DAY_OF_MONTH, day);
  1189. tcal.set(Calendar.MONTH, mon - 1);
  1190. tcal.set(Calendar.YEAR, cl.get(Calendar.YEAR));
  1191. int ldom = getLastDayOfMonth(mon, cl.get(Calendar.YEAR));
  1192. int dow = tcal.get(Calendar.DAY_OF_WEEK);
  1193. if(dow == Calendar.SATURDAY && day == 1) {
  1194. day += 2;
  1195. } else if(dow == Calendar.SATURDAY) {
  1196. day -= 1;
  1197. } else if(dow == Calendar.SUNDAY && day == ldom) {
  1198. day -= 2;
  1199. } else if(dow == Calendar.SUNDAY) {
  1200. day += 1;
  1201. }
  1202. tcal.set(Calendar.SECOND, sec);
  1203. tcal.set(Calendar.MINUTE, min);
  1204. tcal.set(Calendar.HOUR_OF_DAY, hr);
  1205. tcal.set(Calendar.DAY_OF_MONTH, day);
  1206. tcal.set(Calendar.MONTH, mon - 1);
  1207. Date nTime = tcal.getTime();
  1208. if(nTime.before(afterTime)) {
  1209. day = daysOfMonth.first();
  1210. mon++;
  1211. }
  1212. } else if (st != null && st.size() != 0) {
  1213. t = day;
  1214. day = st.first();
  1215. // make sure we don't over-run a short month, such as february
  1216. int lastDay = getLastDayOfMonth(mon, cl.get(Calendar.YEAR));
  1217. if (day > lastDay) {
  1218. day = daysOfMonth.first();
  1219. mon++;
  1220. }
  1221. } else {
  1222. day = daysOfMonth.first();
  1223. mon++;
  1224. }
  1225. if (day != t || mon != tmon) {
  1226. cl.set(Calendar.SECOND, 0);
  1227. cl.set(Calendar.MINUTE, 0);
  1228. cl.set(Calendar.HOUR_OF_DAY, 0);
  1229. cl.set(Calendar.DAY_OF_MONTH, day);
  1230. cl.set(Calendar.MONTH, mon - 1);
  1231. // '- 1' because calendar is 0-based for this field, and we
  1232. // are 1-based
  1233. continue;
  1234. }
  1235. } else if (dayOfWSpec && !dayOfMSpec) { // get day by day of week rule
  1236. if (lastdayOfWeek) { // are we looking for the last XXX day of
  1237. // the month?
  1238. int dow = daysOfWeek.first(); // desired
  1239. // d-o-w
  1240. int cDow = cl.get(Calendar.DAY_OF_WEEK); // current d-o-w
  1241. int daysToAdd = 0;
  1242. if (cDow < dow) {
  1243. daysToAdd = dow - cDow;
  1244. }
  1245. if (cDow > dow) {
  1246. daysToAdd = dow + (7 - cDow);
  1247. }
  1248. int lDay = getLastDayOfMonth(mon, cl.get(Calendar.YEAR));
  1249. if (day + daysToAdd > lDay) { // did we already miss the
  1250. // last one?
  1251. cl.set(Calendar.SECOND, 0);
  1252. cl.set(Calendar.MINUTE, 0);
  1253. cl.set(Calendar.HOUR_OF_DAY, 0);
  1254. cl.set(Calendar.DAY_OF_MONTH, 1);
  1255. cl.set(Calendar.MONTH, mon);
  1256. // no '- 1' here because we are promoting the month
  1257. continue;
  1258. }
  1259. // find date of last occurrence of this day in this month...
  1260. while ((day + daysToAdd + 7) <= lDay) {
  1261. daysToAdd += 7;
  1262. }
  1263. day += daysToAdd;
  1264. if (daysToAdd > 0) {
  1265. cl.set(Calendar.SECOND, 0);
  1266. cl.set(Calendar.MINUTE, 0);
  1267. cl.set(Calendar.HOUR_OF_DAY, 0);
  1268. cl.set(Calendar.DAY_OF_MONTH, day);
  1269. cl.set(Calendar.MONTH, mon - 1);
  1270. // '- 1' here because we are not promoting the month
  1271. continue;
  1272. }
  1273. } else if (nthdayOfWeek != 0) {
  1274. // are we looking for the Nth XXX day in the month?
  1275. int dow = daysOfWeek.first(); // desired
  1276. // d-o-w
  1277. int cDow = cl.get(Calendar.DAY_OF_WEEK); // current d-o-w
  1278. int daysToAdd = 0;
  1279. if (cDow < dow) {
  1280. daysToAdd = dow - cDow;
  1281. } else if (cDow > dow) {
  1282. daysToAdd = dow + (7 - cDow);
  1283. }
  1284. boolean dayShifted = false;
  1285. if (daysToAdd > 0) {
  1286. dayShifted = true;
  1287. }
  1288. day += daysToAdd;
  1289. int weekOfMonth = day / 7;
  1290. if (day % 7 > 0) {
  1291. weekOfMonth++;
  1292. }
  1293. daysToAdd = (nthdayOfWeek - weekOfMonth) * 7;
  1294. day += daysToAdd;
  1295. if (daysToAdd < 0
  1296. || day > getLastDayOfMonth(mon, cl
  1297. .get(Calendar.YEAR))) {
  1298. cl.set(Calendar.SECOND, 0);
  1299. cl.set(Calendar.MINUTE, 0);
  1300. cl.set(Calendar.HOUR_OF_DAY, 0);
  1301. cl.set(Calendar.DAY_OF_MONTH, 1);
  1302. cl.set(Calendar.MONTH, mon);
  1303. // no '- 1' here because we are promoting the month
  1304. continue;
  1305. } else if (daysToAdd > 0 || dayShifted) {
  1306. cl.set(Calendar.SECOND, 0);
  1307. cl.set(Calendar.MINUTE, 0);
  1308. cl.set(Calendar.HOUR_OF_DAY, 0);
  1309. cl.set(Calendar.DAY_OF_MONTH, day);
  1310. cl.set(Calendar.MONTH, mon - 1);
  1311. // '- 1' here because we are NOT promoting the month
  1312. continue;
  1313. }
  1314. } else {
  1315. int cDow = cl.get(Calendar.DAY_OF_WEEK); // current d-o-w
  1316. int dow = daysOfWeek.first(); // desired
  1317. // d-o-w
  1318. st = daysOfWeek.tailSet(cDow);
  1319. if (st != null && st.size() > 0) {
  1320. dow = st.first();
  1321. }
  1322. int daysToAdd = 0;
  1323. if (cDow < dow) {
  1324. daysToAdd = dow - cDow;
  1325. }
  1326. if (cDow > dow) {
  1327. daysToAdd = dow + (7 - cDow);
  1328. }
  1329. int lDay = getLastDayOfMonth(mon, cl.get(Calendar.YEAR));
  1330. if (day + daysToAdd > lDay) { // will we pass the end of
  1331. // the month?
  1332. cl.set(Calendar.SECOND, 0);
  1333. cl.set(Calendar.MINUTE, 0);
  1334. cl.set(Calendar.HOUR_OF_DAY, 0);
  1335. cl.set(Calendar.DAY_OF_MONTH, 1);
  1336. cl.set(Calendar.MONTH, mon);
  1337. // no '- 1' here because we are promoting the month
  1338. continue;
  1339. } else if (daysToAdd > 0) { // are we swithing days?
  1340. cl.set(Calendar.SECOND, 0);
  1341. cl.set(Calendar.MINUTE, 0);
  1342. cl.set(Calendar.HOUR_OF_DAY, 0);
  1343. cl.set(Calendar.DAY_OF_MONTH, day + daysToAdd);
  1344. cl.set(Calendar.MONTH, mon - 1);
  1345. // '- 1' because calendar is 0-based for this field,
  1346. // and we are 1-based
  1347. continue;
  1348. }
  1349. }
  1350. } else { // dayOfWSpec && !dayOfMSpec
  1351. throw new UnsupportedOperationException(
  1352. "Support for specifying both a day-of-week AND a day-of-month parameter is not implemented.");
  1353. }
  1354. cl.set(Calendar.DAY_OF_MONTH, day);
  1355. mon = cl.get(Calendar.MONTH) + 1;
  1356. // '+ 1' because calendar is 0-based for this field, and we are
  1357. // 1-based
  1358. int year = cl.get(Calendar.YEAR);
  1359. t = -1;
  1360. // test for expressions that never generate a valid fire date,
  1361. // but keep looping...
  1362. if (year > MAX_YEAR) {
  1363. return null;
  1364. }
  1365. // get month...................................................
  1366. st = months.tailSet(mon);
  1367. if (st != null && st.size() != 0) {
  1368. t = mon;
  1369. mon = st.first();
  1370. } else {
  1371. mon = months.first();
  1372. year++;
  1373. }
  1374. if (mon != t) {
  1375. cl.set(Calendar.SECOND, 0);
  1376. cl.set(Calendar.MINUTE, 0);
  1377. cl.set(Calendar.HOUR_OF_DAY, 0);
  1378. cl.set(Calendar.DAY_OF_MONTH, 1);
  1379. cl.set(Calendar.MONTH, mon - 1);
  1380. // '- 1' because calendar is 0-based for this field, and we are
  1381. // 1-based
  1382. cl.set(Calendar.YEAR, year);
  1383. continue;
  1384. }
  1385. cl.set(Calendar.MONTH, mon - 1);
  1386. // '- 1' because calendar is 0-based for this field, and we are
  1387. // 1-based
  1388. year = cl.get(Calendar.YEAR);
  1389. t = -1;
  1390. // get year...................................................
  1391. st = years.tailSet(year);
  1392. if (st != null && st.size() != 0) {
  1393. t = year;
  1394. year = st.first();
  1395. } else {
  1396. return null; // ran out of years...
  1397. }
  1398. if (year != t) {
  1399. cl.set(Calendar.SECOND, 0);
  1400. cl.set(Calendar.MINUTE, 0);
  1401. cl.set(Calendar.HOUR_OF_DAY, 0);
  1402. cl.set(Calendar.DAY_OF_MONTH, 1);
  1403. cl.set(Calendar.MONTH, 0);
  1404. // '- 1' because calendar is 0-based for this field, and we are
  1405. // 1-based
  1406. cl.set(Calendar.YEAR, year);
  1407. continue;
  1408. }
  1409. cl.set(Calendar.YEAR, year);
  1410. gotOne = true;
  1411. } // while( !done )
  1412. return cl.getTime();
  1413. }
  1414. /**
  1415. * Advance the calendar to the particular hour paying particular attention
  1416. * to daylight saving problems.
  1417. *
  1418. * @param cal the calendar to operate on
  1419. * @param hour the hour to set
  1420. */
  1421. protected void setCalendarHour(Calendar cal, int hour) {
  1422. cal.set(java.util.Calendar.HOUR_OF_DAY, hour);
  1423. if (cal.get(java.util.Calendar.HOUR_OF_DAY) != hour && hour != 24) {
  1424. cal.set(java.util.Calendar.HOUR_OF_DAY, hour + 1);
  1425. }
  1426. }
  1427. /**
  1428. * NOT YET IMPLEMENTED: Returns the time before the given time
  1429. * that the <code>CronExpression</code> matches.
  1430. */
  1431. public Date getTimeBefore(Date endTime) {
  1432. // FUTURE_TODO: implement QUARTZ-423
  1433. return null;
  1434. }
  1435. /**
  1436. * NOT YET IMPLEMENTED: Returns the final time that the
  1437. * <code>CronExpression</code> will match.
  1438. */
  1439. public Date getFinalFireTime() {
  1440. // FUTURE_TODO: implement QUARTZ-423
  1441. return null;
  1442. }
  1443. protected boolean isLeapYear(int year) {
  1444. return ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0));
  1445. }
  1446. protected int getLastDayOfMonth(int monthNum, int year) {
  1447. switch (monthNum) {
  1448. case 1:
  1449. return 31;
  1450. case 2:
  1451. return (isLeapYear(year)) ? 29 : 28;
  1452. case 3:
  1453. return 31;
  1454. case 4:
  1455. return 30;
  1456. case 5:
  1457. return 31;
  1458. case 6:
  1459. return 30;
  1460. case 7:
  1461. return 31;
  1462. case 8:
  1463. return 31;
  1464. case 9:
  1465. return 30;
  1466. case 10:
  1467. return 31;
  1468. case 11:
  1469. return 30;
  1470. case 12:
  1471. return 31;
  1472. default:
  1473. throw new IllegalArgumentException("Illegal month number: "
  1474. + monthNum);
  1475. }
  1476. }
  1477. private void readObject(java.io.ObjectInputStream stream)
  1478. throws java.io.IOException, ClassNotFoundException {
  1479. stream.defaultReadObject();
  1480. try {
  1481. buildExpression(cronExpression);
  1482. } catch (Exception ignore) {
  1483. } // never happens
  1484. }
  1485. @Override
  1486. @Deprecated
  1487. public Object clone() {
  1488. return new CronExpression(this);
  1489. }
  1490. }
  1491. class ValueSet {
  1492. public int value;
  1493. public int pos;
  1494. }