Browse Source

(Re)introduce CronExpression::isValidExpression

This commit introduces CronExpression::isValidExpression, which was also
present on the deprecated CronSequenceGenerator.

Closes: gh-26996
pull/27009/head
Arjen Poutsma 4 years ago
parent
commit
6f2fe5ddcb
  1. 21
      spring-context/src/main/java/org/springframework/scheduling/support/CronExpression.java
  2. 10
      spring-context/src/test/java/org/springframework/scheduling/support/CronExpressionTests.java

21
spring-context/src/main/java/org/springframework/scheduling/support/CronExpression.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2020 the original author or authors.
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -202,6 +202,25 @@ public final class CronExpression { @@ -202,6 +202,25 @@ public final class CronExpression {
}
}
/**
* Determine whether the given string represents a valid cron expression.
* @param expression the expression to evaluate
* @return {@code true} if the given expression is a valid cron expression
* @since 5.3.8
*/
public static boolean isValidExpression(@Nullable String expression) {
if (expression == null) {
return false;
}
try {
parse(expression);
return true;
}
catch (IllegalArgumentException ex) {
return false;
}
}
private static String resolveMacros(String expression) {
expression = expression.trim();

10
spring-context/src/test/java/org/springframework/scheduling/support/CronExpressionTests.java

@ -51,6 +51,16 @@ class CronExpressionTests { @@ -51,6 +51,16 @@ class CronExpressionTests {
}
};
@Test
public void isValidExpression() {
assertThat(CronExpression.isValidExpression(null)).isFalse();
assertThat(CronExpression.isValidExpression("")).isFalse();
assertThat(CronExpression.isValidExpression("*")).isFalse();
assertThat(CronExpression.isValidExpression("* * * * *")).isFalse();
assertThat(CronExpression.isValidExpression("* * * * * * *")).isFalse();
assertThat(CronExpression.isValidExpression("* * * * * *")).isTrue();
}
@Test
void matchAll() {

Loading…
Cancel
Save