1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 *
9 * https://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17 package org.apache.commons.lang3;
18
19 import java.util.Collection;
20 import java.util.Map;
21 import java.util.Objects;
22 import java.util.concurrent.atomic.AtomicInteger;
23 import java.util.function.Supplier;
24 import java.util.regex.Pattern;
25
26 /**
27 * This class assists in validating arguments. The validation methods are
28 * based along the following principles:
29 * <ul>
30 * <li>An invalid {@code null} argument causes a {@link NullPointerException}.</li>
31 * <li>A non-{@code null} argument causes an {@link IllegalArgumentException}.</li>
32 * <li>An invalid index into an array/collection/map/string causes an {@link IndexOutOfBoundsException}.</li>
33 * </ul>
34 *
35 * <p>All exceptions messages are
36 * <a href="https://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html#syntax">format strings</a>
37 * as defined by the Java platform. For example:
38 *
39 * <pre>
40 * Validate.isTrue(i > 0, "The value must be greater than zero: %d", i);
41 * Validate.notNull(surname, "The surname must not be %s", null);
42 * </pre>
43 *
44 * <p>#ThreadSafe#</p>
45 * @see String#format(String, Object...)
46 * @since 2.0
47 */
48 public class Validate {
49
50 private static final String DEFAULT_NOT_NAN_EX_MESSAGE =
51 "The validated value is not a number";
52 private static final String DEFAULT_FINITE_EX_MESSAGE =
53 "The value is invalid: %f";
54 private static final String DEFAULT_EXCLUSIVE_BETWEEN_EX_MESSAGE =
55 "The value %s is not in the specified exclusive range of %s to %s";
56 private static final String DEFAULT_INCLUSIVE_BETWEEN_EX_MESSAGE =
57 "The value %s is not in the specified inclusive range of %s to %s";
58 private static final String DEFAULT_MATCHES_PATTERN_EX = "The string %s does not match the pattern %s";
59 private static final String DEFAULT_IS_NULL_EX_MESSAGE = "The validated object is null";
60 private static final String DEFAULT_IS_TRUE_EX_MESSAGE = "The validated expression is false";
61 private static final String DEFAULT_NO_NULL_ELEMENTS_ARRAY_EX_MESSAGE =
62 "The validated array contains null element at index: %d";
63 private static final String DEFAULT_NO_NULL_ELEMENTS_COLLECTION_EX_MESSAGE =
64 "The validated collection contains null element at index: %d";
65 private static final String DEFAULT_NOT_BLANK_EX_MESSAGE = "The validated character sequence is blank";
66 private static final String DEFAULT_NOT_EMPTY_ARRAY_EX_MESSAGE = "The validated array is empty";
67 private static final String DEFAULT_NOT_EMPTY_CHAR_SEQUENCE_EX_MESSAGE =
68 "The validated character sequence is empty";
69 private static final String DEFAULT_NOT_EMPTY_COLLECTION_EX_MESSAGE = "The validated collection is empty";
70 private static final String DEFAULT_NOT_EMPTY_MAP_EX_MESSAGE = "The validated map is empty";
71 private static final String DEFAULT_VALID_INDEX_ARRAY_EX_MESSAGE = "The validated array index is invalid: %d";
72 private static final String DEFAULT_VALID_INDEX_CHAR_SEQUENCE_EX_MESSAGE =
73 "The validated character sequence index is invalid: %d";
74 private static final String DEFAULT_VALID_INDEX_COLLECTION_EX_MESSAGE =
75 "The validated collection index is invalid: %d";
76 private static final String DEFAULT_VALID_STATE_EX_MESSAGE = "The validated state is false";
77 private static final String DEFAULT_IS_ASSIGNABLE_EX_MESSAGE = "Cannot assign a %s to a %s";
78 private static final String DEFAULT_IS_INSTANCE_OF_EX_MESSAGE = "Expected type: %s, actual: %s";
79
80 /**
81 * Validate that the specified primitive value falls between the two
82 * exclusive values specified; otherwise, throws an exception.
83 *
84 * <pre>Validate.exclusiveBetween(0.1, 2.1, 1.1);</pre>
85 *
86 * @param start the exclusive start value.
87 * @param end the exclusive end value.
88 * @param value the value to validate.
89 * @throws IllegalArgumentException if the value falls out of the boundaries.
90 * @since 3.3
91 */
92 @SuppressWarnings("boxing")
93 public static void exclusiveBetween(final double start, final double end, final double value) {
94 // TODO when breaking BC, consider returning value
95 if (value <= start || value >= end) {
96 throw new IllegalArgumentException(String.format(DEFAULT_EXCLUSIVE_BETWEEN_EX_MESSAGE, value, start, end));
97 }
98 }
99
100 /**
101 * Validate that the specified primitive value falls between the two
102 * exclusive values specified; otherwise, throws an exception with the
103 * specified message.
104 *
105 * <pre>Validate.exclusiveBetween(0.1, 2.1, 1.1, "Not in range");</pre>
106 *
107 * @param start the exclusive start value.
108 * @param end the exclusive end value.
109 * @param value the value to validate.
110 * @param message the exception message if invalid, not null.
111 * @throws IllegalArgumentException if the value falls outside the boundaries.
112 * @since 3.3
113 */
114 public static void exclusiveBetween(final double start, final double end, final double value, final String message) {
115 // TODO when breaking BC, consider returning value
116 if (value <= start || value >= end) {
117 throw new IllegalArgumentException(message);
118 }
119 }
120
121 /**
122 * Validate that the specified primitive value falls between the two
123 * exclusive values specified; otherwise, throws an exception.
124 *
125 * <pre>Validate.exclusiveBetween(0, 2, 1);</pre>
126 *
127 * @param start the exclusive start value.
128 * @param end the exclusive end value.
129 * @param value the value to validate.
130 * @throws IllegalArgumentException if the value falls out of the boundaries.
131 * @since 3.3
132 */
133 @SuppressWarnings("boxing")
134 public static void exclusiveBetween(final long start, final long end, final long value) {
135 // TODO when breaking BC, consider returning value
136 if (value <= start || value >= end) {
137 throw new IllegalArgumentException(String.format(DEFAULT_EXCLUSIVE_BETWEEN_EX_MESSAGE, value, start, end));
138 }
139 }
140
141 /**
142 * Validate that the specified primitive value falls between the two
143 * exclusive values specified; otherwise, throws an exception with the
144 * specified message.
145 *
146 * <pre>Validate.exclusiveBetween(0, 2, 1, "Not in range");</pre>
147 *
148 * @param start the exclusive start value.
149 * @param end the exclusive end value.
150 * @param value the value to validate.
151 * @param message the exception message if invalid, not null.
152 * @throws IllegalArgumentException if the value falls outside the boundaries.
153 * @since 3.3
154 */
155 public static void exclusiveBetween(final long start, final long end, final long value, final String message) {
156 // TODO when breaking BC, consider returning value
157 if (value <= start || value >= end) {
158 throw new IllegalArgumentException(message);
159 }
160 }
161
162 /**
163 * Validate that the specified argument object fall between the two
164 * exclusive values specified; otherwise, throws an exception.
165 *
166 * <pre>Validate.exclusiveBetween(0, 2, 1);</pre>
167 *
168 * @param <T> the type of the argument object.
169 * @param start the exclusive start value, not null.
170 * @param end the exclusive end value, not null.
171 * @param value the object to validate, not null.
172 * @throws IllegalArgumentException if the value falls outside the boundaries.
173 * @see #exclusiveBetween(Object, Object, Comparable, String, Object...)
174 * @since 3.0
175 */
176 public static <T> void exclusiveBetween(final T start, final T end, final Comparable<T> value) {
177 // TODO when breaking BC, consider returning value
178 if (value.compareTo(start) <= 0 || value.compareTo(end) >= 0) {
179 throw new IllegalArgumentException(String.format(DEFAULT_EXCLUSIVE_BETWEEN_EX_MESSAGE, value, start, end));
180 }
181 }
182
183 /**
184 * Validate that the specified argument object fall between the two
185 * exclusive values specified; otherwise, throws an exception with the
186 * specified message.
187 *
188 * <pre>Validate.exclusiveBetween(0, 2, 1, "Not in boundaries");</pre>
189 *
190 * @param <T> the type of the argument object.
191 * @param start the exclusive start value, not null.
192 * @param end the exclusive end value, not null.
193 * @param value the object to validate, not null.
194 * @param message the {@link String#format(String, Object...)} exception message if invalid, not null.
195 * @param values the optional values for the formatted exception message, null array not recommended.
196 * @throws IllegalArgumentException if the value falls outside the boundaries.
197 * @see #exclusiveBetween(Object, Object, Comparable)
198 * @since 3.0
199 */
200 public static <T> void exclusiveBetween(final T start, final T end, final Comparable<T> value, final String message, final Object... values) {
201 // TODO when breaking BC, consider returning value
202 if (value.compareTo(start) <= 0 || value.compareTo(end) >= 0) {
203 throw new IllegalArgumentException(getMessage(message, values));
204 }
205 }
206
207 /**
208 * Validates that the specified argument is not infinite or Not-a-Number (NaN);
209 * otherwise throwing an exception.
210 *
211 * <pre>Validate.finite(myDouble);</pre>
212 *
213 * <p>The message of the exception is "The value is invalid: %f".</p>
214 *
215 * @param value the value to validate.
216 * @throws IllegalArgumentException if the value is infinite or Not-a-Number (NaN).
217 * @see #finite(double, String, Object...)
218 * @since 3.5
219 */
220 public static void finite(final double value) {
221 finite(value, DEFAULT_FINITE_EX_MESSAGE, value);
222 }
223
224 /**
225 * Validates that the specified argument is not infinite or Not-a-Number (NaN);
226 * otherwise throwing an exception with the specified message.
227 *
228 * <pre>Validate.finite(myDouble, "The argument must contain a numeric value");</pre>
229 *
230 * @param value the value to validate.
231 * @param message the {@link String#format(String, Object...)} exception message if invalid, not null.
232 * @param values the optional values for the formatted exception message.
233 * @throws IllegalArgumentException if the value is infinite or Not-a-Number (NaN).
234 * @see #finite(double)
235 * @since 3.5
236 */
237 public static void finite(final double value, final String message, final Object... values) {
238 if (Double.isNaN(value) || Double.isInfinite(value)) {
239 throw new IllegalArgumentException(getMessage(message, values));
240 }
241 }
242
243 /**
244 * Gets the message using {@link String#format(String, Object...) String.format(message, values)} if the values are not empty, otherwise return the message
245 * unformatted. This method exists to allow validation methods declaring a String message and varargs parameters to be used without any message parameters
246 * when the message contains special characters, e.g. {@code Validate.isTrue(false, "%Failed%")}.
247 *
248 * @param message the {@link String#format(String, Object...)} exception message if invalid, not null.
249 * @param values the optional values for the formatted message.
250 * @return formatted message using {@link String#format(String, Object...) String.format(message, values)} if the values are not empty, otherwise return the
251 * unformatted message.
252 */
253 private static String getMessage(final String message, final Object... values) {
254 return ArrayUtils.isEmpty(values) ? message : String.format(message, values);
255 }
256
257 /**
258 * Validate that the specified primitive value falls between the two
259 * inclusive values specified; otherwise, throws an exception.
260 *
261 * <pre>Validate.inclusiveBetween(0.1, 2.1, 1.1);</pre>
262 *
263 * @param start the inclusive start value.
264 * @param end the inclusive end value.
265 * @param value the value to validate.
266 * @throws IllegalArgumentException if the value falls outside the boundaries (inclusive).
267 * @since 3.3
268 */
269 @SuppressWarnings("boxing")
270 public static void inclusiveBetween(final double start, final double end, final double value) {
271 // TODO when breaking BC, consider returning value
272 if (value < start || value > end) {
273 throw new IllegalArgumentException(String.format(DEFAULT_INCLUSIVE_BETWEEN_EX_MESSAGE, value, start, end));
274 }
275 }
276
277 /**
278 * Validate that the specified primitive value falls between the two
279 * inclusive values specified; otherwise, throws an exception with the
280 * specified message.
281 *
282 * <pre>Validate.inclusiveBetween(0.1, 2.1, 1.1, "Not in range");</pre>
283 *
284 * @param start the inclusive start value.
285 * @param end the inclusive end value.
286 * @param value the value to validate.
287 * @param message the exception message if invalid, not null.
288 * @throws IllegalArgumentException if the value falls outside the boundaries.
289 * @since 3.3
290 */
291 public static void inclusiveBetween(final double start, final double end, final double value, final String message) {
292 // TODO when breaking BC, consider returning value
293 if (value < start || value > end) {
294 throw new IllegalArgumentException(message);
295 }
296 }
297
298 /**
299 * Validate that the specified primitive value falls between the two
300 * inclusive values specified; otherwise, throws an exception.
301 *
302 * <pre>Validate.inclusiveBetween(0, 2, 1);</pre>
303 *
304 * @param start the inclusive start value.
305 * @param end the inclusive end value.
306 * @param value the value to validate.
307 * @throws IllegalArgumentException if the value falls outside the boundaries (inclusive).
308 * @since 3.3
309 */
310 @SuppressWarnings("boxing")
311 public static void inclusiveBetween(final long start, final long end, final long value) {
312 // TODO when breaking BC, consider returning value
313 if (value < start || value > end) {
314 throw new IllegalArgumentException(String.format(DEFAULT_INCLUSIVE_BETWEEN_EX_MESSAGE, value, start, end));
315 }
316 }
317
318 /**
319 * Validate that the specified primitive value falls between the two
320 * inclusive values specified; otherwise, throws an exception with the
321 * specified message.
322 *
323 * <pre>Validate.inclusiveBetween(0, 2, 1, "Not in range");</pre>
324 *
325 * @param start the inclusive start value.
326 * @param end the inclusive end value.
327 * @param value the value to validate.
328 * @param message the exception message if invalid, not null.
329 * @throws IllegalArgumentException if the value falls outside the boundaries.
330 * @since 3.3
331 */
332 public static void inclusiveBetween(final long start, final long end, final long value, final String message) {
333 // TODO when breaking BC, consider returning value
334 if (value < start || value > end) {
335 throw new IllegalArgumentException(message);
336 }
337 }
338
339 /**
340 * Validate that the specified argument object fall between the two
341 * inclusive values specified; otherwise, throws an exception.
342 *
343 * <pre>Validate.inclusiveBetween(0, 2, 1);</pre>
344 *
345 * @param <T> the type of the argument object.
346 * @param start the inclusive start value, not null.
347 * @param end the inclusive end value, not null.
348 * @param value the object to validate, not null.
349 * @throws IllegalArgumentException if the value falls outside the boundaries.
350 * @see #inclusiveBetween(Object, Object, Comparable, String, Object...)
351 * @since 3.0
352 */
353 public static <T> void inclusiveBetween(final T start, final T end, final Comparable<T> value) {
354 // TODO when breaking BC, consider returning value
355 if (value.compareTo(start) < 0 || value.compareTo(end) > 0) {
356 throw new IllegalArgumentException(String.format(DEFAULT_INCLUSIVE_BETWEEN_EX_MESSAGE, value, start, end));
357 }
358 }
359
360 /**
361 * Validate that the specified argument object fall between the two
362 * inclusive values specified; otherwise, throws an exception with the
363 * specified message.
364 *
365 * <pre>Validate.inclusiveBetween(0, 2, 1, "Not in boundaries");</pre>
366 *
367 * @param <T> the type of the argument object.
368 * @param start the inclusive start value, not null.
369 * @param end the inclusive end value, not null.
370 * @param value the object to validate, not null.
371 * @param message the {@link String#format(String, Object...)} exception message if invalid, not null.
372 * @param values the optional values for the formatted exception message, null array not recommended.
373 * @throws IllegalArgumentException if the value falls outside the boundaries.
374 * @see #inclusiveBetween(Object, Object, Comparable)
375 * @since 3.0
376 */
377 public static <T> void inclusiveBetween(final T start, final T end, final Comparable<T> value, final String message, final Object... values) {
378 // TODO when breaking BC, consider returning value
379 if (value.compareTo(start) < 0 || value.compareTo(end) > 0) {
380 throw new IllegalArgumentException(getMessage(message, values));
381 }
382 }
383
384 /**
385 * Validates that the argument can be converted to the specified class, if not, throws an exception.
386 *
387 * <p>This method is useful when validating that there will be no casting errors.</p>
388 *
389 * <pre>Validate.isAssignableFrom(SuperClass.class, object.getClass());</pre>
390 *
391 * <p>The message format of the exception is "Cannot assign {type} to {superType}"</p>
392 *
393 * @param superType the class must be validated against, not null.
394 * @param type the class to check, not null.
395 * @throws IllegalArgumentException if type argument is not assignable to the specified superType.
396 * @see #isAssignableFrom(Class, Class, String, Object...)
397 * @since 3.0
398 */
399 public static void isAssignableFrom(final Class<?> superType, final Class<?> type) {
400 // TODO when breaking BC, consider returning type
401 if (type == null || superType == null || !superType.isAssignableFrom(type)) {
402 throw new IllegalArgumentException(
403 String.format(DEFAULT_IS_ASSIGNABLE_EX_MESSAGE, ClassUtils.getName(type, "null type"), ClassUtils.getName(superType, "null type")));
404 }
405 }
406
407 /**
408 * Validates that the argument can be converted to the specified class, if not throws an exception.
409 *
410 * <p>This method is useful when validating if there will be no casting errors.</p>
411 *
412 * <pre>Validate.isAssignableFrom(SuperClass.class, object.getClass());</pre>
413 *
414 * <p>The message of the exception is "The validated object cannot be converted to the"
415 * followed by the name of the class and "class"</p>
416 *
417 * @param superType the class must be validated against, not null.
418 * @param type the class to check, not null.
419 * @param message the {@link String#format(String, Object...)} exception message if invalid, not null.
420 * @param values the optional values for the formatted exception message, null array not recommended.
421 * @throws IllegalArgumentException if argument cannot be converted to the specified class.
422 * @see #isAssignableFrom(Class, Class)
423 */
424 public static void isAssignableFrom(final Class<?> superType, final Class<?> type, final String message, final Object... values) {
425 // TODO when breaking BC, consider returning type
426 if (!superType.isAssignableFrom(type)) {
427 throw new IllegalArgumentException(getMessage(message, values));
428 }
429 }
430
431 /**
432 * Validates that the argument is an instance of the specified class, if not throws an exception.
433 *
434 * <p>This method is useful when validating according to an arbitrary class</p>
435 *
436 * <pre>Validate.isInstanceOf(OkClass.class, object);</pre>
437 *
438 * <p>The message of the exception is "Expected type: {type}, actual: {obj_type}"</p>
439 *
440 * @param type the class the object must be validated against, not null.
441 * @param obj the object to check, null throws an exception.
442 * @throws IllegalArgumentException if argument is not of specified class.
443 * @see #isInstanceOf(Class, Object, String, Object...)
444 * @since 3.0
445 */
446 public static void isInstanceOf(final Class<?> type, final Object obj) {
447 // TODO when breaking BC, consider returning obj
448 if (!type.isInstance(obj)) {
449 throw new IllegalArgumentException(String.format(DEFAULT_IS_INSTANCE_OF_EX_MESSAGE, type.getName(), ClassUtils.getName(obj, "null")));
450 }
451 }
452
453 /**
454 * Validate that the argument is an instance of the specified class; otherwise
455 * throwing an exception with the specified message. This method is useful when
456 * validating according to an arbitrary class
457 *
458 * <pre>Validate.isInstanceOf(OkClass.class, object, "Wrong class, object is of class %s",
459 * object.getClass().getName());</pre>
460 *
461 * @param type the class the object must be validated against, not null.
462 * @param obj the object to check, null throws an exception.
463 * @param message the {@link String#format(String, Object...)} exception message if invalid, not null.
464 * @param values the optional values for the formatted exception message, null array not recommended.
465 * @throws IllegalArgumentException if argument is not of specified class.
466 * @see #isInstanceOf(Class, Object)
467 * @since 3.0
468 */
469 public static void isInstanceOf(final Class<?> type, final Object obj, final String message, final Object... values) {
470 // TODO when breaking BC, consider returning obj
471 if (!type.isInstance(obj)) {
472 throw new IllegalArgumentException(getMessage(message, values));
473 }
474 }
475
476 /**
477 * Validate that the argument condition is {@code true}; otherwise
478 * throwing an exception. This method is useful when validating according
479 * to an arbitrary boolean expression, such as validating a
480 * primitive number or using your own custom validation expression.
481 *
482 * <pre>
483 * Validate.isTrue(i > 0);
484 * Validate.isTrue(myObject.isOk());</pre>
485 *
486 * <p>The message of the exception is "The validated expression is
487 * false".</p>
488 *
489 * @param expression the boolean expression to check.
490 * @throws IllegalArgumentException if expression is {@code false}.
491 * @see #isTrue(boolean, String, long)
492 * @see #isTrue(boolean, String, double)
493 * @see #isTrue(boolean, String, Object...)
494 * @see #isTrue(boolean, Supplier)
495 */
496 public static void isTrue(final boolean expression) {
497 if (!expression) {
498 throw new IllegalArgumentException(DEFAULT_IS_TRUE_EX_MESSAGE);
499 }
500 }
501
502 /**
503 * Validate that the argument condition is {@code true}; otherwise
504 * throwing an exception with the specified message. This method is useful when
505 * validating according to an arbitrary boolean expression, such as validating a
506 * primitive number or using your own custom validation expression.
507 *
508 * <pre>Validate.isTrue(d > 0.0, "The value must be greater than zero: %s", d);</pre>
509 *
510 * <p>For performance reasons, the double value is passed as a separate parameter and
511 * appended to the exception message only in the case of an error.</p>
512 *
513 * @param expression the boolean expression to check.
514 * @param message the {@link String#format(String, Object...)} exception message if invalid, not null.
515 * @param value the value to append to the message when invalid.
516 * @throws IllegalArgumentException if expression is {@code false}.
517 * @see #isTrue(boolean)
518 * @see #isTrue(boolean, String, long)
519 * @see #isTrue(boolean, String, Object...)
520 * @see #isTrue(boolean, Supplier)
521 */
522 public static void isTrue(final boolean expression, final String message, final double value) {
523 if (!expression) {
524 throw new IllegalArgumentException(String.format(message, Double.valueOf(value)));
525 }
526 }
527
528 /**
529 * Validate that the argument condition is {@code true}; otherwise
530 * throwing an exception with the specified message. This method is useful when
531 * validating according to an arbitrary boolean expression, such as validating a
532 * primitive number or using your own custom validation expression.
533 *
534 * <pre>Validate.isTrue(i > 0.0, "The value must be greater than zero: %d", i);</pre>
535 *
536 * <p>For performance reasons, the long value is passed as a separate parameter and
537 * appended to the exception message only in the case of an error.</p>
538 *
539 * @param expression the boolean expression to check.
540 * @param message the {@link String#format(String, Object...)} exception message if invalid, not null.
541 * @param value the value to append to the message when invalid.
542 * @throws IllegalArgumentException if expression is {@code false}.
543 * @see #isTrue(boolean)
544 * @see #isTrue(boolean, String, double)
545 * @see #isTrue(boolean, String, Object...)
546 * @see #isTrue(boolean, Supplier)
547 */
548 public static void isTrue(final boolean expression, final String message, final long value) {
549 if (!expression) {
550 throw new IllegalArgumentException(String.format(message, Long.valueOf(value)));
551 }
552 }
553
554 /**
555 * Validate that the argument condition is {@code true}; otherwise
556 * throwing an exception with the specified message. This method is useful when
557 * validating according to an arbitrary boolean expression, such as validating a
558 * primitive number or using your own custom validation expression.
559 *
560 * <pre>{@code
561 * Validate.isTrue(i >= min && i <= max, "The value must be between %d and %d", min, max);}</pre>
562 *
563 * @param expression the boolean expression to check.
564 * @param message the {@link String#format(String, Object...)} exception message if invalid, not null.
565 * @param values the optional values for the formatted exception message, null array not recommended.
566 * @throws IllegalArgumentException if expression is {@code false}.
567 * @see #isTrue(boolean)
568 * @see #isTrue(boolean, String, long)
569 * @see #isTrue(boolean, String, double)
570 * @see #isTrue(boolean, Supplier)
571 */
572 public static void isTrue(final boolean expression, final String message, final Object... values) {
573 if (!expression) {
574 throw new IllegalArgumentException(getMessage(message, values));
575 }
576 }
577
578 /**
579 * Validate that the argument condition is {@code true}; otherwise throwing an exception with the specified message. This method is useful when validating
580 * according to an arbitrary boolean expression, such as validating a primitive number or using your own custom validation expression.
581 *
582 * <pre>{@code
583 * Validate.isTrue(i >= min && i <= max, "The value must be between %d and %d", min, max);
584 * }</pre>
585 *
586 * @param expression the boolean expression to check.
587 * @param messageSupplier the exception message supplier.
588 * @throws IllegalArgumentException if expression is {@code false}.
589 * @see #isTrue(boolean)
590 * @see #isTrue(boolean, String, long)
591 * @see #isTrue(boolean, String, double)
592 * @since 3.18.0
593 */
594 public static void isTrue(final boolean expression, final Supplier<String> messageSupplier) {
595 if (!expression) {
596 throw new IllegalArgumentException(messageSupplier.get());
597 }
598 }
599
600 /**
601 * Validate that the specified argument character sequence matches the specified regular
602 * expression pattern; otherwise throwing an exception.
603 *
604 * <pre>Validate.matchesPattern("hi", "[a-z]*");</pre>
605 *
606 * <p>The syntax of the pattern is the one used in the {@link Pattern} class.</p>
607 *
608 * @param input the character sequence to validate, not null.
609 * @param pattern the regular expression pattern, not null.
610 * @throws IllegalArgumentException if the character sequence does not match the pattern.
611 * @see #matchesPattern(CharSequence, String, String, Object...)
612 * @since 3.0
613 */
614 public static void matchesPattern(final CharSequence input, final String pattern) {
615 // TODO when breaking BC, consider returning input
616 if (!Pattern.matches(pattern, input)) {
617 throw new IllegalArgumentException(String.format(DEFAULT_MATCHES_PATTERN_EX, input, pattern));
618 }
619 }
620
621 /**
622 * Validate that the specified argument character sequence matches the specified regular
623 * expression pattern; otherwise throwing an exception with the specified message.
624 *
625 * <pre>Validate.matchesPattern("hi", "[a-z]*", "%s does not match %s", "hi" "[a-z]*");</pre>
626 *
627 * <p>The syntax of the pattern is the one used in the {@link Pattern} class.</p>
628 *
629 * @param input the character sequence to validate, not null.
630 * @param pattern the regular expression pattern, not null.
631 * @param message the {@link String#format(String, Object...)} exception message if invalid, not null.
632 * @param values the optional values for the formatted exception message, null array not recommended.
633 * @throws IllegalArgumentException if the character sequence does not match the pattern.
634 * @see #matchesPattern(CharSequence, String)
635 * @since 3.0
636 */
637 public static void matchesPattern(final CharSequence input, final String pattern, final String message, final Object... values) {
638 // TODO when breaking BC, consider returning input
639 if (!Pattern.matches(pattern, input)) {
640 throw new IllegalArgumentException(getMessage(message, values));
641 }
642 }
643
644 /**
645 * Validate that the specified argument iterable is neither
646 * {@code null} nor contains any elements that are {@code null};
647 * otherwise throwing an exception.
648 *
649 * <pre>Validate.noNullElements(myCollection);</pre>
650 *
651 * <p>If the iterable is {@code null}, then the message in the exception
652 * is "The validated object is null".
653 *
654 * <p>If the array has a {@code null} element, then the message in the
655 * exception is "The validated iterable contains null element at index:
656 * " followed by the index.</p>
657 *
658 * @param <T> the iterable type.
659 * @param iterable the iterable to check, validated not null by this method.
660 * @return the validated iterable (never {@code null} method for chaining).
661 * @throws NullPointerException if the array is {@code null}.
662 * @throws IllegalArgumentException if an element is {@code null}.
663 * @see #noNullElements(Iterable, String, Object...)
664 */
665 public static <T extends Iterable<?>> T noNullElements(final T iterable) {
666 return noNullElements(iterable, DEFAULT_NO_NULL_ELEMENTS_COLLECTION_EX_MESSAGE);
667 }
668
669 /**
670 * Validate that the specified argument iterable is neither
671 * {@code null} nor contains any elements that are {@code null};
672 * otherwise throwing an exception with the specified message.
673 *
674 * <pre>Validate.noNullElements(myCollection, "The collection contains null at position %d");</pre>
675 *
676 * <p>If the iterable is {@code null}, then the message in the exception
677 * is "The validated object is null".
678 *
679 * <p>If the iterable has a {@code null} element, then the iteration
680 * index of the invalid element is appended to the {@code values}
681 * argument.</p>
682 *
683 * @param <T> the iterable type.
684 * @param iterable the iterable to check, validated not null by this method.
685 * @param message the {@link String#format(String, Object...)} exception message if invalid, not null.
686 * @param values the optional values for the formatted exception message, null array not recommended.
687 * @return the validated iterable (never {@code null} method for chaining).
688 * @throws NullPointerException if the array is {@code null}.
689 * @throws IllegalArgumentException if an element is {@code null}.
690 * @see #noNullElements(Iterable)
691 */
692 public static <T extends Iterable<?>> T noNullElements(final T iterable, final String message, final Object... values) {
693 Objects.requireNonNull(iterable, "iterable");
694 final AtomicInteger ai = new AtomicInteger();
695 iterable.forEach(e -> {
696 if (e == null) {
697 throw new IllegalArgumentException(getMessage(message, ArrayUtils.addAll(values, ai.getAndIncrement())));
698 }
699 });
700 return iterable;
701 }
702
703 /**
704 * Validate that the specified argument array is neither
705 * {@code null} nor contains any elements that are {@code null};
706 * otherwise throwing an exception.
707 *
708 * <pre>Validate.noNullElements(myArray);</pre>
709 *
710 * <p>If the array is {@code null}, then the message in the exception
711 * is "The validated object is null".</p>
712 *
713 * <p>If the array has a {@code null} element, then the message in the
714 * exception is "The validated array contains null element at index:
715 * " followed by the index.</p>
716 *
717 * @param <T> the array type.
718 * @param array the array to check, validated not null by this method.
719 * @return the validated array (never {@code null} method for chaining).
720 * @throws NullPointerException if the array is {@code null}.
721 * @throws IllegalArgumentException if an element is {@code null}.
722 * @see #noNullElements(Object[], String, Object...)
723 */
724 public static <T> T[] noNullElements(final T[] array) {
725 return noNullElements(array, DEFAULT_NO_NULL_ELEMENTS_ARRAY_EX_MESSAGE);
726 }
727
728 /**
729 * Validate that the specified argument array is neither
730 * {@code null} nor contains any elements that are {@code null};
731 * otherwise throwing an exception with the specified message.
732 *
733 * <pre>Validate.noNullElements(myArray, "The array contain null at position %d");</pre>
734 *
735 * <p>If the array is {@code null}, then the message in the exception
736 * is "The validated object is null".
737 *
738 * <p>If the array has a {@code null} element, then the iteration
739 * index of the invalid element is appended to the {@code values}
740 * argument.</p>
741 *
742 * @param <T> the array type.
743 * @param array the array to check, validated not null by this method.
744 * @param message the {@link String#format(String, Object...)} exception message if invalid, not null.
745 * @param values the optional values for the formatted exception message, null array not recommended.
746 * @return the validated array (never {@code null} method for chaining).
747 * @throws NullPointerException if the array is {@code null}.
748 * @throws IllegalArgumentException if an element is {@code null}.
749 * @see #noNullElements(Object[])
750 */
751 public static <T> T[] noNullElements(final T[] array, final String message, final Object... values) {
752 Objects.requireNonNull(array, "array");
753 for (int i = 0; i < array.length; i++) {
754 if (array[i] == null) {
755 final Object[] values2 = ArrayUtils.add(values, Integer.valueOf(i));
756 throw new IllegalArgumentException(getMessage(message, values2));
757 }
758 }
759 return array;
760 }
761
762 /**
763 * <p>Validates that the specified argument character sequence is
764 * neither {@code null}, a length of zero (no characters), empty
765 * nor whitespace; otherwise throwing an exception.
766 *
767 * <pre>Validate.notBlank(myString);</pre>
768 *
769 * <p>The message in the exception is "The validated character
770 * sequence is blank".
771 *
772 * @param <T> the character sequence type.
773 * @param chars the character sequence to check, validated not null by this method.
774 * @return the validated character sequence (never {@code null} method for chaining).
775 * @throws NullPointerException if the character sequence is {@code null}.
776 * @throws IllegalArgumentException if the character sequence is blank.
777 * @see #notBlank(CharSequence, String, Object...)
778 * @since 3.0
779 */
780 public static <T extends CharSequence> T notBlank(final T chars) {
781 return notBlank(chars, DEFAULT_NOT_BLANK_EX_MESSAGE);
782 }
783
784 /**
785 * Validates that the specified argument character sequence is not {@link StringUtils#isBlank(CharSequence) blank} (whitespaces, empty ({@code ""}) or
786 * {@code null}); otherwise throwing an exception with the specified message.
787 *
788 * <pre>
789 * Validate.notBlank(myString, "The string must not be blank");
790 * </pre>
791 *
792 * @param <T> the character sequence type.
793 * @param chars the character sequence to check, validated not null by this method.
794 * @param message the {@link String#format(String, Object...)} exception message if invalid, not null.
795 * @param values the optional values for the formatted exception message, null array not recommended.
796 * @return the validated character sequence (never {@code null} method for chaining).
797 * @throws NullPointerException if the character sequence is {@code null}.
798 * @throws IllegalArgumentException if the character sequence is blank.
799 * @see #notBlank(CharSequence)
800 * @see StringUtils#isBlank(CharSequence)
801 * @since 3.0
802 */
803 public static <T extends CharSequence> T notBlank(final T chars, final String message, final Object... values) {
804 Objects.requireNonNull(chars, toSupplier(message, values));
805 if (StringUtils.isBlank(chars)) {
806 throw new IllegalArgumentException(getMessage(message, values));
807 }
808 return chars;
809 }
810
811 /**
812 * <p>Validates that the specified argument collection is neither {@code null}
813 * nor a size of zero (no elements); otherwise throwing an exception.
814 *
815 * <pre>Validate.notEmpty(myCollection);</pre>
816 *
817 * <p>The message in the exception is "The validated collection is
818 * empty".
819 *
820 * @param <T> the collection type.
821 * @param collection the collection to check, validated not null by this method.
822 * @return the validated collection (never {@code null} method for chaining).
823 * @throws NullPointerException if the collection is {@code null}.
824 * @throws IllegalArgumentException if the collection is empty.
825 * @see #notEmpty(Collection, String, Object...)
826 */
827 public static <T extends Collection<?>> T notEmpty(final T collection) {
828 return notEmpty(collection, DEFAULT_NOT_EMPTY_COLLECTION_EX_MESSAGE);
829 }
830
831 /**
832 * <p>Validates that the specified argument map is neither {@code null}
833 * nor a size of zero (no elements); otherwise throwing an exception.
834 *
835 * <pre>Validate.notEmpty(myMap);</pre>
836 *
837 * <p>The message in the exception is "The validated map is
838 * empty".
839 *
840 * @param <T> the map type.
841 * @param map the map to check, validated not null by this method.
842 * @return the validated map (never {@code null} method for chaining).
843 * @throws NullPointerException if the map is {@code null}.
844 * @throws IllegalArgumentException if the map is empty.
845 * @see #notEmpty(Map, String, Object...)
846 */
847 public static <T extends Map<?, ?>> T notEmpty(final T map) {
848 return notEmpty(map, DEFAULT_NOT_EMPTY_MAP_EX_MESSAGE);
849 }
850
851 /**
852 * <p>Validates that the specified argument character sequence is
853 * neither {@code null} nor a length of zero (no characters);
854 * otherwise throwing an exception with the specified message.
855 *
856 * <pre>Validate.notEmpty(myString);</pre>
857 *
858 * <p>The message in the exception is "The validated
859 * character sequence is empty".
860 *
861 * @param <T> the character sequence type.
862 * @param chars the character sequence to check, validated not null by this method.
863 * @return the validated character sequence (never {@code null} method for chaining).
864 * @throws NullPointerException if the character sequence is {@code null}.
865 * @throws IllegalArgumentException if the character sequence is empty.
866 * @see #notEmpty(CharSequence, String, Object...)
867 */
868 public static <T extends CharSequence> T notEmpty(final T chars) {
869 return notEmpty(chars, DEFAULT_NOT_EMPTY_CHAR_SEQUENCE_EX_MESSAGE);
870 }
871
872 /**
873 * <p>Validates that the specified argument collection is neither {@code null}
874 * nor a size of zero (no elements); otherwise throwing an exception
875 * with the specified message.
876 *
877 * <pre>Validate.notEmpty(myCollection, "The collection must not be empty");</pre>
878 *
879 * @param <T> the collection type.
880 * @param collection the collection to check, validated not null by this method.
881 * @param message the {@link String#format(String, Object...)} exception message if invalid, not null.
882 * @param values the optional values for the formatted exception message, null array not recommended.
883 * @return the validated collection (never {@code null} method for chaining).
884 * @throws NullPointerException if the collection is {@code null}.
885 * @throws IllegalArgumentException if the collection is empty.
886 * @see #notEmpty(Object[])
887 */
888 public static <T extends Collection<?>> T notEmpty(final T collection, final String message, final Object... values) {
889 Objects.requireNonNull(collection, toSupplier(message, values));
890 if (collection.isEmpty()) {
891 throw new IllegalArgumentException(getMessage(message, values));
892 }
893 return collection;
894 }
895
896 /**
897 * Validate that the specified argument map is neither {@code null}
898 * nor a size of zero (no elements); otherwise throwing an exception
899 * with the specified message.
900 *
901 * <pre>Validate.notEmpty(myMap, "The map must not be empty");</pre>
902 *
903 * @param <T> the map type.
904 * @param map the map to check, validated not null by this method.
905 * @param message the {@link String#format(String, Object...)} exception message if invalid, not null.
906 * @param values the optional values for the formatted exception message, null array not recommended.
907 * @return the validated map (never {@code null} method for chaining).
908 * @throws NullPointerException if the map is {@code null}.
909 * @throws IllegalArgumentException if the map is empty.
910 * @see #notEmpty(Object[])
911 */
912 public static <T extends Map<?, ?>> T notEmpty(final T map, final String message, final Object... values) {
913 Objects.requireNonNull(map, toSupplier(message, values));
914 if (map.isEmpty()) {
915 throw new IllegalArgumentException(getMessage(message, values));
916 }
917 return map;
918 }
919
920 /**
921 * Validate that the specified argument character sequence is
922 * neither {@code null} nor a length of zero (no characters);
923 * otherwise throwing an exception with the specified message.
924 *
925 * <pre>Validate.notEmpty(myString, "The string must not be empty");</pre>
926 *
927 * @param <T> the character sequence type.
928 * @param chars the character sequence to check, validated not null by this method.
929 * @param message the {@link String#format(String, Object...)} exception message if invalid, not null.
930 * @param values the optional values for the formatted exception message, null array not recommended.
931 * @return the validated character sequence (never {@code null} method for chaining).
932 * @throws NullPointerException if the character sequence is {@code null}.
933 * @throws IllegalArgumentException if the character sequence is empty.
934 * @see #notEmpty(CharSequence)
935 */
936 public static <T extends CharSequence> T notEmpty(final T chars, final String message, final Object... values) {
937 Objects.requireNonNull(chars, toSupplier(message, values));
938 if (chars.length() == 0) {
939 throw new IllegalArgumentException(getMessage(message, values));
940 }
941 return chars;
942 }
943
944 /**
945 * <p>Validates that the specified argument array is neither {@code null}
946 * nor a length of zero (no elements); otherwise throwing an exception.
947 *
948 * <pre>Validate.notEmpty(myArray);</pre>
949 *
950 * <p>The message in the exception is "The validated array is
951 * empty".
952 *
953 * @param <T> the array type.
954 * @param array the array to check, validated not null by this method.
955 * @return the validated array (never {@code null} method for chaining).
956 * @throws NullPointerException if the array is {@code null}.
957 * @throws IllegalArgumentException if the array is empty.
958 * @see #notEmpty(Object[], String, Object...)
959 */
960 public static <T> T[] notEmpty(final T[] array) {
961 return notEmpty(array, DEFAULT_NOT_EMPTY_ARRAY_EX_MESSAGE);
962 }
963
964 /**
965 * <p>Validates that the specified argument array is neither {@code null}
966 * nor a length of zero (no elements); otherwise throwing an exception
967 * with the specified message.
968 *
969 * <pre>Validate.notEmpty(myArray, "The array must not be empty");</pre>
970 *
971 * @param <T> the array type.
972 * @param array the array to check, validated not null by this method.
973 * @param message the {@link String#format(String, Object...)} exception message if invalid, not null.
974 * @param values the optional values for the formatted exception message, null array not recommended.
975 * @return the validated array (never {@code null} method for chaining).
976 * @throws NullPointerException if the array is {@code null}
977 * @throws IllegalArgumentException if the array is empty
978 * @see #notEmpty(Object[])
979 */
980 public static <T> T[] notEmpty(final T[] array, final String message, final Object... values) {
981 Objects.requireNonNull(array, toSupplier(message, values));
982 if (array.length == 0) {
983 throw new IllegalArgumentException(getMessage(message, values));
984 }
985 return array;
986 }
987
988 /**
989 * Validates that the specified argument is not Not-a-Number (NaN); otherwise
990 * throwing an exception.
991 *
992 * <pre>Validate.notNaN(myDouble);</pre>
993 *
994 * <p>The message of the exception is "The validated value is not a
995 * number".</p>
996 *
997 * @param value the value to validate.
998 * @throws IllegalArgumentException if the value is not a number.
999 * @see #notNaN(double, String, Object...)
1000 * @since 3.5
1001 */
1002 public static void notNaN(final double value) {
1003 notNaN(value, DEFAULT_NOT_NAN_EX_MESSAGE);
1004 }
1005
1006 /**
1007 * Validates that the specified argument is not Not-a-Number (NaN); otherwise
1008 * throwing an exception with the specified message.
1009 *
1010 * <pre>Validate.notNaN(myDouble, "The value must be a number");</pre>
1011 *
1012 * @param value the value to validate.
1013 * @param message the {@link String#format(String, Object...)} exception message if invalid, not null.
1014 * @param values the optional values for the formatted exception message.
1015 * @throws IllegalArgumentException if the value is not a number.
1016 * @see #notNaN(double)
1017 * @since 3.5
1018 */
1019 public static void notNaN(final double value, final String message, final Object... values) {
1020 if (Double.isNaN(value)) {
1021 throw new IllegalArgumentException(getMessage(message, values));
1022 }
1023 }
1024
1025 /**
1026 * Validate that the specified argument is not {@code null};
1027 * otherwise throwing an exception.
1028 *
1029 * <pre>Validate.notNull(myObject, "The object must not be null");</pre>
1030 *
1031 * <p>The message of the exception is "The validated object is
1032 * null".
1033 *
1034 * @param <T> the object type.
1035 * @param object the object to check.
1036 * @return the validated object (never {@code null} for method chaining).
1037 * @throws NullPointerException if the object is {@code null}.
1038 * @see #notNull(Object, String, Object...)
1039 * @deprecated Use {@link Objects#requireNonNull(Object)}.
1040 */
1041 @Deprecated
1042 public static <T> T notNull(final T object) {
1043 return notNull(object, DEFAULT_IS_NULL_EX_MESSAGE);
1044 }
1045
1046 /**
1047 * Validate that the specified argument is not {@code null};
1048 * otherwise throwing an exception with the specified message.
1049 *
1050 * <pre>Validate.notNull(myObject, "The object must not be null");</pre>
1051 *
1052 * @param <T> the object type.
1053 * @param object the object to check.
1054 * @param message the {@link String#format(String, Object...)} exception message if invalid, not null.
1055 * @param values the optional values for the formatted exception message.
1056 * @return the validated object (never {@code null} for method chaining).
1057 * @throws NullPointerException if the object is {@code null}.
1058 * @see Objects#requireNonNull(Object)
1059 */
1060 public static <T> T notNull(final T object, final String message, final Object... values) {
1061 return Objects.requireNonNull(object, toSupplier(message, values));
1062 }
1063
1064 private static Supplier<String> toSupplier(final String message, final Object... values) {
1065 return () -> getMessage(message, values);
1066 }
1067
1068 /**
1069 * Validates that the index is within the bounds of the argument
1070 * collection; otherwise throwing an exception.
1071 *
1072 * <pre>Validate.validIndex(myCollection, 2);</pre>
1073 *
1074 * <p>If the index is invalid, then the message of the exception
1075 * is "The validated collection index is invalid: "
1076 * followed by the index.</p>
1077 *
1078 * @param <T> the collection type.
1079 * @param collection the collection to check, validated not null by this method.
1080 * @param index the index to check.
1081 * @return the validated collection (never {@code null} for method chaining).
1082 * @throws NullPointerException if the collection is {@code null}.
1083 * @throws IndexOutOfBoundsException if the index is invalid.
1084 * @see #validIndex(Collection, int, String, Object...)
1085 * @since 3.0
1086 */
1087 public static <T extends Collection<?>> T validIndex(final T collection, final int index) {
1088 return validIndex(collection, index, DEFAULT_VALID_INDEX_COLLECTION_EX_MESSAGE, Integer.valueOf(index));
1089 }
1090
1091 /**
1092 * Validates that the index is within the bounds of the argument
1093 * character sequence; otherwise throwing an exception.
1094 *
1095 * <pre>Validate.validIndex(myStr, 2);</pre>
1096 *
1097 * <p>If the character sequence is {@code null}, then the message
1098 * of the exception is "The validated object is
1099 * null".</p>
1100 *
1101 * <p>If the index is invalid, then the message of the exception
1102 * is "The validated character sequence index is invalid: "
1103 * followed by the index.</p>
1104 *
1105 * @param <T> the character sequence type.
1106 * @param chars the character sequence to check, validated not null by this method.
1107 * @param index the index to check.
1108 * @return the validated character sequence (never {@code null} for method chaining).
1109 * @throws NullPointerException if the character sequence is {@code null}.
1110 * @throws IndexOutOfBoundsException if the index is invalid.
1111 * @see #validIndex(CharSequence, int, String, Object...)
1112 * @since 3.0
1113 */
1114 public static <T extends CharSequence> T validIndex(final T chars, final int index) {
1115 return validIndex(chars, index, DEFAULT_VALID_INDEX_CHAR_SEQUENCE_EX_MESSAGE, Integer.valueOf(index));
1116 }
1117
1118 /**
1119 * Validates that the index is within the bounds of the argument
1120 * collection; otherwise throwing an exception with the specified message.
1121 *
1122 * <pre>Validate.validIndex(myCollection, 2, "The collection index is invalid: ");</pre>
1123 *
1124 * <p>If the collection is {@code null}, then the message of the
1125 * exception is "The validated object is null".</p>
1126 *
1127 * @param <T> the collection type.
1128 * @param collection the collection to check, validated not null by this method.
1129 * @param index the index to check.
1130 * @param message the {@link String#format(String, Object...)} exception message if invalid, not null.
1131 * @param values the optional values for the formatted exception message, null array not recommended.
1132 * @return the validated collection (never {@code null} for chaining).
1133 * @throws NullPointerException if the collection is {@code null}.
1134 * @throws IndexOutOfBoundsException if the index is invalid.
1135 * @see #validIndex(Collection, int)
1136 * @since 3.0
1137 */
1138 public static <T extends Collection<?>> T validIndex(final T collection, final int index, final String message, final Object... values) {
1139 Objects.requireNonNull(collection, "collection");
1140 if (index < 0 || index >= collection.size()) {
1141 throw new IndexOutOfBoundsException(getMessage(message, values));
1142 }
1143 return collection;
1144 }
1145
1146 /**
1147 * Validates that the index is within the bounds of the argument
1148 * character sequence; otherwise throwing an exception with the
1149 * specified message.
1150 *
1151 * <pre>Validate.validIndex(myStr, 2, "The string index is invalid: ");</pre>
1152 *
1153 * <p>If the character sequence is {@code null}, then the message
1154 * of the exception is "The validated object is null".</p>
1155 *
1156 * @param <T> the character sequence type.
1157 * @param chars the character sequence to check, validated not null by this method.
1158 * @param index the index to check.
1159 * @param message the {@link String#format(String, Object...)} exception message if invalid, not null.
1160 * @param values the optional values for the formatted exception message, null array not recommended.
1161 * @return the validated character sequence (never {@code null} for method chaining).
1162 * @throws NullPointerException if the character sequence is {@code null}.
1163 * @throws IndexOutOfBoundsException if the index is invalid.
1164 * @see #validIndex(CharSequence, int)
1165 * @since 3.0
1166 */
1167 public static <T extends CharSequence> T validIndex(final T chars, final int index, final String message, final Object... values) {
1168 Objects.requireNonNull(chars, "chars");
1169 if (index < 0 || index >= chars.length()) {
1170 throw new IndexOutOfBoundsException(getMessage(message, values));
1171 }
1172 return chars;
1173 }
1174
1175 /**
1176 * Validates that the index is within the bounds of the argument
1177 * array; otherwise throwing an exception.
1178 *
1179 * <pre>Validate.validIndex(myArray, 2);</pre>
1180 *
1181 * <p>If the array is {@code null}, then the message of the exception
1182 * is "The validated object is null".</p>
1183 *
1184 * <p>If the index is invalid, then the message of the exception is
1185 * "The validated array index is invalid: " followed by the
1186 * index.</p>
1187 *
1188 * @param <T> the array type.
1189 * @param array the array to check, validated not null by this method.
1190 * @param index the index to check.
1191 * @return the validated array (never {@code null} for method chaining).
1192 * @throws NullPointerException if the array is {@code null}.
1193 * @throws IndexOutOfBoundsException if the index is invalid.
1194 * @see #validIndex(Object[], int, String, Object...)
1195 * @since 3.0
1196 */
1197 public static <T> T[] validIndex(final T[] array, final int index) {
1198 return validIndex(array, index, DEFAULT_VALID_INDEX_ARRAY_EX_MESSAGE, Integer.valueOf(index));
1199 }
1200
1201 /**
1202 * Validates that the index is within the bounds of the argument
1203 * array; otherwise throwing an exception with the specified message.
1204 *
1205 * <pre>Validate.validIndex(myArray, 2, "The array index is invalid: ");</pre>
1206 *
1207 * <p>If the array is {@code null}, then the message of the exception
1208 * is "The validated object is null".</p>
1209 *
1210 * @param <T> the array type.
1211 * @param array the array to check, validated not null by this method.
1212 * @param index the index to check.
1213 * @param message the {@link String#format(String, Object...)} exception message if invalid, not null.
1214 * @param values the optional values for the formatted exception message, null array not recommended.
1215 * @return the validated array (never {@code null} for method chaining).
1216 * @throws NullPointerException if the array is {@code null}.
1217 * @throws IndexOutOfBoundsException if the index is invalid.
1218 * @see #validIndex(Object[], int)
1219 * @since 3.0
1220 */
1221 public static <T> T[] validIndex(final T[] array, final int index, final String message, final Object... values) {
1222 Objects.requireNonNull(array, "array");
1223 if (index < 0 || index >= array.length) {
1224 throw new IndexOutOfBoundsException(getMessage(message, values));
1225 }
1226 return array;
1227 }
1228
1229 /**
1230 * Validate that the stateful condition is {@code true}; otherwise
1231 * throwing an exception. This method is useful when validating according
1232 * to an arbitrary boolean expression, such as validating a
1233 * primitive number or using your own custom validation expression.
1234 *
1235 * <pre>
1236 * Validate.validState(field > 0);
1237 * Validate.validState(this.isOk());</pre>
1238 *
1239 * <p>The message of the exception is "The validated state is
1240 * false".</p>
1241 *
1242 * @param expression the boolean expression to check.
1243 * @throws IllegalStateException if expression is {@code false}.
1244 * @see #validState(boolean, String, Object...)
1245 * @since 3.0
1246 */
1247 public static void validState(final boolean expression) {
1248 if (!expression) {
1249 throw new IllegalStateException(DEFAULT_VALID_STATE_EX_MESSAGE);
1250 }
1251 }
1252
1253 /**
1254 * Validate that the stateful condition is {@code true}; otherwise
1255 * throwing an exception with the specified message. This method is useful when
1256 * validating according to an arbitrary boolean expression, such as validating a
1257 * primitive number or using your own custom validation expression.
1258 *
1259 * <pre>Validate.validState(this.isOk(), "The state is not OK: %s", myObject);</pre>
1260 *
1261 * @param expression the boolean expression to check.
1262 * @param message the {@link String#format(String, Object...)} exception message if invalid, not null.
1263 * @param values the optional values for the formatted exception message, null array not recommended.
1264 * @throws IllegalStateException if expression is {@code false}.
1265 * @see #validState(boolean)
1266 * @since 3.0
1267 */
1268 public static void validState(final boolean expression, final String message, final Object... values) {
1269 if (!expression) {
1270 throw new IllegalStateException(getMessage(message, values));
1271 }
1272 }
1273
1274 /**
1275 * Constructs a new instance. This class should not normally be instantiated.
1276 */
1277 public Validate() {
1278 }
1279 }