From 6f2fe5ddcbaf4563f52d474c002cddf2ae6371e6 Mon Sep 17 00:00:00 2001 From: Arjen Poutsma Date: Mon, 31 May 2021 14:28:55 +0200 Subject: [PATCH] (Re)introduce CronExpression::isValidExpression This commit introduces CronExpression::isValidExpression, which was also present on the deprecated CronSequenceGenerator. Closes: gh-26996 --- .../scheduling/support/CronExpression.java | 21 ++++++++++++++++++- .../support/CronExpressionTests.java | 10 +++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/spring-context/src/main/java/org/springframework/scheduling/support/CronExpression.java b/spring-context/src/main/java/org/springframework/scheduling/support/CronExpression.java index 08a6444a6b..120ced6132 100644 --- a/spring-context/src/main/java/org/springframework/scheduling/support/CronExpression.java +++ b/spring-context/src/main/java/org/springframework/scheduling/support/CronExpression.java @@ -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 { } } + /** + * 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(); diff --git a/spring-context/src/test/java/org/springframework/scheduling/support/CronExpressionTests.java b/spring-context/src/test/java/org/springframework/scheduling/support/CronExpressionTests.java index 23319d5ca9..104e482828 100644 --- a/spring-context/src/test/java/org/springframework/scheduling/support/CronExpressionTests.java +++ b/spring-context/src/test/java/org/springframework/scheduling/support/CronExpressionTests.java @@ -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() {