/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang3; import java.util.Collection; import java.util.Iterator; import java.util.Map; import java.util.Objects; import java.util.function.Supplier; import java.util.regex.Pattern; /** * This class assists in validating arguments. The validation methods are * based along the following principles: *
All exceptions messages are * format strings * as defined by the Java platform. For example: * *
* Validate.isTrue(i > 0, "The value must be greater than zero: %d", i); * Validate.notNull(surname, "The surname must not be %s", null); ** *
#ThreadSafe#
* @see String#format(String, Object...) * @since 2.0 */ public class Validate { private static final String DEFAULT_NOT_NAN_EX_MESSAGE = "The validated value is not a number"; private static final String DEFAULT_FINITE_EX_MESSAGE = "The value is invalid: %f"; private static final String DEFAULT_EXCLUSIVE_BETWEEN_EX_MESSAGE = "The value %s is not in the specified exclusive range of %s to %s"; private static final String DEFAULT_INCLUSIVE_BETWEEN_EX_MESSAGE = "The value %s is not in the specified inclusive range of %s to %s"; private static final String DEFAULT_MATCHES_PATTERN_EX = "The string %s does not match the pattern %s"; private static final String DEFAULT_IS_NULL_EX_MESSAGE = "The validated object is null"; private static final String DEFAULT_IS_TRUE_EX_MESSAGE = "The validated expression is false"; private static final String DEFAULT_NO_NULL_ELEMENTS_ARRAY_EX_MESSAGE = "The validated array contains null element at index: %d"; private static final String DEFAULT_NO_NULL_ELEMENTS_COLLECTION_EX_MESSAGE = "The validated collection contains null element at index: %d"; private static final String DEFAULT_NOT_BLANK_EX_MESSAGE = "The validated character sequence is blank"; private static final String DEFAULT_NOT_EMPTY_ARRAY_EX_MESSAGE = "The validated array is empty"; private static final String DEFAULT_NOT_EMPTY_CHAR_SEQUENCE_EX_MESSAGE = "The validated character sequence is empty"; private static final String DEFAULT_NOT_EMPTY_COLLECTION_EX_MESSAGE = "The validated collection is empty"; private static final String DEFAULT_NOT_EMPTY_MAP_EX_MESSAGE = "The validated map is empty"; private static final String DEFAULT_VALID_INDEX_ARRAY_EX_MESSAGE = "The validated array index is invalid: %d"; private static final String DEFAULT_VALID_INDEX_CHAR_SEQUENCE_EX_MESSAGE = "The validated character sequence index is invalid: %d"; private static final String DEFAULT_VALID_INDEX_COLLECTION_EX_MESSAGE = "The validated collection index is invalid: %d"; private static final String DEFAULT_VALID_STATE_EX_MESSAGE = "The validated state is false"; private static final String DEFAULT_IS_ASSIGNABLE_EX_MESSAGE = "Cannot assign a %s to a %s"; private static final String DEFAULT_IS_INSTANCE_OF_EX_MESSAGE = "Expected type: %s, actual: %s"; /** * Validate that the specified primitive value falls between the two * exclusive values specified; otherwise, throws an exception. * *Validate.exclusiveBetween(0.1, 2.1, 1.1);* * @param start the exclusive start value * @param end the exclusive end value * @param value the value to validate * @throws IllegalArgumentException if the value falls out of the boundaries * @since 3.3 */ @SuppressWarnings("boxing") public static void exclusiveBetween(final double start, final double end, final double value) { // TODO when breaking BC, consider returning value if (value <= start || value >= end) { throw new IllegalArgumentException(String.format(DEFAULT_EXCLUSIVE_BETWEEN_EX_MESSAGE, value, start, end)); } } /** * Validate that the specified primitive value falls between the two * exclusive values specified; otherwise, throws an exception with the * specified message. * *
Validate.exclusiveBetween(0.1, 2.1, 1.1, "Not in range");* * @param start the exclusive start value * @param end the exclusive end value * @param value the value to validate * @param message the exception message if invalid, not null * @throws IllegalArgumentException if the value falls outside the boundaries * @since 3.3 */ public static void exclusiveBetween(final double start, final double end, final double value, final String message) { // TODO when breaking BC, consider returning value if (value <= start || value >= end) { throw new IllegalArgumentException(message); } } /** * Validate that the specified primitive value falls between the two * exclusive values specified; otherwise, throws an exception. * *
Validate.exclusiveBetween(0, 2, 1);* * @param start the exclusive start value * @param end the exclusive end value * @param value the value to validate * @throws IllegalArgumentException if the value falls out of the boundaries * @since 3.3 */ @SuppressWarnings("boxing") public static void exclusiveBetween(final long start, final long end, final long value) { // TODO when breaking BC, consider returning value if (value <= start || value >= end) { throw new IllegalArgumentException(String.format(DEFAULT_EXCLUSIVE_BETWEEN_EX_MESSAGE, value, start, end)); } } /** * Validate that the specified primitive value falls between the two * exclusive values specified; otherwise, throws an exception with the * specified message. * *
Validate.exclusiveBetween(0, 2, 1, "Not in range");* * @param start the exclusive start value * @param end the exclusive end value * @param value the value to validate * @param message the exception message if invalid, not null * @throws IllegalArgumentException if the value falls outside the boundaries * @since 3.3 */ public static void exclusiveBetween(final long start, final long end, final long value, final String message) { // TODO when breaking BC, consider returning value if (value <= start || value >= end) { throw new IllegalArgumentException(message); } } /** * Validate that the specified argument object fall between the two * exclusive values specified; otherwise, throws an exception. * *
Validate.exclusiveBetween(0, 2, 1);* * @param
Validate.exclusiveBetween(0, 2, 1, "Not in boundaries");* * @param
Validate.finite(myDouble);* *
The message of the exception is "The value is invalid: %f".
* * @param value the value to validate * @throws IllegalArgumentException if the value is infinite or Not-a-Number (NaN) * @see #finite(double, String, Object...) * @since 3.5 */ public static void finite(final double value) { finite(value, DEFAULT_FINITE_EX_MESSAGE, value); } /** * Validates that the specified argument is not infinite or Not-a-Number (NaN); * otherwise throwing an exception with the specified message. * *Validate.finite(myDouble, "The argument must contain a numeric value");* * @param value the value to validate * @param message the {@link String#format(String, Object...)} exception message if invalid, not null * @param values the optional values for the formatted exception message * @throws IllegalArgumentException if the value is infinite or Not-a-Number (NaN) * @see #finite(double) * @since 3.5 */ public static void finite(final double value, final String message, final Object... values) { if (Double.isNaN(value) || Double.isInfinite(value)) { throw new IllegalArgumentException(getMessage(message, values)); } } /** * Gets the message using {@link String#format(String, Object...) String.format(message, values)} * if the values are not empty, otherwise return the message unformatted. * This method exists to allow validation methods declaring a String message and varargs parameters * to be used without any message parameters when the message contains special characters, * e.g. {@code Validate.isTrue(false, "%Failed%")}. * * @param message the {@link String#format(String, Object...)} exception message if invalid, not null * @param values the optional values for the formatted message * @return formatted message using {@link String#format(String, Object...) String.format(message, values)} * if the values are not empty, otherwise return the unformatted message. */ private static String getMessage(final String message, final Object... values) { return ArrayUtils.isEmpty(values) ? message : String.format(message, values); } /** * Validate that the specified primitive value falls between the two * inclusive values specified; otherwise, throws an exception. * *
Validate.inclusiveBetween(0.1, 2.1, 1.1);* * @param start the inclusive start value * @param end the inclusive end value * @param value the value to validate * @throws IllegalArgumentException if the value falls outside the boundaries (inclusive) * @since 3.3 */ @SuppressWarnings("boxing") public static void inclusiveBetween(final double start, final double end, final double value) { // TODO when breaking BC, consider returning value if (value < start || value > end) { throw new IllegalArgumentException(String.format(DEFAULT_INCLUSIVE_BETWEEN_EX_MESSAGE, value, start, end)); } } /** * Validate that the specified primitive value falls between the two * inclusive values specified; otherwise, throws an exception with the * specified message. * *
Validate.inclusiveBetween(0.1, 2.1, 1.1, "Not in range");* * @param start the inclusive start value * @param end the inclusive end value * @param value the value to validate * @param message the exception message if invalid, not null * @throws IllegalArgumentException if the value falls outside the boundaries * @since 3.3 */ public static void inclusiveBetween(final double start, final double end, final double value, final String message) { // TODO when breaking BC, consider returning value if (value < start || value > end) { throw new IllegalArgumentException(message); } } /** * Validate that the specified primitive value falls between the two * inclusive values specified; otherwise, throws an exception. * *
Validate.inclusiveBetween(0, 2, 1);* * @param start the inclusive start value * @param end the inclusive end value * @param value the value to validate * @throws IllegalArgumentException if the value falls outside the boundaries (inclusive) * @since 3.3 */ @SuppressWarnings("boxing") public static void inclusiveBetween(final long start, final long end, final long value) { // TODO when breaking BC, consider returning value if (value < start || value > end) { throw new IllegalArgumentException(String.format(DEFAULT_INCLUSIVE_BETWEEN_EX_MESSAGE, value, start, end)); } } /** * Validate that the specified primitive value falls between the two * inclusive values specified; otherwise, throws an exception with the * specified message. * *
Validate.inclusiveBetween(0, 2, 1, "Not in range");* * @param start the inclusive start value * @param end the inclusive end value * @param value the value to validate * @param message the exception message if invalid, not null * @throws IllegalArgumentException if the value falls outside the boundaries * @since 3.3 */ public static void inclusiveBetween(final long start, final long end, final long value, final String message) { // TODO when breaking BC, consider returning value if (value < start || value > end) { throw new IllegalArgumentException(message); } } /** * Validate that the specified argument object fall between the two * inclusive values specified; otherwise, throws an exception. * *
Validate.inclusiveBetween(0, 2, 1);* * @param
Validate.inclusiveBetween(0, 2, 1, "Not in boundaries");* * @param
This method is useful when validating that there will be no casting errors.
* *Validate.isAssignableFrom(SuperClass.class, object.getClass());* *
The message format of the exception is "Cannot assign {type} to {superType}"
* * @param superType the class must be validated against, not null * @param type the class to check, not null * @throws IllegalArgumentException if type argument is not assignable to the specified superType * @see #isAssignableFrom(Class, Class, String, Object...) * @since 3.0 */ public static void isAssignableFrom(final Class> superType, final Class> type) { // TODO when breaking BC, consider returning type if (type == null || superType == null || !superType.isAssignableFrom(type)) { throw new IllegalArgumentException( String.format(DEFAULT_IS_ASSIGNABLE_EX_MESSAGE, ClassUtils.getName(type, "null type"), ClassUtils.getName(superType, "null type"))); } } /** * Validates that the argument can be converted to the specified class, if not throws an exception. * *This method is useful when validating if there will be no casting errors.
* *Validate.isAssignableFrom(SuperClass.class, object.getClass());* *
The message of the exception is "The validated object can not be converted to the" * followed by the name of the class and "class"
* * @param superType the class must be validated against, not null * @param type the class to check, not null * @param message the {@link String#format(String, Object...)} exception message if invalid, not null * @param values the optional values for the formatted exception message, null array not recommended * @throws IllegalArgumentException if argument can not be converted to the specified class * @see #isAssignableFrom(Class, Class) */ public static void isAssignableFrom(final Class> superType, final Class> type, final String message, final Object... values) { // TODO when breaking BC, consider returning type if (!superType.isAssignableFrom(type)) { throw new IllegalArgumentException(getMessage(message, values)); } } /** * Validates that the argument is an instance of the specified class, if not throws an exception. * *This method is useful when validating according to an arbitrary class
* *Validate.isInstanceOf(OkClass.class, object);* *
The message of the exception is "Expected type: {type}, actual: {obj_type}"
* * @param type the class the object must be validated against, not null * @param obj the object to check, null throws an exception * @throws IllegalArgumentException if argument is not of specified class * @see #isInstanceOf(Class, Object, String, Object...) * @since 3.0 */ public static void isInstanceOf(final Class> type, final Object obj) { // TODO when breaking BC, consider returning obj if (!type.isInstance(obj)) { throw new IllegalArgumentException(String.format(DEFAULT_IS_INSTANCE_OF_EX_MESSAGE, type.getName(), ClassUtils.getName(obj, "null"))); } } /** * Validate that the argument is an instance of the specified class; otherwise * throwing an exception with the specified message. This method is useful when * validating according to an arbitrary class * *Validate.isInstanceOf(OkClass.class, object, "Wrong class, object is of class %s",
* object.getClass().getName());
*
* @param type the class the object must be validated against, not null
* @param obj the object to check, null throws an exception
* @param message the {@link String#format(String, Object...)} exception message if invalid, not null
* @param values the optional values for the formatted exception message, null array not recommended
* @throws IllegalArgumentException if argument is not of specified class
* @see #isInstanceOf(Class, Object)
* @since 3.0
*/
public static void isInstanceOf(final Class> type, final Object obj, final String message, final Object... values) {
// TODO when breaking BC, consider returning obj
if (!type.isInstance(obj)) {
throw new IllegalArgumentException(getMessage(message, values));
}
}
/**
* Validate that the argument condition is {@code true}; otherwise
* throwing an exception. This method is useful when validating according
* to an arbitrary boolean expression, such as validating a
* primitive number or using your own custom validation expression.
*
*
* Validate.isTrue(i > 0);
* Validate.isTrue(myObject.isOk());
*
* The message of the exception is "The validated expression is * false".
* * @param expression the boolean expression to check * @throws IllegalArgumentException if expression is {@code false} * @see #isTrue(boolean, String, long) * @see #isTrue(boolean, String, double) * @see #isTrue(boolean, String, Object...) */ public static void isTrue(final boolean expression) { if (!expression) { throw new IllegalArgumentException(DEFAULT_IS_TRUE_EX_MESSAGE); } } /** * Validate that the argument condition is {@code true}; otherwise * throwing an exception with the specified message. This method is useful when * validating according to an arbitrary boolean expression, such as validating a * primitive number or using your own custom validation expression. * *Validate.isTrue(d > 0.0, "The value must be greater than zero: %s", d);* *
For performance reasons, the double value is passed as a separate parameter and * appended to the exception message only in the case of an error.
* * @param expression the boolean expression to check * @param message the {@link String#format(String, Object...)} exception message if invalid, not null * @param value the value to append to the message when invalid * @throws IllegalArgumentException if expression is {@code false} * @see #isTrue(boolean) * @see #isTrue(boolean, String, long) * @see #isTrue(boolean, String, Object...) */ public static void isTrue(final boolean expression, final String message, final double value) { if (!expression) { throw new IllegalArgumentException(String.format(message, Double.valueOf(value))); } } /** * Validate that the argument condition is {@code true}; otherwise * throwing an exception with the specified message. This method is useful when * validating according to an arbitrary boolean expression, such as validating a * primitive number or using your own custom validation expression. * *Validate.isTrue(i > 0.0, "The value must be greater than zero: %d", i);* *
For performance reasons, the long value is passed as a separate parameter and * appended to the exception message only in the case of an error.
* * @param expression the boolean expression to check * @param message the {@link String#format(String, Object...)} exception message if invalid, not null * @param value the value to append to the message when invalid * @throws IllegalArgumentException if expression is {@code false} * @see #isTrue(boolean) * @see #isTrue(boolean, String, double) * @see #isTrue(boolean, String, Object...) */ public static void isTrue(final boolean expression, final String message, final long value) { if (!expression) { throw new IllegalArgumentException(String.format(message, Long.valueOf(value))); } } /** * Validate that the argument condition is {@code true}; otherwise * throwing an exception with the specified message. This method is useful when * validating according to an arbitrary boolean expression, such as validating a * primitive number or using your own custom validation expression. * *{@code
* Validate.isTrue(i >= min && i <= max, "The value must be between %d and %d", min, max);}
*
* @param expression the boolean expression to check
* @param message the {@link String#format(String, Object...)} exception message if invalid, not null
* @param values the optional values for the formatted exception message, null array not recommended
* @throws IllegalArgumentException if expression is {@code false}
* @see #isTrue(boolean)
* @see #isTrue(boolean, String, long)
* @see #isTrue(boolean, String, double)
*/
public static void isTrue(final boolean expression, final String message, final Object... values) {
if (!expression) {
throw new IllegalArgumentException(getMessage(message, values));
}
}
/**
* Validate that the specified argument character sequence matches the specified regular
* expression pattern; otherwise throwing an exception.
*
* Validate.matchesPattern("hi", "[a-z]*");
*
* The syntax of the pattern is the one used in the {@link Pattern} class.
* * @param input the character sequence to validate, not null * @param pattern the regular expression pattern, not null * @throws IllegalArgumentException if the character sequence does not match the pattern * @see #matchesPattern(CharSequence, String, String, Object...) * @since 3.0 */ public static void matchesPattern(final CharSequence input, final String pattern) { // TODO when breaking BC, consider returning input if (!Pattern.matches(pattern, input)) { throw new IllegalArgumentException(String.format(DEFAULT_MATCHES_PATTERN_EX, input, pattern)); } } /** * Validate that the specified argument character sequence matches the specified regular * expression pattern; otherwise throwing an exception with the specified message. * *Validate.matchesPattern("hi", "[a-z]*", "%s does not match %s", "hi" "[a-z]*");
*
* The syntax of the pattern is the one used in the {@link Pattern} class.
* * @param input the character sequence to validate, not null * @param pattern the regular expression pattern, not null * @param message the {@link String#format(String, Object...)} exception message if invalid, not null * @param values the optional values for the formatted exception message, null array not recommended * @throws IllegalArgumentException if the character sequence does not match the pattern * @see #matchesPattern(CharSequence, String) * @since 3.0 */ public static void matchesPattern(final CharSequence input, final String pattern, final String message, final Object... values) { // TODO when breaking BC, consider returning input if (!Pattern.matches(pattern, input)) { throw new IllegalArgumentException(getMessage(message, values)); } } /** * Validate that the specified argument iterable is neither * {@code null} nor contains any elements that are {@code null}; * otherwise throwing an exception. * *Validate.noNullElements(myCollection);* *
If the iterable is {@code null}, then the message in the exception * is "The validated object is null". * *
If the array has a {@code null} element, then the message in the * exception is "The validated iterable contains null element at index: * " followed by the index.
* * @paramValidate.noNullElements(myCollection, "The collection contains null at position %d");* *
If the iterable is {@code null}, then the message in the exception * is "The validated object is null". * *
If the iterable has a {@code null} element, then the iteration * index of the invalid element is appended to the {@code values} * argument.
* * @paramValidate.noNullElements(myArray);* *
If the array is {@code null}, then the message in the exception * is "The validated object is null".
* *If the array has a {@code null} element, then the message in the * exception is "The validated array contains null element at index: * " followed by the index.
* * @paramValidate.noNullElements(myArray, "The array contain null at position %d");* *
If the array is {@code null}, then the message in the exception * is "The validated object is null". * *
If the array has a {@code null} element, then the iteration * index of the invalid element is appended to the {@code values} * argument.
* * @paramValidate that the specified argument character sequence is * neither {@code null}, a length of zero (no characters), empty * nor whitespace; otherwise throwing an exception. * *
Validate.notBlank(myString);* *
The message in the exception is "The validated character
* sequence is blank".
*
* @param Validate that the specified argument collection is neither {@code null}
* nor a size of zero (no elements); otherwise throwing an exception.
*
* The message in the exception is "The validated collection is
* empty".
*
* @param Validate that the specified argument map is neither {@code null}
* nor a size of zero (no elements); otherwise throwing an exception.
*
* The message in the exception is "The validated map is
* empty".
*
* @param Validate that the specified argument character sequence is
* neither {@code null} nor a length of zero (no characters);
* otherwise throwing an exception with the specified message.
*
* The message in the exception is "The validated
* character sequence is empty".
*
* @param Validate that the specified argument collection is neither {@code null}
* nor a size of zero (no elements); otherwise throwing an exception
* with the specified message.
*
* Validate that the specified argument array is neither {@code null}
* nor a length of zero (no elements); otherwise throwing an exception.
*
* The message in the exception is "The validated array is
* empty".
*
* @param Validate that the specified argument array is neither {@code null}
* nor a length of zero (no elements); otherwise throwing an exception
* with the specified message.
*
* The message of the exception is "The validated value is not a
* number". The message of the exception is "The validated object is
* null".
*
* @param If the index is invalid, then the message of the exception
* is "The validated collection index is invalid: "
* followed by the index. If the character sequence is {@code null}, then the message
* of the exception is "The validated object is
* null". If the index is invalid, then the message of the exception
* is "The validated character sequence index is invalid: "
* followed by the index. If the collection is {@code null}, then the message of the
* exception is "The validated object is null". If the character sequence is {@code null}, then the message
* of the exception is "The validated object is null". If the array is {@code null}, then the message of the exception
* is "The validated object is null". If the index is invalid, then the message of the exception is
* "The validated array index is invalid: " followed by the
* index. If the array is {@code null}, then the message of the exception
* is "The validated object is null". The message of the exception is "The validated state is
* false".Validate.notBlank(myString, "The string must not be blank");
*
* @param Validate.notEmpty(myCollection);
*
* Validate.notEmpty(myMap);
*
* Validate.notEmpty(myString);
*
* Validate.notEmpty(myCollection, "The collection must not be empty");
*
* @param Validate.notEmpty(myMap, "The map must not be empty");
*
* @param Validate.notEmpty(myString, "The string must not be empty");
*
* @param Validate.notEmpty(myArray);
*
* Validate.notEmpty(myArray, "The array must not be empty");
*
* @param Validate.notNaN(myDouble);
*
* Validate.notNaN(myDouble, "The value must be a number");
*
* @param value the value to validate
* @param message the {@link String#format(String, Object...)} exception message if invalid, not null
* @param values the optional values for the formatted exception message
* @throws IllegalArgumentException if the value is not a number
* @see #notNaN(double)
* @since 3.5
*/
public static void notNaN(final double value, final String message, final Object... values) {
if (Double.isNaN(value)) {
throw new IllegalArgumentException(getMessage(message, values));
}
}
/**
* Validate that the specified argument is not {@code null};
* otherwise throwing an exception.
*
* Validate.notNull(myObject, "The object must not be null");
*
* Validate.notNull(myObject, "The object must not be null");
*
* @param Validate.validIndex(myCollection, 2);
*
* Validate.validIndex(myStr, 2);
*
* Validate.validIndex(myCollection, 2, "The collection index is invalid: ");
*
* Validate.validIndex(myStr, 2, "The string index is invalid: ");
*
* Validate.validIndex(myArray, 2);
*
* Validate.validIndex(myArray, 2, "The array index is invalid: ");
*
*
* Validate.validState(field > 0);
* Validate.validState(this.isOk());
*
* Validate.validState(this.isOk(), "The state is not OK: %s", myObject);
*
* @param expression the boolean expression to check
* @param message the {@link String#format(String, Object...)} exception message if invalid, not null
* @param values the optional values for the formatted exception message, null array not recommended
* @throws IllegalStateException if expression is {@code false}
* @see #validState(boolean)
* @since 3.0
*/
public static void validState(final boolean expression, final String message, final Object... values) {
if (!expression) {
throw new IllegalStateException(getMessage(message, values));
}
}
/**
* Constructs a new instance. This class should not normally be instantiated.
*/
public Validate() {
}
}