Added cron expression validation method for CronSequenceGenerator
It's handy to know in advance whether or not expression that is passed to CronSequenceGenerator or CronTrigger constructor would not results in IllegalArgumentException. The only way to do it now is to try\catch an instance creation but it's kinda ugly.
This commit is contained in:
parent
6e4e52b23a
commit
31d634e6bf
|
|
@ -149,6 +149,22 @@ public class CronSequenceGenerator {
|
|||
return calendar.getTime();
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicates whether the specified cron expression can be parsed into a
|
||||
* valid cron sequence generator
|
||||
* @param cronExpression the expression to evaluate
|
||||
* @return a boolean indicating whether the given expression is a valid cron
|
||||
* expression
|
||||
*/
|
||||
public static boolean isValidExpression(String cronExpression) {
|
||||
String[] fields = StringUtils.tokenizeToStringArray(cronExpression, " ");
|
||||
return validateCronFields(fields);
|
||||
}
|
||||
|
||||
private static boolean validateCronFields(String[] fields) {
|
||||
return fields != null && fields.length == 6;
|
||||
}
|
||||
|
||||
private void doNext(Calendar calendar, int dot) {
|
||||
List<Integer> resets = new ArrayList<Integer>();
|
||||
|
||||
|
|
@ -262,7 +278,7 @@ public class CronSequenceGenerator {
|
|||
*/
|
||||
private void parse(String expression) throws IllegalArgumentException {
|
||||
String[] fields = StringUtils.tokenizeToStringArray(expression, " ");
|
||||
if (fields.length != 6) {
|
||||
if (!validateCronFields(fields)) {
|
||||
throw new IllegalArgumentException(String.format(
|
||||
"Cron expression must consist of 6 fields (found %d in \"%s\")", fields.length, expression));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -56,4 +56,18 @@ public class CronSequenceGeneratorTests {
|
|||
new CronSequenceGenerator("*/-1 * * * * *").next(new Date(2012, 6, 1, 9, 0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testValidExpression() {
|
||||
assertTrue(CronSequenceGenerator.isValidExpression("0 */2 1-4 * * *"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNotValidExpression() {
|
||||
assertFalse(CronSequenceGenerator.isValidExpression("0 */2 1-4 * * * *"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNullExpression() {
|
||||
assertFalse(CronSequenceGenerator.isValidExpression(null));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue