From a606a0328ba4b3061c5bc810a31418fa4251ea16 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Tue, 7 Jan 2020 23:03:39 -0500 Subject: [PATCH 0001/3230] [LANG-1513] ObjectUtils: Get first non-null supplier value. --- src/changes/changes.xml | 1 + .../org/apache/commons/lang3/ObjectUtils.java | 39 +++++++++++++++++++ .../apache/commons/lang3/ObjectUtilsTest.java | 23 +++++++++++ 3 files changed, 63 insertions(+) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 2a307cb550e..11f89c4fbee 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -94,6 +94,7 @@ The type attribute can be add,update,fix,remove. Add ObjectToStringComparator. #483. Add org.apache.commons.lang3.arch.Processor.Arch.getLabel(). Add IS_JAVA_14 and IS_JAVA_15 to org.apache.commons.lang3.SystemUtils. + ObjectUtils: Get first non-null supplier value. diff --git a/src/main/java/org/apache/commons/lang3/ObjectUtils.java b/src/main/java/org/apache/commons/lang3/ObjectUtils.java index 3b83ce16cdf..b647c1a4a60 100644 --- a/src/main/java/org/apache/commons/lang3/ObjectUtils.java +++ b/src/main/java/org/apache/commons/lang3/ObjectUtils.java @@ -209,6 +209,45 @@ public static T firstNonNull(final T... values) { return null; } + /** + *

Executes the given suppliers in order and returns the first return + * value where a value other than {@code null} is returned. + * Once a non-{@code null} value is obtained, all following suppliers are + * not executed anymore. + * If all the return values are {@code null} or no suppliers are provided + * then {@code null} is returned.

+ * + *
+     * ObjectUtils.firstNonNullLazy(null, () -> null) = null
+     * ObjectUtils.firstNonNullLazy(() -> null, () -> "") = ""
+     * ObjectUtils.firstNonNullLazy(() -> "", () -> throw new IllegalStateException()) = ""
+     * ObjectUtils.firstNonNullLazy(() -> null, () -> "zz) = "zz"
+     * ObjectUtils.firstNonNullLazy() = null
+     * 
+ * + * @param the type of the return values + * @param suppliers the suppliers returning the values to test. + * {@code null} values are ignored. + * Suppliers may return {@code null} or a value of type @{code T} + * @return the first return value from {@code suppliers} which is not {@code null}, + * or {@code null} if there are no non-null values + * @since 3.10 + */ + @SafeVarargs + public static T getFirstNonNull(final Supplier... suppliers) { + if (suppliers != null) { + for (final Supplier supplier : suppliers) { + if (supplier != null) { + T value = supplier.get(); + if (value != null) { + return value; + } + } + } + } + return null; + } + /** *

* Returns the given {@code object} is it is non-null, otherwise returns the Supplier's {@link Supplier#get()} diff --git a/src/test/java/org/apache/commons/lang3/ObjectUtilsTest.java b/src/test/java/org/apache/commons/lang3/ObjectUtilsTest.java index 19d61103c88..7fcdc4b71d8 100644 --- a/src/test/java/org/apache/commons/lang3/ObjectUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/ObjectUtilsTest.java @@ -25,6 +25,7 @@ import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.io.IOException; import java.lang.reflect.Constructor; @@ -149,6 +150,28 @@ public void testFirstNonNull() { assertNull(ObjectUtils.firstNonNull((Object[]) null)); } + @Test + public void testGetFirstNonNull() { + // first non null + assertEquals("", ObjectUtils.getFirstNonNull(() -> null, () -> "")); + // first encountered value is used + assertEquals("1", ObjectUtils.getFirstNonNull(() -> null, () -> "1", () -> "2", () -> null)); + assertEquals("123", ObjectUtils.getFirstNonNull(() -> "123", () -> null, () -> "456")); + // don't evaluate suppliers after first value is found + assertEquals("123", ObjectUtils.getFirstNonNull(() -> null, () -> "123", () -> fail("Supplier after first non-null value should not be evaluated"))); + // supplier returning null and null supplier both result in null + assertNull(ObjectUtils.getFirstNonNull(null, () -> null)); + // Explicitly pass in an empty array of Object type to ensure compiler doesn't complain of unchecked generic array creation + assertNull(ObjectUtils.getFirstNonNull()); + // supplier is null + assertNull(ObjectUtils.getFirstNonNull((Supplier) null)); + // varargs array itself is null + assertNull(ObjectUtils.getFirstNonNull((Supplier[]) null)); + // test different types + assertEquals(1, ObjectUtils.getFirstNonNull(() -> null, () -> 1)); + assertEquals(Boolean.TRUE, ObjectUtils.getFirstNonNull(() -> null, () -> Boolean.TRUE)); + } + /** * Tests {@link ObjectUtils#anyNotNull(Object...)}. */ From 4b11c764e5bfa1fd2e3b85247c0384c66b515489 Mon Sep 17 00:00:00 2001 From: contextshuffling Date: Sun, 19 Jan 2020 23:00:06 +0800 Subject: [PATCH 0002/3230] [LANG-1514] make test more stable by using HashSet to compare --- .../java/org/apache/commons/lang3/reflect/FieldUtilsTest.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/test/java/org/apache/commons/lang3/reflect/FieldUtilsTest.java b/src/test/java/org/apache/commons/lang3/reflect/FieldUtilsTest.java index 4e428a926b6..291e70a20be 100644 --- a/src/test/java/org/apache/commons/lang3/reflect/FieldUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/reflect/FieldUtilsTest.java @@ -36,6 +36,7 @@ import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; +import java.util.HashSet; import java.util.List; import static org.junit.jupiter.api.Assertions.assertArrayEquals; @@ -188,7 +189,7 @@ public void testGetAllFieldsList() { final List fieldsInteger = Arrays.asList(Integer.class.getDeclaredFields()); final List allFieldsInteger = new ArrayList<>(fieldsInteger); allFieldsInteger.addAll(fieldsNumber); - assertEquals(allFieldsInteger, FieldUtils.getAllFieldsList(Integer.class)); + assertEquals(new HashSet(allFieldsInteger), new HashSet(FieldUtils.getAllFieldsList(Integer.class))); final List allFields = FieldUtils.getAllFieldsList(PublicChild.class); // Under Jacoco,0.8.1 and Java 10, the field count is 7. int expected = 5; From bb5244814ca59d1ce896e68fdbe0dc8928b32532 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Fri, 24 Jan 2020 09:05:31 -0500 Subject: [PATCH 0003/3230] Reduce magic number usage. --- .../apache/commons/lang3/exception/ExceptionUtils.java | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/exception/ExceptionUtils.java b/src/main/java/org/apache/commons/lang3/exception/ExceptionUtils.java index 152c809c252..3a1d6994267 100644 --- a/src/main/java/org/apache/commons/lang3/exception/ExceptionUtils.java +++ b/src/main/java/org/apache/commons/lang3/exception/ExceptionUtils.java @@ -39,6 +39,8 @@ */ public class ExceptionUtils { + private static final int NOT_FOUND = -1; + /** *

The names of methods commonly used to access a wrapped exception.

*/ @@ -299,7 +301,7 @@ static List getStackFrameList(final Throwable t) { final String token = frames.nextToken(); // Determine if the line starts with at final int at = token.indexOf("at"); - if (at != -1 && token.substring(0, at).trim().isEmpty()) { + if (at != NOT_FOUND && token.substring(0, at).trim().isEmpty()) { traceStarted = true; list.add(token); } else if (traceStarted) { @@ -475,14 +477,14 @@ public static boolean hasCause(Throwable chain, */ private static int indexOf(final Throwable throwable, final Class type, int fromIndex, final boolean subclass) { if (throwable == null || type == null) { - return -1; + return NOT_FOUND; } if (fromIndex < 0) { fromIndex = 0; } final Throwable[] throwables = getThrowables(throwable); if (fromIndex >= throwables.length) { - return -1; + return NOT_FOUND; } if (subclass) { for (int i = fromIndex; i < throwables.length; i++) { @@ -497,7 +499,7 @@ private static int indexOf(final Throwable throwable, final Class type, int f } } } - return -1; + return NOT_FOUND; } /** From bfc88d23cb83448f6f5ac98cece5da92deeb221e Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Fri, 24 Jan 2020 09:16:01 -0500 Subject: [PATCH 0004/3230] [LANG-1516] Fix generics in API signatures of ExceptionUtils. --- .../apache/commons/lang3/exception/ExceptionUtils.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/exception/ExceptionUtils.java b/src/main/java/org/apache/commons/lang3/exception/ExceptionUtils.java index 3a1d6994267..6bfc79ef60c 100644 --- a/src/main/java/org/apache/commons/lang3/exception/ExceptionUtils.java +++ b/src/main/java/org/apache/commons/lang3/exception/ExceptionUtils.java @@ -475,7 +475,7 @@ public static boolean hasCause(Throwable chain, * using references * @return index of the {@code type} within throwables nested within the specified {@code throwable} */ - private static int indexOf(final Throwable throwable, final Class type, int fromIndex, final boolean subclass) { + private static int indexOf(final Throwable throwable, final Class type, int fromIndex, final boolean subclass) { if (throwable == null || type == null) { return NOT_FOUND; } @@ -516,7 +516,7 @@ private static int indexOf(final Throwable throwable, final Class type, int f * @param clazz the class to search for, subclasses do not match, null returns -1 * @return the index into the throwable chain, -1 if no match or null input */ - public static int indexOfThrowable(final Throwable throwable, final Class clazz) { + public static int indexOfThrowable(final Throwable throwable, final Class clazz) { return indexOf(throwable, clazz, 0, false); } @@ -539,7 +539,7 @@ public static int indexOfThrowable(final Throwable throwable, final Class cla * negative treated as zero, larger than chain size returns -1 * @return the index into the throwable chain, -1 if no match or null input */ - public static int indexOfThrowable(final Throwable throwable, final Class clazz, final int fromIndex) { + public static int indexOfThrowable(final Throwable throwable, final Class clazz, final int fromIndex) { return indexOf(throwable, clazz, fromIndex, false); } @@ -558,7 +558,7 @@ public static int indexOfThrowable(final Throwable throwable, final Class cla * @return the index into the throwable chain, -1 if no match or null input * @since 2.1 */ - public static int indexOfType(final Throwable throwable, final Class type) { + public static int indexOfType(final Throwable throwable, final Class type) { return indexOf(throwable, type, 0, true); } @@ -582,7 +582,7 @@ public static int indexOfType(final Throwable throwable, final Class type) { * @return the index into the throwable chain, -1 if no match or null input * @since 2.1 */ - public static int indexOfType(final Throwable throwable, final Class type, final int fromIndex) { + public static int indexOfType(final Throwable throwable, final Class type, final int fromIndex) { return indexOf(throwable, type, fromIndex, true); } From 2ea44b2adae8da8e3e7f55cc226479f9431feda9 Mon Sep 17 00:00:00 2001 From: Jochen Wiedmann Date: Sun, 26 Jan 2020 22:57:13 +0100 Subject: [PATCH 0005/3230] - Added the Streams class. - Added Functions.stream() as an accessor method. --- src/changes/changes.xml | 1 + .../org/apache/commons/lang3/Functions.java | 37 ++ .../org/apache/commons/lang3/Streams.java | 380 ++++++++++++++++++ .../org/apache/commons/lang3/StreamsTest.java | 176 ++++++++ 4 files changed, 594 insertions(+) create mode 100644 src/main/java/org/apache/commons/lang3/Streams.java create mode 100644 src/test/java/org/apache/commons/lang3/StreamsTest.java diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 11f89c4fbee..c5516d5f222 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -95,6 +95,7 @@ The type attribute can be add,update,fix,remove. Add org.apache.commons.lang3.arch.Processor.Arch.getLabel(). Add IS_JAVA_14 and IS_JAVA_15 to org.apache.commons.lang3.SystemUtils. ObjectUtils: Get first non-null supplier value. + Added the Streams class, and Functions.stream() as an accessor thereof. diff --git a/src/main/java/org/apache/commons/lang3/Functions.java b/src/main/java/org/apache/commons/lang3/Functions.java index 2d0ca06b7a7..ef9c45d909b 100644 --- a/src/main/java/org/apache/commons/lang3/Functions.java +++ b/src/main/java/org/apache/commons/lang3/Functions.java @@ -19,6 +19,7 @@ import java.io.IOException; import java.io.UncheckedIOException; import java.lang.reflect.UndeclaredThrowableException; +import java.util.Collection; import java.util.Objects; import java.util.concurrent.Callable; import java.util.function.BiConsumer; @@ -28,6 +29,9 @@ import java.util.function.Function; import java.util.function.Predicate; import java.util.function.Supplier; +import java.util.stream.Stream; + +import org.apache.commons.lang3.Streams.FailableStream; /** This class provides utility functions, and classes for working with the @@ -400,6 +404,39 @@ public static O get(FailableSupplier pSupplier) { } } + /** + * Converts the given stream into a {@link FailableStream}. The + * {@link FailableStream} consists of the same elements, than the + * input stream. However, failable lambdas, like + * {@link FailablePredicate}, {@link FailableFunction}, and + * {@link FailableConsumer} may be applied, rather than + * {@link Predicate}, {@link Function}, {@link Consumer}, etc. + * @param pStream The stream, which is being converted into a + * {@link FailableStream}. + * @param The streams element type. + * @return The created {@link FailableStream}. + */ + public static FailableStream stream(Stream pStream) { + return new FailableStream(pStream); + } + + /** + * Converts the given collection into a {@link FailableStream}. + * The {@link FailableStream} consists of the collections + * elements. Shortcut for + *
+     *   Functions.stream(pCollection.stream());
+     * 
+ * @param pCollection The collection, which is being converted into a + * {@link FailableStream}. + * @param The collections element type. (In turn, the result + * streams element type.) + * @return The created {@link FailableStream}. + */ + public static FailableStream stream(Collection pCollection) { + return new FailableStream(pCollection.stream()); + } + /** * A simple try-with-resources implementation, that can be used, if your diff --git a/src/main/java/org/apache/commons/lang3/Streams.java b/src/main/java/org/apache/commons/lang3/Streams.java new file mode 100644 index 00000000000..a0f32afecc7 --- /dev/null +++ b/src/main/java/org/apache/commons/lang3/Streams.java @@ -0,0 +1,380 @@ +/* + * 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.function.BiConsumer; +import java.util.function.BinaryOperator; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.function.Supplier; +import java.util.stream.Collector; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.apache.commons.lang3.Functions.FailableConsumer; +import org.apache.commons.lang3.Functions.FailableFunction; +import org.apache.commons.lang3.Functions.FailablePredicate; + +/** + * This class provides utility functions, and classes for working with the + * java.util.stream package, or more generally, with Java 8 lambdas. More + * specifically, it attempts to address the fact that lambdas are supposed + * not to throw Exceptions, at least not checked Exceptions, aka instances + * of {@link Exception}. This enforces the use of constructs like + *
+ *     Consumer<java.lang.reflect.Method> consumer = (m) -> {
+ *         try {
+ *             m.invoke(o, args);
+ *         } catch (Throwable t) {
+ *             throw Functions.rethrow(t);
+ *         }
+ *    };
+ *    stream.forEach(consumer);
+ * 
+ * Using a {@link FailableStream}, this can be rewritten as follows: + *
+ *     ObjectStreams.failable(stream).forEach((m) -> m.invoke(o, args));
+ * 
+ * Obviously, the second version is much more concise and the spirit of + * Lambda expressions is met better than in the first version. + * @see Stream + * @see Functions + */ +public class Streams { + /** A reduced, and simplified version of a {@link Stream} with + * failable method signatures. + * @param The streams element type. + */ + public static class FailableStream { + private Stream stream; + private boolean terminated; + + public FailableStream(Stream pStream) { + stream = pStream; + } + + protected void assertNotTerminated() { + if (terminated) { + throw new IllegalStateException("This stream is already terminated."); + } + } + + protected void makeTerminated() { + assertNotTerminated(); + terminated = true; + } + + /** + * Returns a FailableStream consisting of the elements of this stream that match + * the given FailablePredicate. + * + *

This is an intermediate operation. + * + * @param pPredicate a non-interfering, stateless predicate to apply to each + * element to determine if it should be included. + * @return the new stream + */ + public FailableStream filter(FailablePredicate pPredicate){ + assertNotTerminated(); + stream = stream.filter(Functions.asPredicate(pPredicate)); + return this; + } + + /** + * Performs an action for each element of this stream. + * + *

This is a terminal operation. + * + *

The behavior of this operation is explicitly nondeterministic. + * For parallel stream pipelines, this operation does not + * guarantee to respect the encounter order of the stream, as doing so + * would sacrifice the benefit of parallelism. For any given element, the + * action may be performed at whatever time and in whatever thread the + * library chooses. If the action accesses shared state, it is + * responsible for providing the required synchronization. + * + * @param pAction a non-interfering action to perform on the elements + */ + public void forEach(FailableConsumer pAction) { + makeTerminated(); + stream().forEach(Functions.asConsumer(pAction)); + } + + /** + * Performs a mutable reduction operation on the elements of this stream using a + * {@code Collector}. A {@code Collector} + * encapsulates the functions used as arguments to + * {@link #collect(Supplier, BiConsumer, BiConsumer)}, allowing for reuse of + * collection strategies and composition of collect operations such as + * multiple-level grouping or partitioning. + * + *

If the underlying stream is parallel, and the {@code Collector} + * is concurrent, and either the stream is unordered or the collector is + * unordered, then a concurrent reduction will be performed + * (see {@link Collector} for details on concurrent reduction.) + * + *

This is a terminal operation. + * + *

When executed in parallel, multiple intermediate results may be + * instantiated, populated, and merged so as to maintain isolation of + * mutable data structures. Therefore, even when executed in parallel + * with non-thread-safe data structures (such as {@code ArrayList}), no + * additional synchronization is needed for a parallel reduction. + * + * \@apiNote + * The following will accumulate strings into an ArrayList: + *

{@code
+	     *     List asList = stringStream.collect(Collectors.toList());
+	     * }
+ * + *

The following will classify {@code Person} objects by city: + *

{@code
+	     *     Map> peopleByCity
+	     *         = personStream.collect(Collectors.groupingBy(Person::getCity));
+	     * }
+ * + *

The following will classify {@code Person} objects by state and city, + * cascading two {@code Collector}s together: + *

{@code
+	     *     Map>> peopleByStateAndCity
+	     *         = personStream.collect(Collectors.groupingBy(Person::getState,
+	     *                                                      Collectors.groupingBy(Person::getCity)));
+	     * }
+ * + * @param the type of the result + * @param the intermediate accumulation type of the {@code Collector} + * @param pCollector the {@code Collector} describing the reduction + * @return the result of the reduction + * @see #collect(Supplier, BiConsumer, BiConsumer) + * @see Collectors + */ + public R collect(Collector pCollector) { + makeTerminated(); + return stream().collect(pCollector); + } + + /** + * Performs a mutable reduction operation on the elements of this FailableStream. + * A mutable reduction is one in which the reduced value is a mutable result + * container, such as an {@code ArrayList}, and elements are incorporated by updating + * the state of the result rather than by replacing the result. This produces a result equivalent to: + *
{@code
+	     *     R result = supplier.get();
+	     *     for (T element : this stream)
+	     *         accumulator.accept(result, element);
+	     *     return result;
+	     * }
+ * + *

Like {@link #reduce(Object, BinaryOperator)}, {@code collect} operations + * can be parallelized without requiring additional synchronization. + * + *

This is a terminal operation. + * + * \@apiNote There are many existing classes in the JDK whose signatures are + * well-suited for use with method references as arguments to {@code collect()}. + * For example, the following will accumulate strings into an {@code ArrayList}: + *

{@code
+	     *     List asList = stringStream.collect(ArrayList::new, ArrayList::add,
+	     *                                                ArrayList::addAll);
+	     * }
+ * + *

The following will take a stream of strings and concatenates them into a + * single string: + *

{@code
+	     *     String concat = stringStream.collect(StringBuilder::new, StringBuilder::append,
+	     *                                          StringBuilder::append)
+	     *                                 .toString();
+	     * }
+ * + * @param type of the result + * @param
Type of the accumulator. + * @param pSupplier a function that creates a new result container. For a + * parallel execution, this function may be called + * multiple times and must return a fresh value each time. + * @param pAccumulator An associative, non-interfering, stateless function for + * incorporating an additional element into a result + * @param pCombiner An associative, non-interfering, stateless + * function for combining two values, which must be compatible with the + * accumulator function + * @return The result of the reduction + */ + public R collect(Supplier pSupplier, BiConsumer pAccumulator, BiConsumer pCombiner) { + makeTerminated(); + return stream().collect(pSupplier, pAccumulator, pCombiner); + } + + /** + * Performs a reduction on the elements of this stream, using the provided + * identity value and an associative accumulation function, and returns + * the reduced value. This is equivalent to: + *
{@code
+	     *     T result = identity;
+	     *     for (T element : this stream)
+	     *         result = accumulator.apply(result, element)
+	     *     return result;
+	     * }
+ * + * but is not constrained to execute sequentially. + * + *

The {@code identity} value must be an identity for the accumulator + * function. This means that for all {@code t}, + * {@code accumulator.apply(identity, t)} is equal to {@code t}. + * The {@code accumulator} function must be an associative function. + * + *

This is a terminal operation. + * + * \@apiNote Sum, min, max, average, and string concatenation are all special + * cases of reduction. Summing a stream of numbers can be expressed as: + * + *

{@code
+	     *     Integer sum = integers.reduce(0, (a, b) -> a+b);
+	     * }
+ * + * or: + * + *
{@code
+	     *     Integer sum = integers.reduce(0, Integer::sum);
+	     * }
+ * + *

While this may seem a more roundabout way to perform an aggregation + * compared to simply mutating a running total in a loop, reduction + * operations parallelize more gracefully, without needing additional + * synchronization and with greatly reduced risk of data races. + * + * @param pIdentity the identity value for the accumulating function + * @param pAccumulator an associative, non-interfering, stateless + * function for combining two values + * @return the result of the reduction + */ + public O reduce(O pIdentity, BinaryOperator pAccumulator) { + makeTerminated(); + return stream().reduce(pIdentity, pAccumulator); + } + + /** + * Returns a stream consisting of the results of applying the given + * function to the elements of this stream. + * + *

This is an intermediate operation. + * + * @param The element type of the new stream + * @param pMapper A non-interfering, stateless function to apply to each element + * @return the new stream + */ + public FailableStream map(FailableFunction pMapper) { + assertNotTerminated(); + return new FailableStream(stream.map(Functions.asFunction(pMapper))); + } + + /** + * Converts the FailableStream into an equivalent stream. + * @return A stream, which will return the same elements, which this FailableStream would return. + */ + public Stream stream() { + return stream; + } + + /** + * Returns whether all elements of this stream match the provided predicate. + * May not evaluate the predicate on all elements if not necessary for + * determining the result. If the stream is empty then {@code true} is + * returned and the predicate is not evaluated. + * + *

This is a short-circuiting terminal operation. + * + * \@apiNote + * This method evaluates the universal quantification of the + * predicate over the elements of the stream (for all x P(x)). If the + * stream is empty, the quantification is said to be vacuously + * satisfied and is always {@code true} (regardless of P(x)). + * + * @param pPredicate A non-interfering, stateless predicate to apply to + * elements of this stream + * @return {@code true} If either all elements of the stream match the + * provided predicate or the stream is empty, otherwise {@code false}. + */ + public boolean allMatch(FailablePredicate pPredicate) { + assertNotTerminated(); + return stream().allMatch(Functions.asPredicate(pPredicate)); + } + + /** + * Returns whether any elements of this stream match the provided + * predicate. May not evaluate the predicate on all elements if not + * necessary for determining the result. If the stream is empty then + * {@code false} is returned and the predicate is not evaluated. + * + *

This is a short-circuiting terminal operation. + * + * \@apiNote + * This method evaluates the existential quantification of the + * predicate over the elements of the stream (for some x P(x)). + * + * @param pPredicate A non-interfering, stateless predicate to apply to + * elements of this stream + * @return {@code true} if any elements of the stream match the provided + * predicate, otherwise {@code false} + */ + public boolean anyMatch(FailablePredicate pPredicate) { + assertNotTerminated(); + return stream().anyMatch(Functions.asPredicate(pPredicate)); + } + } + + /** + * Converts the given {@link Stream stream} into a {@link FailableStream}. + * This is basically a simplified, reduced version of the {@link Stream} + * class, with the same underlying element stream, except that failable + * objects, like {@link FailablePredicate}, {@link FailableFunction}, or + * {@link FailableConsumer} may be applied, instead of + * {@link Predicate}, {@link Function}, or {@link Consumer}. The idea is + * to rewrite a code snippet like this: + *

+	 *     final List<O> list;
+	 *     final Method m;
+	 *     final Function<O,String> mapper = (o) -> {
+	 *         try {
+	 *             return (String) m.invoke(o);
+	 *         } catch (Throwable t) {
+	 *             throw Functions.rethrow(t);
+	 *         }
+	 *     };
+	 *     final List<String> strList = list.stream()
+	 *         .map(mapper).collect(Collectors.toList());
+	 *  
+ * as follows: + *
+     *     final List<O> list;
+     *     final Method m;
+     *     final List<String> strList = Functions.stream(list.stream())
+     *         .map((o) -> (String) m.invoke(o)).collect(Collectors.toList());
+     *  
+ * While the second version may not be quite as + * efficient (because it depends on the creation of additional, + * intermediate objects, of type FailableStream), it is much more + * concise, and readable, and meets the spirit of Lambdas better + * than the first version. + * @param The streams element type. + * @param pStream The stream, which is being converted. + * @return The {@link FailableStream}, which has been created by + * converting the stream. + */ + public static FailableStream stream(Stream pStream) { + return new FailableStream(pStream); + } +} diff --git a/src/test/java/org/apache/commons/lang3/StreamsTest.java b/src/test/java/org/apache/commons/lang3/StreamsTest.java new file mode 100644 index 00000000000..9ad8e781017 --- /dev/null +++ b/src/test/java/org/apache/commons/lang3/StreamsTest.java @@ -0,0 +1,176 @@ +/* + * 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 static org.junit.jupiter.api.Assertions.*; + +import java.lang.reflect.UndeclaredThrowableException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import org.apache.commons.lang3.Functions.FailableConsumer; +import org.apache.commons.lang3.Functions.FailablePredicate; +import org.junit.jupiter.api.Test; +import org.xml.sax.SAXException; + +class StreamsTest { + @Test + void testSimpleStreamMap() { + final List input = Arrays.asList("1", "2", "3", "4", "5", "6"); + final List output = Functions.stream(input).map((s) -> Integer.valueOf(s)).collect(Collectors.toList()); + assertEquals(6, output.size()); + for (int i = 0; i < 6; i++) { + assertEquals(i+1, output.get(i).intValue()); + } + } + + @Test + void testSimpleStreamMapFailing() { + final List input = Arrays.asList("1", "2", "3", "4 ", "5", "6"); + try { + Functions.stream(input).map((s) -> Integer.valueOf(s)).collect(Collectors.toList()); + fail("Expected Exception"); + } catch (NumberFormatException nfe) { + assertEquals("For input string: \"4 \"", nfe.getMessage()); + } + } + + @Test + void testSimpleStreamForEach() { + final List input = Arrays.asList("1", "2", "3", "4", "5", "6"); + final List output = new ArrayList<>(); + Functions.stream(input).forEach((s) -> output.add(Integer.valueOf(s))); + assertEquals(6, output.size()); + for (int i = 0; i < 6; i++) { + assertEquals(i+1, output.get(i).intValue()); + } + } + + protected FailableConsumer asIntConsumer(T pThrowable) { + return (s) -> { + final Integer i = Integer.valueOf(s); + if (i.intValue() == 4) { + throw pThrowable; + } + }; + } + + @Test + void testSimpleStreamForEachFailing() { + final List input = Arrays.asList("1", "2", "3", "4", "5", "6"); + final List output = new ArrayList<>(); + final IllegalArgumentException ise = new IllegalArgumentException("Invalid argument: 4"); + try { + Functions.stream(input).forEach(asIntConsumer(ise)); + fail("Expected Exception"); + } catch (IllegalArgumentException e) { + assertSame(ise, e); + } + output.clear(); + final OutOfMemoryError oome = new OutOfMemoryError(); + try { + Functions.stream(input).forEach(asIntConsumer(oome)); + fail("Expected Exception"); + } catch (Throwable t) { + assertSame(oome, t); + } + output.clear(); + final SAXException se = new SAXException(); + try { + Functions.stream(input).forEach(asIntConsumer(se)); + fail("Expected Exception"); + } catch (UndeclaredThrowableException ute) { + assertSame(se, ute.getCause()); + } + } + + @Test + void testSimpleStreamFilter() { + final List input = Arrays.asList("1", "2", "3", "4", "5", "6"); + final List output = Functions.stream(input) + .map((s) -> Integer.valueOf(s)) + .filter((i) -> { return i.intValue() %2 == 0;}) + .collect(Collectors.toList()); + assertEvenNumbers(output); + } + + private void assertEvenNumbers(final List output) { + assertEquals(3, output.size()); + for (int i = 0; i < 3; i++) { + assertEquals((i+1)*2, output.get(i).intValue()); + } + } + + protected FailablePredicate asIntPredicate(T pThrowable) { + return (i) -> { + if (i.intValue() == 5) { + if (pThrowable != null) { + throw pThrowable; + } + } + return i%2==0; + }; + } + + @Test + void testSimpleStreamFilterFailing() { + final List input = Arrays.asList("1", "2", "3", "4", "5", "6"); + final List output = Functions.stream(input) + .map((s) -> Integer.valueOf(s)) + .filter(asIntPredicate(null)) + .collect(Collectors.toList()); + assertEvenNumbers(output); + + output.clear(); + final IllegalArgumentException iae = new IllegalArgumentException("Invalid argument: " + 5); + try { + Functions.stream(input) + .map((s) -> Integer.valueOf(s)) + .filter(asIntPredicate(iae)) + .collect(Collectors.toList()); + fail("Expected Exception"); + } catch (IllegalArgumentException e) { + assertSame(iae, e); + } + + output.clear(); + final OutOfMemoryError oome = new OutOfMemoryError(); + try { + Functions.stream(input) + .map((s) -> Integer.valueOf(s)) + .filter(asIntPredicate(oome)) + .collect(Collectors.toList()); + fail("Expected Exception"); + } catch (Throwable t) { + assertSame(oome, t); + } + + output.clear(); + final SAXException se = new SAXException(); + try { + Functions.stream(input) + .map((s) -> Integer.valueOf(s)) + .filter(asIntPredicate(se)) + .collect(Collectors.toList()); + fail("Expected Exception"); + } catch (UndeclaredThrowableException t) { + assertSame(se, t.getCause()); + } + } +} From 3ce3b27dbd579a918e97e1fb09e9b0153cc71a60 Mon Sep 17 00:00:00 2001 From: Jochen Wiedmann Date: Fri, 7 Feb 2020 21:59:23 +0100 Subject: [PATCH 0006/3230] Fixing Checkstyle problems. --- .../org/apache/commons/lang3/Streams.java | 631 ++++++++++-------- .../org/apache/commons/lang3/StreamsTest.java | 12 +- 2 files changed, 345 insertions(+), 298 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/Streams.java b/src/main/java/org/apache/commons/lang3/Streams.java index a0f32afecc7..c097d76f371 100644 --- a/src/main/java/org/apache/commons/lang3/Streams.java +++ b/src/main/java/org/apache/commons/lang3/Streams.java @@ -16,6 +16,7 @@ */ package org.apache.commons.lang3; +import java.util.Collection; import java.util.function.BiConsumer; import java.util.function.BinaryOperator; import java.util.function.Consumer; @@ -48,7 +49,7 @@ * * Using a {@link FailableStream}, this can be rewritten as follows: *
- *     ObjectStreams.failable(stream).forEach((m) -> m.invoke(o, args));
+ *     Streams.failable(stream).forEach((m) -> m.invoke(o, args));
  * 
* Obviously, the second version is much more concise and the spirit of * Lambda expressions is met better than in the first version. @@ -56,309 +57,351 @@ * @see Functions */ public class Streams { - /** A reduced, and simplified version of a {@link Stream} with - * failable method signatures. - * @param The streams element type. - */ - public static class FailableStream { - private Stream stream; - private boolean terminated; + /** A reduced, and simplified version of a {@link Stream} with + * failable method signatures. + * @param The streams element type. + */ + public static class FailableStream { + private Stream stream; + private boolean terminated; - public FailableStream(Stream pStream) { - stream = pStream; - } + public FailableStream(Stream pStream) { + stream = pStream; + } - protected void assertNotTerminated() { - if (terminated) { - throw new IllegalStateException("This stream is already terminated."); - } - } + protected void assertNotTerminated() { + if (terminated) { + throw new IllegalStateException("This stream is already terminated."); + } + } - protected void makeTerminated() { - assertNotTerminated(); - terminated = true; - } + protected void makeTerminated() { + assertNotTerminated(); + terminated = true; + } - /** - * Returns a FailableStream consisting of the elements of this stream that match - * the given FailablePredicate. - * - *

This is an intermediate operation. - * - * @param pPredicate a non-interfering, stateless predicate to apply to each - * element to determine if it should be included. - * @return the new stream - */ - public FailableStream filter(FailablePredicate pPredicate){ - assertNotTerminated(); - stream = stream.filter(Functions.asPredicate(pPredicate)); - return this; - } + /** + * Returns a FailableStream consisting of the elements of this stream that match + * the given FailablePredicate. + * + *

This is an intermediate operation. + * + * @param pPredicate a non-interfering, stateless predicate to apply to each + * element to determine if it should be included. + * @return the new stream + */ + public FailableStream filter(FailablePredicate pPredicate){ + assertNotTerminated(); + stream = stream.filter(Functions.asPredicate(pPredicate)); + return this; + } - /** - * Performs an action for each element of this stream. - * - *

This is a terminal operation. - * - *

The behavior of this operation is explicitly nondeterministic. - * For parallel stream pipelines, this operation does not - * guarantee to respect the encounter order of the stream, as doing so - * would sacrifice the benefit of parallelism. For any given element, the - * action may be performed at whatever time and in whatever thread the - * library chooses. If the action accesses shared state, it is - * responsible for providing the required synchronization. - * - * @param pAction a non-interfering action to perform on the elements - */ - public void forEach(FailableConsumer pAction) { - makeTerminated(); - stream().forEach(Functions.asConsumer(pAction)); - } + /** + * Performs an action for each element of this stream. + * + *

This is a terminal operation. + * + *

The behavior of this operation is explicitly nondeterministic. + * For parallel stream pipelines, this operation does not + * guarantee to respect the encounter order of the stream, as doing so + * would sacrifice the benefit of parallelism. For any given element, the + * action may be performed at whatever time and in whatever thread the + * library chooses. If the action accesses shared state, it is + * responsible for providing the required synchronization. + * + * @param pAction a non-interfering action to perform on the elements + */ + public void forEach(FailableConsumer pAction) { + makeTerminated(); + stream().forEach(Functions.asConsumer(pAction)); + } - /** - * Performs a mutable reduction operation on the elements of this stream using a - * {@code Collector}. A {@code Collector} - * encapsulates the functions used as arguments to - * {@link #collect(Supplier, BiConsumer, BiConsumer)}, allowing for reuse of - * collection strategies and composition of collect operations such as - * multiple-level grouping or partitioning. - * - *

If the underlying stream is parallel, and the {@code Collector} - * is concurrent, and either the stream is unordered or the collector is - * unordered, then a concurrent reduction will be performed - * (see {@link Collector} for details on concurrent reduction.) - * - *

This is a terminal operation. - * - *

When executed in parallel, multiple intermediate results may be - * instantiated, populated, and merged so as to maintain isolation of - * mutable data structures. Therefore, even when executed in parallel - * with non-thread-safe data structures (such as {@code ArrayList}), no - * additional synchronization is needed for a parallel reduction. - * - * \@apiNote - * The following will accumulate strings into an ArrayList: - *

{@code
-	     *     List asList = stringStream.collect(Collectors.toList());
-	     * }
- * - *

The following will classify {@code Person} objects by city: - *

{@code
-	     *     Map> peopleByCity
-	     *         = personStream.collect(Collectors.groupingBy(Person::getCity));
-	     * }
- * - *

The following will classify {@code Person} objects by state and city, - * cascading two {@code Collector}s together: - *

{@code
-	     *     Map>> peopleByStateAndCity
-	     *         = personStream.collect(Collectors.groupingBy(Person::getState,
-	     *                                                      Collectors.groupingBy(Person::getCity)));
-	     * }
- * - * @param the type of the result - * @param
the intermediate accumulation type of the {@code Collector} - * @param pCollector the {@code Collector} describing the reduction - * @return the result of the reduction - * @see #collect(Supplier, BiConsumer, BiConsumer) - * @see Collectors - */ - public R collect(Collector pCollector) { + /** + * Performs a mutable reduction operation on the elements of this stream using a + * {@code Collector}. A {@code Collector} + * encapsulates the functions used as arguments to + * {@link #collect(Supplier, BiConsumer, BiConsumer)}, allowing for reuse of + * collection strategies and composition of collect operations such as + * multiple-level grouping or partitioning. + * + *

If the underlying stream is parallel, and the {@code Collector} + * is concurrent, and either the stream is unordered or the collector is + * unordered, then a concurrent reduction will be performed + * (see {@link Collector} for details on concurrent reduction.) + * + *

This is a terminal operation. + * + *

When executed in parallel, multiple intermediate results may be + * instantiated, populated, and merged so as to maintain isolation of + * mutable data structures. Therefore, even when executed in parallel + * with non-thread-safe data structures (such as {@code ArrayList}), no + * additional synchronization is needed for a parallel reduction. + * + * \@apiNote + * The following will accumulate strings into an ArrayList: + *

{@code
+         *     List asList = stringStream.collect(Collectors.toList());
+         * }
+ * + *

The following will classify {@code Person} objects by city: + *

{@code
+         *     Map> peopleByCity
+         *         = personStream.collect(Collectors.groupingBy(Person::getCity));
+         * }
+ * + *

The following will classify {@code Person} objects by state and city, + * cascading two {@code Collector}s together: + *

{@code
+         *     Map>> peopleByStateAndCity
+         *         = personStream.collect(Collectors.groupingBy(Person::getState,
+         *                                                      Collectors.groupingBy(Person::getCity)));
+         * }
+ * + * @param the type of the result + * @param
the intermediate accumulation type of the {@code Collector} + * @param pCollector the {@code Collector} describing the reduction + * @return the result of the reduction + * @see #collect(Supplier, BiConsumer, BiConsumer) + * @see Collectors + */ + public R collect(Collector pCollector) { makeTerminated(); - return stream().collect(pCollector); - } + return stream().collect(pCollector); + } - /** - * Performs a mutable reduction operation on the elements of this FailableStream. - * A mutable reduction is one in which the reduced value is a mutable result - * container, such as an {@code ArrayList}, and elements are incorporated by updating - * the state of the result rather than by replacing the result. This produces a result equivalent to: - *
{@code
-	     *     R result = supplier.get();
-	     *     for (T element : this stream)
-	     *         accumulator.accept(result, element);
-	     *     return result;
-	     * }
- * - *

Like {@link #reduce(Object, BinaryOperator)}, {@code collect} operations - * can be parallelized without requiring additional synchronization. - * - *

This is a terminal operation. - * - * \@apiNote There are many existing classes in the JDK whose signatures are - * well-suited for use with method references as arguments to {@code collect()}. - * For example, the following will accumulate strings into an {@code ArrayList}: - *

{@code
-	     *     List asList = stringStream.collect(ArrayList::new, ArrayList::add,
-	     *                                                ArrayList::addAll);
-	     * }
- * - *

The following will take a stream of strings and concatenates them into a - * single string: - *

{@code
-	     *     String concat = stringStream.collect(StringBuilder::new, StringBuilder::append,
-	     *                                          StringBuilder::append)
-	     *                                 .toString();
-	     * }
- * - * @param type of the result - * @param
Type of the accumulator. - * @param pSupplier a function that creates a new result container. For a - * parallel execution, this function may be called - * multiple times and must return a fresh value each time. - * @param pAccumulator An associative, non-interfering, stateless function for - * incorporating an additional element into a result - * @param pCombiner An associative, non-interfering, stateless - * function for combining two values, which must be compatible with the - * accumulator function - * @return The result of the reduction - */ - public R collect(Supplier pSupplier, BiConsumer pAccumulator, BiConsumer pCombiner) { + /** + * Performs a mutable reduction operation on the elements of this FailableStream. + * A mutable reduction is one in which the reduced value is a mutable result + * container, such as an {@code ArrayList}, and elements are incorporated by updating + * the state of the result rather than by replacing the result. This produces a result equivalent to: + *
{@code
+         *     R result = supplier.get();
+         *     for (T element : this stream)
+         *         accumulator.accept(result, element);
+         *     return result;
+         * }
+ * + *

Like {@link #reduce(Object, BinaryOperator)}, {@code collect} operations + * can be parallelized without requiring additional synchronization. + * + *

This is a terminal operation. + * + * \@apiNote There are many existing classes in the JDK whose signatures are + * well-suited for use with method references as arguments to {@code collect()}. + * For example, the following will accumulate strings into an {@code ArrayList}: + *

{@code
+         *     List asList = stringStream.collect(ArrayList::new, ArrayList::add,
+         *                                                ArrayList::addAll);
+         * }
+ * + *

The following will take a stream of strings and concatenates them into a + * single string: + *

{@code
+         *     String concat = stringStream.collect(StringBuilder::new, StringBuilder::append,
+         *                                          StringBuilder::append)
+         *                                 .toString();
+         * }
+ * + * @param type of the result + * @param
Type of the accumulator. + * @param pSupplier a function that creates a new result container. For a + * parallel execution, this function may be called + * multiple times and must return a fresh value each time. + * @param pAccumulator An associative, non-interfering, stateless function for + * incorporating an additional element into a result + * @param pCombiner An associative, non-interfering, stateless + * function for combining two values, which must be compatible with the + * accumulator function + * @return The result of the reduction + */ + public R collect(Supplier pSupplier, BiConsumer pAccumulator, BiConsumer pCombiner) { makeTerminated(); - return stream().collect(pSupplier, pAccumulator, pCombiner); - } + return stream().collect(pSupplier, pAccumulator, pCombiner); + } - /** - * Performs a reduction on the elements of this stream, using the provided - * identity value and an associative accumulation function, and returns - * the reduced value. This is equivalent to: - *
{@code
-	     *     T result = identity;
-	     *     for (T element : this stream)
-	     *         result = accumulator.apply(result, element)
-	     *     return result;
-	     * }
- * - * but is not constrained to execute sequentially. - * - *

The {@code identity} value must be an identity for the accumulator - * function. This means that for all {@code t}, - * {@code accumulator.apply(identity, t)} is equal to {@code t}. - * The {@code accumulator} function must be an associative function. - * - *

This is a terminal operation. - * - * \@apiNote Sum, min, max, average, and string concatenation are all special - * cases of reduction. Summing a stream of numbers can be expressed as: - * - *

{@code
-	     *     Integer sum = integers.reduce(0, (a, b) -> a+b);
-	     * }
- * - * or: - * - *
{@code
-	     *     Integer sum = integers.reduce(0, Integer::sum);
-	     * }
- * - *

While this may seem a more roundabout way to perform an aggregation - * compared to simply mutating a running total in a loop, reduction - * operations parallelize more gracefully, without needing additional - * synchronization and with greatly reduced risk of data races. - * - * @param pIdentity the identity value for the accumulating function - * @param pAccumulator an associative, non-interfering, stateless - * function for combining two values - * @return the result of the reduction - */ - public O reduce(O pIdentity, BinaryOperator pAccumulator) { + /** + * Performs a reduction on the elements of this stream, using the provided + * identity value and an associative accumulation function, and returns + * the reduced value. This is equivalent to: + *

{@code
+         *     T result = identity;
+         *     for (T element : this stream)
+         *         result = accumulator.apply(result, element)
+         *     return result;
+         * }
+ * + * but is not constrained to execute sequentially. + * + *

The {@code identity} value must be an identity for the accumulator + * function. This means that for all {@code t}, + * {@code accumulator.apply(identity, t)} is equal to {@code t}. + * The {@code accumulator} function must be an associative function. + * + *

This is a terminal operation. + * + * \@apiNote Sum, min, max, average, and string concatenation are all special + * cases of reduction. Summing a stream of numbers can be expressed as: + * + *

{@code
+         *     Integer sum = integers.reduce(0, (a, b) -> a+b);
+         * }
+ * + * or: + * + *
{@code
+         *     Integer sum = integers.reduce(0, Integer::sum);
+         * }
+ * + *

While this may seem a more roundabout way to perform an aggregation + * compared to simply mutating a running total in a loop, reduction + * operations parallelize more gracefully, without needing additional + * synchronization and with greatly reduced risk of data races. + * + * @param pIdentity the identity value for the accumulating function + * @param pAccumulator an associative, non-interfering, stateless + * function for combining two values + * @return the result of the reduction + */ + public O reduce(O pIdentity, BinaryOperator pAccumulator) { makeTerminated(); - return stream().reduce(pIdentity, pAccumulator); - } + return stream().reduce(pIdentity, pAccumulator); + } - /** - * Returns a stream consisting of the results of applying the given - * function to the elements of this stream. - * - *

This is an intermediate operation. - * - * @param The element type of the new stream - * @param pMapper A non-interfering, stateless function to apply to each element - * @return the new stream - */ - public FailableStream map(FailableFunction pMapper) { - assertNotTerminated(); - return new FailableStream(stream.map(Functions.asFunction(pMapper))); - } + /** + * Returns a stream consisting of the results of applying the given + * function to the elements of this stream. + * + *

This is an intermediate operation. + * + * @param The element type of the new stream + * @param pMapper A non-interfering, stateless function to apply to each element + * @return the new stream + */ + public FailableStream map(FailableFunction pMapper) { + assertNotTerminated(); + return new FailableStream(stream.map(Functions.asFunction(pMapper))); + } - /** - * Converts the FailableStream into an equivalent stream. - * @return A stream, which will return the same elements, which this FailableStream would return. - */ - public Stream stream() { - return stream; - } + /** + * Converts the FailableStream into an equivalent stream. + * @return A stream, which will return the same elements, which this FailableStream would return. + */ + public Stream stream() { + return stream; + } - /** - * Returns whether all elements of this stream match the provided predicate. - * May not evaluate the predicate on all elements if not necessary for - * determining the result. If the stream is empty then {@code true} is - * returned and the predicate is not evaluated. - * - *

This is a short-circuiting terminal operation. - * - * \@apiNote - * This method evaluates the universal quantification of the - * predicate over the elements of the stream (for all x P(x)). If the - * stream is empty, the quantification is said to be vacuously - * satisfied and is always {@code true} (regardless of P(x)). - * - * @param pPredicate A non-interfering, stateless predicate to apply to - * elements of this stream - * @return {@code true} If either all elements of the stream match the - * provided predicate or the stream is empty, otherwise {@code false}. - */ - public boolean allMatch(FailablePredicate pPredicate) { - assertNotTerminated(); - return stream().allMatch(Functions.asPredicate(pPredicate)); - } + /** + * Returns whether all elements of this stream match the provided predicate. + * May not evaluate the predicate on all elements if not necessary for + * determining the result. If the stream is empty then {@code true} is + * returned and the predicate is not evaluated. + * + *

This is a short-circuiting terminal operation. + * + * \@apiNote + * This method evaluates the universal quantification of the + * predicate over the elements of the stream (for all x P(x)). If the + * stream is empty, the quantification is said to be vacuously + * satisfied and is always {@code true} (regardless of P(x)). + * + * @param pPredicate A non-interfering, stateless predicate to apply to + * elements of this stream + * @return {@code true} If either all elements of the stream match the + * provided predicate or the stream is empty, otherwise {@code false}. + */ + public boolean allMatch(FailablePredicate pPredicate) { + assertNotTerminated(); + return stream().allMatch(Functions.asPredicate(pPredicate)); + } - /** - * Returns whether any elements of this stream match the provided - * predicate. May not evaluate the predicate on all elements if not - * necessary for determining the result. If the stream is empty then - * {@code false} is returned and the predicate is not evaluated. - * - *

This is a short-circuiting terminal operation. - * - * \@apiNote - * This method evaluates the existential quantification of the - * predicate over the elements of the stream (for some x P(x)). - * - * @param pPredicate A non-interfering, stateless predicate to apply to - * elements of this stream - * @return {@code true} if any elements of the stream match the provided - * predicate, otherwise {@code false} - */ - public boolean anyMatch(FailablePredicate pPredicate) { + /** + * Returns whether any elements of this stream match the provided + * predicate. May not evaluate the predicate on all elements if not + * necessary for determining the result. If the stream is empty then + * {@code false} is returned and the predicate is not evaluated. + * + *

This is a short-circuiting terminal operation. + * + * \@apiNote + * This method evaluates the existential quantification of the + * predicate over the elements of the stream (for some x P(x)). + * + * @param pPredicate A non-interfering, stateless predicate to apply to + * elements of this stream + * @return {@code true} if any elements of the stream match the provided + * predicate, otherwise {@code false} + */ + public boolean anyMatch(FailablePredicate pPredicate) { assertNotTerminated(); return stream().anyMatch(Functions.asPredicate(pPredicate)); - } - } + } + } + + /** + * Converts the given {@link Stream stream} into a {@link FailableStream}. + * This is basically a simplified, reduced version of the {@link Stream} + * class, with the same underlying element stream, except that failable + * objects, like {@link FailablePredicate}, {@link FailableFunction}, or + * {@link FailableConsumer} may be applied, instead of + * {@link Predicate}, {@link Function}, or {@link Consumer}. The idea is + * to rewrite a code snippet like this: + *

+     *     final List<O> list;
+     *     final Method m;
+     *     final Function<O,String> mapper = (o) -> {
+     *         try {
+     *             return (String) m.invoke(o);
+     *         } catch (Throwable t) {
+     *             throw Functions.rethrow(t);
+     *         }
+     *     };
+     *     final List<String> strList = list.stream()
+     *         .map(mapper).collect(Collectors.toList());
+     *  
+ * as follows: + *
+     *     final List<O> list;
+     *     final Method m;
+     *     final List<String> strList = Functions.stream(list.stream())
+     *         .map((o) -> (String) m.invoke(o)).collect(Collectors.toList());
+     *  
+ * While the second version may not be quite as + * efficient (because it depends on the creation of additional, + * intermediate objects, of type FailableStream), it is much more + * concise, and readable, and meets the spirit of Lambdas better + * than the first version. + * @param The streams element type. + * @param pStream The stream, which is being converted. + * @return The {@link FailableStream}, which has been created by + * converting the stream. + */ + public static FailableStream stream(Stream pStream) { + return new FailableStream(pStream); + } - /** - * Converts the given {@link Stream stream} into a {@link FailableStream}. - * This is basically a simplified, reduced version of the {@link Stream} - * class, with the same underlying element stream, except that failable - * objects, like {@link FailablePredicate}, {@link FailableFunction}, or - * {@link FailableConsumer} may be applied, instead of - * {@link Predicate}, {@link Function}, or {@link Consumer}. The idea is - * to rewrite a code snippet like this: - *
-	 *     final List<O> list;
-	 *     final Method m;
-	 *     final Function<O,String> mapper = (o) -> {
-	 *         try {
-	 *             return (String) m.invoke(o);
-	 *         } catch (Throwable t) {
-	 *             throw Functions.rethrow(t);
-	 *         }
-	 *     };
-	 *     final List<String> strList = list.stream()
-	 *         .map(mapper).collect(Collectors.toList());
-	 *  
- * as follows: - *
+    /**
+     * Converts the given {@link Collection} into a {@link FailableStream}.
+     * This is basically a simplified, reduced version of the {@link Stream}
+     * class, with the same underlying element stream, except that failable
+     * objects, like {@link FailablePredicate}, {@link FailableFunction}, or
+     * {@link FailableConsumer} may be applied, instead of
+     * {@link Predicate}, {@link Function}, or {@link Consumer}. The idea is
+     * to rewrite a code snippet like this:
+     * 
+     *     final List<O> list;
+     *     final Method m;
+     *     final Function<O,String> mapper = (o) -> {
+     *         try {
+     *             return (String) m.invoke(o);
+     *         } catch (Throwable t) {
+     *             throw Functions.rethrow(t);
+     *         }
+     *     };
+     *     final List<String> strList = list.stream()
+     *         .map(mapper).collect(Collectors.toList());
+     *  
+ * as follows: + *
      *     final List<O> list;
      *     final Method m;
      *     final List<String> strList = Functions.stream(list.stream())
@@ -369,12 +412,12 @@ public boolean anyMatch(FailablePredicate pPredicate) {
      *  intermediate objects, of type FailableStream), it is much more
      *  concise, and readable, and meets the spirit of Lambdas better
      *  than the first version.
-	 * @param  The streams element type.
-	 * @param pStream The stream, which is being converted.
-	 * @return The {@link FailableStream}, which has been created by
-	 *   converting the stream.
-	 */
-	public static  FailableStream stream(Stream pStream) {
-		return new FailableStream(pStream);
-	}
+     * @param  The streams element type.
+     * @param pStream The stream, which is being converted.
+     * @return The {@link FailableStream}, which has been created by
+     *   converting the stream.
+     */
+    public static  FailableStream stream(Collection pStream) {
+        return stream(pStream.stream());
+    }
 }
diff --git a/src/test/java/org/apache/commons/lang3/StreamsTest.java b/src/test/java/org/apache/commons/lang3/StreamsTest.java
index 9ad8e781017..3ce713d9321 100644
--- a/src/test/java/org/apache/commons/lang3/StreamsTest.java
+++ b/src/test/java/org/apache/commons/lang3/StreamsTest.java
@@ -16,7 +16,9 @@
  */
 package org.apache.commons.lang3;
 
-import static org.junit.jupiter.api.Assertions.*;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.fail;
 
 import java.lang.reflect.UndeclaredThrowableException;
 import java.util.ArrayList;
@@ -62,7 +64,7 @@ void testSimpleStreamForEach() {
         }
     }
 
-    protected  FailableConsumer asIntConsumer(T pThrowable) {
+    protected  FailableConsumer asIntConsumer(T pThrowable) {
         return (s) -> {
             final Integer i = Integer.valueOf(s);
             if (i.intValue() == 4) {
@@ -105,7 +107,9 @@ void testSimpleStreamFilter() {
         final List input = Arrays.asList("1", "2", "3", "4", "5", "6");
         final List output = Functions.stream(input)
                 .map((s) -> Integer.valueOf(s))
-                .filter((i) -> { return i.intValue() %2 == 0;})
+                .filter((i) -> {
+                    return i.intValue() %2 == 0;
+                })
                 .collect(Collectors.toList());
         assertEvenNumbers(output);
     }
@@ -117,7 +121,7 @@ private void assertEvenNumbers(final List output) {
         }
     }
 
-    protected  FailablePredicate asIntPredicate(T pThrowable) {
+    protected  FailablePredicate asIntPredicate(T pThrowable) {
         return (i) -> {
             if (i.intValue() == 5) {
                 if (pThrowable != null) {

From e6165e93770844a8bc1627a2f56807b6e4d6357b Mon Sep 17 00:00:00 2001
From: Gary Gregory 
Date: Thu, 13 Feb 2020 10:25:56 -0500
Subject: [PATCH 0007/3230] - Update copyright year in NOTICE file. -
 org.easymock:easymock 4.1 -> 4.2. - org.junit-pioneer:junit-pioneer 0.4.2 ->
 0.5.3. - org.junit.jupiter:junit-jupiter 5.5.2 -> 5.6.0.

---
 NOTICE.txt              | 2 +-
 pom.xml                 | 6 +++---
 src/changes/changes.xml | 3 +++
 3 files changed, 7 insertions(+), 4 deletions(-)

diff --git a/NOTICE.txt b/NOTICE.txt
index 13a31408974..f223e8f63ac 100644
--- a/NOTICE.txt
+++ b/NOTICE.txt
@@ -1,5 +1,5 @@
 Apache Commons Lang
-Copyright 2001-2019 The Apache Software Foundation
+Copyright 2001-2020 The Apache Software Foundation
 
 This product includes software developed at
 The Apache Software Foundation (http://www.apache.org/).
diff --git a/pom.xml b/pom.xml
index 1505a02856c..6fad1760ef1 100644
--- a/pom.xml
+++ b/pom.xml
@@ -516,13 +516,13 @@
     
       org.junit.jupiter
       junit-jupiter
-      5.5.2
+      5.6.0
       test
     
     
       org.junit-pioneer
       junit-pioneer
-      0.4.2
+      0.5.3
       test
     
     
@@ -535,7 +535,7 @@
     
       org.easymock
       easymock
-      4.1
+      4.2
       test
     
 
diff --git a/src/changes/changes.xml b/src/changes/changes.xml
index c5516d5f222..d5c731ca7fb 100644
--- a/src/changes/changes.xml
+++ b/src/changes/changes.xml
@@ -96,6 +96,9 @@ The  type attribute can be add,update,fix,remove.
     Add IS_JAVA_14 and IS_JAVA_15 to org.apache.commons.lang3.SystemUtils.
     ObjectUtils: Get first non-null supplier value.
     Added the Streams class, and Functions.stream() as an accessor thereof.
+    org.easymock:easymock 4.1 -> 4.2.
+    org.junit-pioneer:junit-pioneer 0.4.2 -> 0.5.3.
+    org.junit.jupiter:junit-jupiter 5.5.2 -> 5.6.0.
   
 
   

From cb0f461237cc9a6fe7082b4a88578cf02a5362f2 Mon Sep 17 00:00:00 2001
From: "Bruno P. Kinoshita" 
Date: Fri, 14 Feb 2020 09:49:59 +1300
Subject: [PATCH 0008/3230] [LANG-1514]: add changes.xml entry

---
 src/changes/changes.xml | 1 +
 1 file changed, 1 insertion(+)

diff --git a/src/changes/changes.xml b/src/changes/changes.xml
index 11f89c4fbee..f16d1511e43 100644
--- a/src/changes/changes.xml
+++ b/src/changes/changes.xml
@@ -46,6 +46,7 @@ The  type attribute can be add,update,fix,remove.
   
 
   
+    Make test more stable by wrapping assertions in hashset.
     Generate Javadoc jar on build.
     Add ExceptionUtils.throwableOfType(Throwable, Class) and friends.
     Add EMPTY_ARRAY constants to classes in org.apache.commons.lang3.tuple.

From 31e726e471b8fe105069bdb27d473fa03d0e13cc Mon Sep 17 00:00:00 2001
From: Gary Gregory 
Date: Fri, 14 Feb 2020 09:33:00 -0500
Subject: [PATCH 0009/3230] Javadoc.

---
 .../java/org/apache/commons/lang3/ClassUtils.java   | 13 +++++++++----
 1 file changed, 9 insertions(+), 4 deletions(-)

diff --git a/src/main/java/org/apache/commons/lang3/ClassUtils.java b/src/main/java/org/apache/commons/lang3/ClassUtils.java
index 4b90ab2973e..2b8927c537f 100644
--- a/src/main/java/org/apache/commons/lang3/ClassUtils.java
+++ b/src/main/java/org/apache/commons/lang3/ClassUtils.java
@@ -50,7 +50,12 @@ public class ClassUtils {
      * @since 3.2
      */
     public enum Interfaces {
-        INCLUDE, EXCLUDE
+
+        /** Includes interfaces. */
+        INCLUDE,
+        
+        /** Excludes interfaces. */
+        EXCLUDE
     }
 
     /**
@@ -598,7 +603,7 @@ public static List> getAllInterfaces(final Class cls) {
     }
 
     /**
-     * Get the interfaces for the specified class.
+     * Gets the interfaces for the specified class.
      *
      * @param cls  the class to look up, may be {@code null}
      * @param interfacesFound the {@code Set} of interfaces for the class
@@ -1468,7 +1473,7 @@ private static String getCanonicalName(String className) {
     }
 
     /**
-     * Get an {@link Iterable} that can iterate over a class hierarchy in ascending (subclass to superclass) order,
+     * Gets an {@link Iterable} that can iterate over a class hierarchy in ascending (subclass to superclass) order,
      * excluding interfaces.
      *
      * @param type the type to get the class hierarchy from
@@ -1480,7 +1485,7 @@ public static Iterable> hierarchy(final Class type) {
     }
 
     /**
-     * Get an {@link Iterable} that can iterate over a class hierarchy in ascending (subclass to superclass) order.
+     * Gets an {@link Iterable} that can iterate over a class hierarchy in ascending (subclass to superclass) order.
      *
      * @param type the type to get the class hierarchy from
      * @param interfacesBehavior switch indicating whether to include or exclude interfaces

From 4ebd3e398804ed374d05e74f0233e0ce5517b3f7 Mon Sep 17 00:00:00 2001
From: Gary Gregory 
Date: Fri, 14 Feb 2020 09:34:46 -0500
Subject: [PATCH 0010/3230] Update SpotBugs.

---
 pom.xml | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/pom.xml b/pom.xml
index 6fad1760ef1..b2503f1c98c 100644
--- a/pom.xml
+++ b/pom.xml
@@ -764,7 +764,7 @@
           
             com.github.spotbugs
             spotbugs
-            4.0.0-beta4
+            4.0.0-RC3
          
                 
         

From 485876f9c2d90b211b5776567086ec0700767f3c Mon Sep 17 00:00:00 2001
From: Gary Gregory 
Date: Fri, 14 Feb 2020 09:36:04 -0500
Subject: [PATCH 0011/3230] Use final.

---
 .../org/apache/commons/lang3/ArrayUtils.java  | 22 ++---
 .../org/apache/commons/lang3/ClassUtils.java  |  2 +-
 .../org/apache/commons/lang3/Functions.java   | 80 +++++++++---------
 .../org/apache/commons/lang3/ObjectUtils.java |  2 +-
 .../org/apache/commons/lang3/Streams.java     | 22 ++---
 .../org/apache/commons/lang3/StringUtils.java |  8 +-
 .../commons/lang3/builder/EqualsBuilder.java  |  2 +-
 .../org/apache/commons/lang3/tuple/Pair.java  |  2 +-
 .../apache/commons/lang3/ArchUtilsTest.java   |  2 +-
 .../apache/commons/lang3/ArrayUtilsTest.java  | 82 +++++++++----------
 .../apache/commons/lang3/CharRangeTest.java   |  2 +-
 .../apache/commons/lang3/FunctionsTest.java   | 36 ++++----
 .../apache/commons/lang3/LocaleUtilsTest.java |  2 +-
 .../apache/commons/lang3/ObjectUtilsTest.java |  8 +-
 .../commons/lang3/RandomStringUtilsTest.java  |  2 +-
 .../commons/lang3/SerializationUtilsTest.java |  4 +-
 .../org/apache/commons/lang3/StreamsTest.java | 18 ++--
 .../apache/commons/lang3/StringUtilsTest.java | 14 ++--
 .../apache/commons/lang3/ValidateTest.java    |  4 +-
 .../lang3/builder/EqualsBuilderTest.java      |  2 +-
 .../ReflectionToStringBuilderSummaryTest.java |  4 +-
 .../concurrent/BackgroundInitializerTest.java |  4 +-
 .../lang3/concurrent/ConcurrentUtilsTest.java | 22 ++---
 .../EventCountCircuitBreakerTest.java         |  4 +-
 .../MultiBackgroundInitializerTest.java       |  2 +-
 .../commons/lang3/event/EventUtilsTest.java   |  4 +-
 .../lang3/exception/ExceptionUtilsTest.java   | 10 +--
 .../commons/lang3/reflect/FieldUtilsTest.java | 12 +--
 .../commons/lang3/text/StrBuilderTest.java    | 16 ++--
 .../lang3/text/StrSubstitutorTest.java        |  4 +-
 .../commons/lang3/time/DateUtilsTest.java     |  4 +-
 .../lang3/time/FastDateParserSDFTest.java     |  4 +-
 .../time/FastDatePrinterTimeZonesTest.java    |  2 +-
 .../commons/lang3/time/WeekYearTest.java      |  4 +-
 .../lang3/tuple/ImmutablePairTest.java        | 22 ++---
 .../lang3/tuple/ImmutableTripleTest.java      | 22 ++---
 .../commons/lang3/tuple/MutablePairTest.java  |  2 +-
 .../apache/commons/lang3/tuple/PairTest.java  |  2 +-
 38 files changed, 230 insertions(+), 230 deletions(-)

diff --git a/src/main/java/org/apache/commons/lang3/ArrayUtils.java b/src/main/java/org/apache/commons/lang3/ArrayUtils.java
index 3cfe46ea993..1485e0c5585 100644
--- a/src/main/java/org/apache/commons/lang3/ArrayUtils.java
+++ b/src/main/java/org/apache/commons/lang3/ArrayUtils.java
@@ -1727,7 +1727,7 @@ public static BitSet indexesOf(final boolean[] array, final boolean valueToFind)
      * @since 3.10
      */
     public static BitSet indexesOf(final boolean[] array, final boolean valueToFind, int startIndex) {
-        BitSet bitSet = new BitSet();
+        final BitSet bitSet = new BitSet();
 
         if (array == null) {
             return bitSet;
@@ -1778,7 +1778,7 @@ public static BitSet indexesOf(final byte[] array, final byte valueToFind) {
      * @since 3.10
      */
     public static BitSet indexesOf(final byte[] array, final byte valueToFind, int startIndex) {
-        BitSet bitSet = new BitSet();
+        final BitSet bitSet = new BitSet();
 
         if (array == null) {
             return bitSet;
@@ -1829,7 +1829,7 @@ public static BitSet indexesOf(final char[] array, final char valueToFind) {
      * @since 3.10
      */
     public static BitSet indexesOf(final char[] array, final char valueToFind, int startIndex) {
-        BitSet bitSet = new BitSet();
+        final BitSet bitSet = new BitSet();
 
         if (array == null) {
             return bitSet;
@@ -1901,7 +1901,7 @@ public static BitSet indexesOf(final double[] array, final double valueToFind, f
      * @since 3.10
      */
     public static BitSet indexesOf(final double[] array, final double valueToFind, int startIndex) {
-        BitSet bitSet = new BitSet();
+        final BitSet bitSet = new BitSet();
 
         if (array == null) {
             return bitSet;
@@ -1943,7 +1943,7 @@ public static BitSet indexesOf(final double[] array, final double valueToFind, i
      * @since 3.10
      */
     public static BitSet indexesOf(final double[] array, final double valueToFind, int startIndex, final double tolerance) {
-        BitSet bitSet = new BitSet();
+        final BitSet bitSet = new BitSet();
 
         if (array == null) {
             return bitSet;
@@ -1994,7 +1994,7 @@ public static BitSet indexesOf(final float[] array, final float valueToFind) {
      * @since 3.10
      */
     public static BitSet indexesOf(final float[] array, final float valueToFind, int startIndex) {
-        BitSet bitSet = new BitSet();
+        final BitSet bitSet = new BitSet();
 
         if (array == null) {
             return bitSet;
@@ -2045,7 +2045,7 @@ public static BitSet indexesOf(final int[] array, final int valueToFind) {
      * @since 3.10
      */
     public static BitSet indexesOf(final int[] array, final int valueToFind, int startIndex) {
-        BitSet bitSet = new BitSet();
+        final BitSet bitSet = new BitSet();
 
         if (array == null) {
             return bitSet;
@@ -2096,7 +2096,7 @@ public static BitSet indexesOf(final long[] array, final long valueToFind) {
      * @since 3.10
      */
     public static BitSet indexesOf(final long[] array, final long valueToFind, int startIndex) {
-        BitSet bitSet = new BitSet();
+        final BitSet bitSet = new BitSet();
 
         if (array == null) {
             return bitSet;
@@ -2147,7 +2147,7 @@ public static BitSet indexesOf(final Object[] array, final Object objectToFind)
      * @since 3.10
      */
     public static BitSet indexesOf(final Object[] array, final Object objectToFind, int startIndex) {
-        BitSet bitSet = new BitSet();
+        final BitSet bitSet = new BitSet();
 
         if (array == null) {
             return bitSet;
@@ -2198,7 +2198,7 @@ public static BitSet indexesOf(final short[] array, final short valueToFind) {
      * @since 3.10
      */
     public static BitSet indexesOf(final short[] array, final short valueToFind, int startIndex) {
-        BitSet bitSet = new BitSet();
+        final BitSet bitSet = new BitSet();
 
         if (array == null) {
             return bitSet;
@@ -3084,7 +3084,7 @@ public static  T[] insert(final int index, final T[] array, final T... values
      * @return Whether the given index is safely-accessible in the given array
      * @since 3.8
      */
-    public static  boolean isArrayIndexValid(T[] array, int index) {
+    public static  boolean isArrayIndexValid(final T[] array, final int index) {
         if (getLength(array) == 0 || array.length <= index) {
             return false;
         }
diff --git a/src/main/java/org/apache/commons/lang3/ClassUtils.java b/src/main/java/org/apache/commons/lang3/ClassUtils.java
index 2b8927c537f..040eb21c924 100644
--- a/src/main/java/org/apache/commons/lang3/ClassUtils.java
+++ b/src/main/java/org/apache/commons/lang3/ClassUtils.java
@@ -282,7 +282,7 @@ public static String getSimpleName(final Class cls) {
      * @since 3.0
      * @see Class#getSimpleName()
      */
-    public static String getSimpleName(final Class cls, String valueIfNull) {
+    public static String getSimpleName(final Class cls, final String valueIfNull) {
         return cls == null ? valueIfNull : cls.getSimpleName();
     }
 
diff --git a/src/main/java/org/apache/commons/lang3/Functions.java b/src/main/java/org/apache/commons/lang3/Functions.java
index ef9c45d909b..0424e1919a8 100644
--- a/src/main/java/org/apache/commons/lang3/Functions.java
+++ b/src/main/java/org/apache/commons/lang3/Functions.java
@@ -162,7 +162,7 @@ public interface FailableSupplier {
      * @param pRunnable a {@code FailableRunnable}
      * @return a standard {@code Runnable}
      */
-    public static Runnable asRunnable(FailableRunnable pRunnable) {
+    public static Runnable asRunnable(final FailableRunnable pRunnable) {
         return () -> run(pRunnable);
     }
 
@@ -173,7 +173,7 @@ public static Runnable asRunnable(FailableRunnable pRunnable) {
      * @param pConsumer a {@code FailableConsumer}
      * @return a standard {@code Consumer}
      */
-    public static  Consumer asConsumer(FailableConsumer pConsumer) {
+    public static  Consumer asConsumer(final FailableConsumer pConsumer) {
         return (pInput) -> accept(pConsumer, pInput);
     }
 
@@ -184,7 +184,7 @@ public static  Consumer asConsumer(FailableConsumer pConsumer) {
      * @param pCallable a {@code FailableCallable}
      * @return a standard {@code Callable}
      */
-    public static  Callable asCallable(FailableCallable pCallable) {
+    public static  Callable asCallable(final FailableCallable pCallable) {
         return () -> call(pCallable);
     }
 
@@ -196,7 +196,7 @@ public static  Callable asCallable(FailableCallable pCallable) {
      * @param pConsumer a failable {@code BiConsumer}
      * @return a standard {@code BiConsumer}
      */
-    public static  BiConsumer asBiConsumer(FailableBiConsumer pConsumer) {
+    public static  BiConsumer asBiConsumer(final FailableBiConsumer pConsumer) {
         return (pInput1, pInput2) -> accept(pConsumer, pInput1, pInput2);
     }
 
@@ -208,7 +208,7 @@ public static  BiConsumer asBiConsumer(FailableBiConsumer Function asFunction(FailableFunction pFunction) {
+    public static  Function asFunction(final FailableFunction pFunction) {
         return (pInput) -> apply(pFunction, pInput);
     }
 
@@ -221,7 +221,7 @@ public static  Function asFunction(FailableFunction pFuncti
      * @param pFunction a {@code FailableBiFunction}
      * @return a standard {@code BiFunction}
      */
-    public static  BiFunction asBiFunction(FailableBiFunction pFunction) {
+    public static  BiFunction asBiFunction(final FailableBiFunction pFunction) {
         return (pInput1, pInput2) -> apply(pFunction, pInput1, pInput2);
     }
 
@@ -232,7 +232,7 @@ public static  BiFunction asBiFunction(FailableBiFunction<
      * @param pPredicate a {@code FailablePredicate}
      * @return a standard {@code Predicate}
      */
-    public static  Predicate asPredicate(FailablePredicate pPredicate) {
+    public static  Predicate asPredicate(final FailablePredicate pPredicate) {
         return (pInput) -> test(pPredicate, pInput);
     }
 
@@ -244,7 +244,7 @@ public static  Predicate asPredicate(FailablePredicate pPredicate) {
      * @param pPredicate a {@code FailableBiPredicate}
      * @return a standard {@code BiPredicate}
      */
-    public static  BiPredicate asBiPredicate(FailableBiPredicate pPredicate) {
+    public static  BiPredicate asBiPredicate(final FailableBiPredicate pPredicate) {
         return (pInput1, pInput2) -> test(pPredicate, pInput1, pInput2);
     }
 
@@ -255,7 +255,7 @@ public static  BiPredicate asBiPredicate(FailableBiPredicate Supplier asSupplier(FailableSupplier pSupplier) {
+    public static  Supplier asSupplier(final FailableSupplier pSupplier) {
         return () -> get(pSupplier);
     }
 
@@ -264,10 +264,10 @@ public static  Supplier asSupplier(FailableSupplier pSupplier) {
      * @param pRunnable The runnable to run
      * @param  the type of checked exception the runnable may throw
      */
-    public static  void run(FailableRunnable pRunnable) {
+    public static  void run(final FailableRunnable pRunnable) {
         try {
             pRunnable.run();
-        } catch (Throwable t) {
+        } catch (final Throwable t) {
             throw rethrow(t);
         }
     }
@@ -279,10 +279,10 @@ public static  void run(FailableRunnable pRunnable) {
      * @param  the type of checked exception the callable may throw
      * @return the value returned from the callable
      */
-    public static  O call(FailableCallable pCallable) {
+    public static  O call(final FailableCallable pCallable) {
         try {
             return pCallable.call();
-        } catch (Throwable t) {
+        } catch (final Throwable t) {
             throw rethrow(t);
         }
     }
@@ -294,10 +294,10 @@ public static  O call(FailableCallable pCallable)
      * @param  the type the consumer accepts
      * @param  the type of checked exception the consumer may throw
      */
-    public static  void accept(FailableConsumer pConsumer, O pObject) {
+    public static  void accept(final FailableConsumer pConsumer, final O pObject) {
         try {
             pConsumer.accept(pObject);
-        } catch (Throwable t) {
+        } catch (final Throwable t) {
             throw rethrow(t);
         }
     }
@@ -311,10 +311,10 @@ public static  void accept(FailableConsumer pConsu
      * @param  the type of the second argument the consumer accepts
      * @param  the type of checked exception the consumer may throw
      */
-    public static  void accept(FailableBiConsumer pConsumer, O1 pObject1, O2 pObject2) {
+    public static  void accept(final FailableBiConsumer pConsumer, final O1 pObject1, final O2 pObject2) {
         try {
             pConsumer.accept(pObject1, pObject2);
-        } catch (Throwable t) {
+        } catch (final Throwable t) {
             throw rethrow(t);
         }
     }
@@ -328,10 +328,10 @@ public static  void accept(FailableBiConsumer the type of checked exception the function may throw
      * @return the value returned from the function
      */
-    public static  O apply(FailableFunction pFunction, I pInput) {
+    public static  O apply(final FailableFunction pFunction, final I pInput) {
         try {
             return pFunction.apply(pInput);
-        } catch (Throwable t) {
+        } catch (final Throwable t) {
             throw rethrow(t);
         }
     }
@@ -347,10 +347,10 @@ public static  O apply(FailableFunction pFun
      * @param  the type of checked exception the function may throw
      * @return the value returned from the function
      */
-    public static  O apply(FailableBiFunction pFunction, I1 pInput1, I2 pInput2) {
+    public static  O apply(final FailableBiFunction pFunction, final I1 pInput1, final I2 pInput2) {
         try {
             return pFunction.apply(pInput1, pInput2);
-        } catch (Throwable t) {
+        } catch (final Throwable t) {
             throw rethrow(t);
         }
     }
@@ -363,10 +363,10 @@ public static  O apply(FailableBiFunction the type of checked exception the predicate may throw
      * @return the boolean value returned by the predicate
      */
-    public static  boolean test(FailablePredicate pPredicate, O pObject) {
+    public static  boolean test(final FailablePredicate pPredicate, final O pObject) {
         try {
             return pPredicate.test(pObject);
-        } catch (Throwable t) {
+        } catch (final Throwable t) {
             throw rethrow(t);
         }
     }
@@ -381,10 +381,10 @@ public static  boolean test(FailablePredicate pPre
      * @param  the type of checked exception the predicate may throw
      * @return the boolean value returned by the predicate
      */
-    public static  boolean test(FailableBiPredicate pPredicate, O1 pObject1, O2 pObject2) {
+    public static  boolean test(final FailableBiPredicate pPredicate, final O1 pObject1, final O2 pObject2) {
         try {
             return pPredicate.test(pObject1, pObject2);
-        } catch (Throwable t) {
+        } catch (final Throwable t) {
             throw rethrow(t);
         }
     }
@@ -396,10 +396,10 @@ public static  boolean test(FailableBiPredicate The type of checked exception, which the supplier can throw.
      * @return The object, which has been created by the supplier
      */
-    public static  O get(FailableSupplier pSupplier) {
+    public static  O get(final FailableSupplier pSupplier) {
         try {
             return pSupplier.get();
-        } catch (Throwable t) {
+        } catch (final Throwable t) {
             throw rethrow(t);
         }
     }
@@ -416,7 +416,7 @@ public static  O get(FailableSupplier pSupplier) {
      * @param  The streams element type.
      * @return The created {@link FailableStream}.
      */
-    public static  FailableStream stream(Stream pStream) {
+    public static  FailableStream stream(final Stream pStream) {
         return new FailableStream(pStream);
     }
 
@@ -433,7 +433,7 @@ public static  FailableStream stream(Stream pStream) {
      *   streams element type.)
      * @return The created {@link FailableStream}.
      */
-    public static  FailableStream stream(Collection pCollection) {
+    public static  FailableStream stream(final Collection pCollection) {
         return new FailableStream(pCollection.stream());
     }
 
@@ -461,9 +461,9 @@ public static  FailableStream stream(Collection pCollection) {
      * @see #tryWithResources(FailableRunnable, FailableRunnable...)
      */
     @SafeVarargs
-    public static void tryWithResources(FailableRunnable pAction,
-                                            FailableConsumer pErrorHandler,
-                                            FailableRunnable... pResources) {
+    public static void tryWithResources(final FailableRunnable pAction,
+                                            final FailableConsumer pErrorHandler,
+                                            final FailableRunnable... pResources) {
         final FailableConsumer errorHandler;
         if (pErrorHandler == null) {
             errorHandler = (t) -> rethrow(t);
@@ -471,21 +471,21 @@ public static void tryWithResources(FailableRunnable pActio
             errorHandler = pErrorHandler;
         }
         if (pResources != null) {
-            for (FailableRunnable failableRunnable : pResources) {
+            for (final FailableRunnable failableRunnable : pResources) {
                 Objects.requireNonNull(failableRunnable, "runnable");
             }
         }
         Throwable th = null;
         try {
             pAction.run();
-        } catch (Throwable t) {
+        } catch (final Throwable t) {
             th = t;
         }
         if (pResources != null) {
-            for (FailableRunnable runnable : pResources) {
+            for (final FailableRunnable runnable : pResources) {
                 try {
                     runnable.run();
-                } catch (Throwable t) {
+                } catch (final Throwable t) {
                     if (th == null) {
                         th = t;
                     }
@@ -495,7 +495,7 @@ public static void tryWithResources(FailableRunnable pActio
         if (th != null) {
             try {
                 errorHandler.accept(th);
-            } catch (Throwable t) {
+            } catch (final Throwable t) {
                 throw rethrow(t);
             }
         }
@@ -521,8 +521,8 @@ public static void tryWithResources(FailableRunnable pActio
      * @see #tryWithResources(FailableRunnable, FailableConsumer, FailableRunnable...)
      */
     @SafeVarargs
-    public static void tryWithResources(FailableRunnable pAction,
-                                            FailableRunnable... pResources) {
+    public static void tryWithResources(final FailableRunnable pAction,
+                                            final FailableRunnable... pResources) {
         tryWithResources(pAction, null, pResources);
     }
 
@@ -549,7 +549,7 @@ public static void tryWithResources(FailableRunnable pActio
      * @param pThrowable The throwable to rethrow possibly wrapped into an unchecked exception
      * @return Never returns anything, this method never terminates normally.
      */
-    public static RuntimeException rethrow(Throwable pThrowable) {
+    public static RuntimeException rethrow(final Throwable pThrowable) {
         Objects.requireNonNull(pThrowable, "pThrowable");
         if (pThrowable instanceof RuntimeException) {
             throw (RuntimeException) pThrowable;
diff --git a/src/main/java/org/apache/commons/lang3/ObjectUtils.java b/src/main/java/org/apache/commons/lang3/ObjectUtils.java
index b647c1a4a60..b94c2ae74b3 100644
--- a/src/main/java/org/apache/commons/lang3/ObjectUtils.java
+++ b/src/main/java/org/apache/commons/lang3/ObjectUtils.java
@@ -238,7 +238,7 @@ public static  T getFirstNonNull(final Supplier... suppliers) {
         if (suppliers != null) {
             for (final Supplier supplier : suppliers) {
                 if (supplier != null) {
-                    T value = supplier.get();
+                    final T value = supplier.get();
                     if (value != null) {
                         return value;
                     }
diff --git a/src/main/java/org/apache/commons/lang3/Streams.java b/src/main/java/org/apache/commons/lang3/Streams.java
index c097d76f371..f9d590a3672 100644
--- a/src/main/java/org/apache/commons/lang3/Streams.java
+++ b/src/main/java/org/apache/commons/lang3/Streams.java
@@ -65,7 +65,7 @@ public static class FailableStream {
         private Stream stream;
         private boolean terminated;
 
-        public FailableStream(Stream pStream) {
+        public FailableStream(final Stream pStream) {
             stream = pStream;
         }
 
@@ -90,7 +90,7 @@ protected void makeTerminated() {
          * element to determine if it should be included.
          * @return the new stream
          */
-        public FailableStream filter(FailablePredicate pPredicate){
+        public FailableStream filter(final FailablePredicate pPredicate){
             assertNotTerminated();
             stream = stream.filter(Functions.asPredicate(pPredicate));
             return this;
@@ -111,7 +111,7 @@ public FailableStream filter(FailablePredicate pPredicate){
          *
          * @param pAction a non-interfering action to perform on the elements
          */
-        public void forEach(FailableConsumer pAction) {
+        public void forEach(final FailableConsumer pAction) {
             makeTerminated();
             stream().forEach(Functions.asConsumer(pAction));
         }
@@ -164,7 +164,7 @@ public void forEach(FailableConsumer pAction) {
          * @see #collect(Supplier, BiConsumer, BiConsumer)
          * @see Collectors
          */
-        public  R collect(Collector pCollector) {
+        public  R collect(final Collector pCollector) {
             makeTerminated();
             return stream().collect(pCollector);
         }
@@ -214,7 +214,7 @@ public  R collect(Collector pCollector) {
          *   accumulator function
          * @return The result of the reduction
          */
-        public  R collect(Supplier pSupplier, BiConsumer pAccumulator, BiConsumer pCombiner) {
+        public  R collect(final Supplier pSupplier, final BiConsumer pAccumulator, final BiConsumer pCombiner) {
             makeTerminated();
             return stream().collect(pSupplier, pAccumulator, pCombiner);
         }
@@ -262,7 +262,7 @@ public  R collect(Supplier pSupplier, BiConsumer pAccumul
          *                    function for combining two values
          * @return the result of the reduction
          */
-        public O reduce(O pIdentity, BinaryOperator pAccumulator) {
+        public O reduce(final O pIdentity, final BinaryOperator pAccumulator) {
             makeTerminated();
             return stream().reduce(pIdentity, pAccumulator);
         }
@@ -277,7 +277,7 @@ public O reduce(O pIdentity, BinaryOperator pAccumulator) {
          * @param pMapper A non-interfering, stateless function to apply to each element
          * @return the new stream
          */
-        public  FailableStream map(FailableFunction pMapper) {
+        public  FailableStream map(final FailableFunction pMapper) {
             assertNotTerminated();
             return new FailableStream(stream.map(Functions.asFunction(pMapper)));
         }
@@ -309,7 +309,7 @@ public Stream stream() {
          * @return {@code true} If either all elements of the stream match the
          * provided predicate or the stream is empty, otherwise {@code false}.
          */
-        public boolean allMatch(FailablePredicate pPredicate) {
+        public boolean allMatch(final FailablePredicate pPredicate) {
             assertNotTerminated();
             return stream().allMatch(Functions.asPredicate(pPredicate));
         }
@@ -331,7 +331,7 @@ public boolean allMatch(FailablePredicate pPredicate) {
          * @return {@code true} if any elements of the stream match the provided
          * predicate, otherwise {@code false}
          */
-        public boolean anyMatch(FailablePredicate pPredicate) {
+        public boolean anyMatch(final FailablePredicate pPredicate) {
             assertNotTerminated();
             return stream().anyMatch(Functions.asPredicate(pPredicate));
         }
@@ -375,7 +375,7 @@ public boolean anyMatch(FailablePredicate pPredicate) {
      * @return The {@link FailableStream}, which has been created by
      *   converting the stream.
      */
-    public static  FailableStream stream(Stream pStream) {
+    public static  FailableStream stream(final Stream pStream) {
         return new FailableStream(pStream);
     }
 
@@ -417,7 +417,7 @@ public static  FailableStream stream(Stream pStream) {
      * @return The {@link FailableStream}, which has been created by
      *   converting the stream.
      */
-    public static  FailableStream stream(Collection pStream) {
+    public static  FailableStream stream(final Collection pStream) {
         return stream(pStream.stream());
     }
 }
diff --git a/src/main/java/org/apache/commons/lang3/StringUtils.java b/src/main/java/org/apache/commons/lang3/StringUtils.java
index 44fba32dc13..2668731eb18 100644
--- a/src/main/java/org/apache/commons/lang3/StringUtils.java
+++ b/src/main/java/org/apache/commons/lang3/StringUtils.java
@@ -535,7 +535,7 @@ public static String appendIfMissingIgnoreCase(final String str, final CharSeque
      * @since 2.0
      */
     public static String capitalize(final String str) {
-        int strLen = length(str);
+        final int strLen = length(str);
         if (strLen == 0) {
             return str;
         }
@@ -3546,7 +3546,7 @@ public static boolean isAsciiPrintable(final CharSequence cs) {
      * @since 3.0 Changed signature from isBlank(String) to isBlank(CharSequence)
      */
     public static boolean isBlank(final CharSequence cs) {
-        int strLen = length(cs);
+        final int strLen = length(cs);
         if (strLen == 0) {
             return true;
         }
@@ -8355,7 +8355,7 @@ public static String stripEnd(final String str, final String stripChars) {
      * @return the stripped String, {@code null} if null String input
      */
     public static String stripStart(final String str, final String stripChars) {
-        int strLen = length(str);
+        final int strLen = length(str);
         if (strLen == 0) {
             return str;
         }
@@ -9203,7 +9203,7 @@ public static String truncate(final String str, final int offset, final int maxW
      * @since 2.0
      */
     public static String uncapitalize(final String str) {
-        int strLen = length(str);
+        final int strLen = length(str);
         if (strLen == 0) {
             return str;
         }
diff --git a/src/main/java/org/apache/commons/lang3/builder/EqualsBuilder.java b/src/main/java/org/apache/commons/lang3/builder/EqualsBuilder.java
index 30c8a1a19cb..6bd1058427c 100644
--- a/src/main/java/org/apache/commons/lang3/builder/EqualsBuilder.java
+++ b/src/main/java/org/apache/commons/lang3/builder/EqualsBuilder.java
@@ -267,7 +267,7 @@ public EqualsBuilder setTestRecursive(final boolean testRecursive) {
      * @return EqualsBuilder - used to chain calls.
      * @since 3.8
      */
-    public EqualsBuilder setBypassReflectionClasses(List> bypassReflectionClasses) {
+    public EqualsBuilder setBypassReflectionClasses(final List> bypassReflectionClasses) {
         this.bypassReflectionClasses = bypassReflectionClasses;
         return this;
     }
diff --git a/src/main/java/org/apache/commons/lang3/tuple/Pair.java b/src/main/java/org/apache/commons/lang3/tuple/Pair.java
index fda2618e8f6..62889bd8d56 100644
--- a/src/main/java/org/apache/commons/lang3/tuple/Pair.java
+++ b/src/main/java/org/apache/commons/lang3/tuple/Pair.java
@@ -55,7 +55,7 @@ public R getRight() {
         }
 
         @Override
-        public R setValue(R value) {
+        public R setValue(final R value) {
             return null;
         }
 
diff --git a/src/test/java/org/apache/commons/lang3/ArchUtilsTest.java b/src/test/java/org/apache/commons/lang3/ArchUtilsTest.java
index 55724ff9835..0ba4c055955 100644
--- a/src/test/java/org/apache/commons/lang3/ArchUtilsTest.java
+++ b/src/test/java/org/apache/commons/lang3/ArchUtilsTest.java
@@ -98,7 +98,7 @@ public void testArch() {
 
     @Test
     public void testArchLabels() {
-        for (Arch arch : Arch.values()) {
+        for (final Arch arch : Arch.values()) {
             // Only test label presence.
             assertFalse(arch.getLabel().isEmpty());
         }
diff --git a/src/test/java/org/apache/commons/lang3/ArrayUtilsTest.java b/src/test/java/org/apache/commons/lang3/ArrayUtilsTest.java
index 8dfcbcb5a5f..16faecd8c91 100644
--- a/src/test/java/org/apache/commons/lang3/ArrayUtilsTest.java
+++ b/src/test/java/org/apache/commons/lang3/ArrayUtilsTest.java
@@ -3146,8 +3146,8 @@ public void testIndexOfWithStartIndex() {
     @Test
     public void testIndexesOf() {
         final Object[] array = new Object[]{"0", "1", "2", "3", null, "0"};
-        BitSet emptySet = new BitSet();
-        BitSet testSet = new BitSet();
+        final BitSet emptySet = new BitSet();
+        final BitSet testSet = new BitSet();
         assertEquals(emptySet, ArrayUtils.indexesOf((Object[]) null, null));
         assertEquals(emptySet, ArrayUtils.indexesOf(new Object[0], "0"));
         testSet.set(5);
@@ -3168,8 +3168,8 @@ public void testIndexesOf() {
     @Test
     public void testIndexesOfWithStartIndex() {
         final Object[] array = new Object[]{"0", "1", "2", "3", "2", "3", "1", null, "0"};
-        BitSet emptySet = new BitSet();
-        BitSet testSet = new BitSet();
+        final BitSet emptySet = new BitSet();
+        final BitSet testSet = new BitSet();
         assertEquals(emptySet, ArrayUtils.indexesOf(null, null, 2));
         assertEquals(emptySet, ArrayUtils.indexesOf(new Object[0], "0", 0));
         assertEquals(emptySet, ArrayUtils.indexesOf(null, "0", 2));
@@ -3288,8 +3288,8 @@ public void testIndexOfLongWithStartIndex() {
     @Test
     public void testIndexesOfLong() {
         final long[] array = new long[]{0, 1, 2, 3};
-        BitSet emptySet = new BitSet();
-        BitSet testSet = new BitSet();
+        final BitSet emptySet = new BitSet();
+        final BitSet testSet = new BitSet();
         assertEquals(emptySet, ArrayUtils.indexesOf((long[]) null, 0));
         assertEquals(emptySet, ArrayUtils.indexesOf(array, 4));
         testSet.set(0);
@@ -3308,8 +3308,8 @@ public void testIndexesOfLong() {
     @Test
     public void testIndexesOfLongWithStartIndex() {
         final long[] array = new long[]{0, 1, 2, 3, 2, 1, 0, 1};
-        BitSet emptySet = new BitSet();
-        BitSet testSet = new BitSet();
+        final BitSet emptySet = new BitSet();
+        final BitSet testSet = new BitSet();
         assertEquals(emptySet, ArrayUtils.indexesOf((long[]) null, 0, 0));
         assertEquals(emptySet, ArrayUtils.indexesOf(array, 4, 0));
         testSet.set(6);
@@ -3399,8 +3399,8 @@ public void testIndexOfIntWithStartIndex() {
     @Test
     public void textIndexesOfInt() {
         int[] array = null;
-        BitSet emptySet = new BitSet();
-        BitSet testSet = new BitSet();
+        final BitSet emptySet = new BitSet();
+        final BitSet testSet = new BitSet();
         assertEquals(emptySet, ArrayUtils.indexesOf(array, 0));
         array = new int[]{0, 1, 2, 3, 0};
         testSet.set(0);
@@ -3421,8 +3421,8 @@ public void textIndexesOfInt() {
     @Test
     public void testIndexesOfIntWithStartIndex() {
         int[] array = null;
-        BitSet emptySet = new BitSet();
-        BitSet testSet = new BitSet();
+        final BitSet emptySet = new BitSet();
+        final BitSet testSet = new BitSet();
         assertEquals(emptySet, ArrayUtils.indexesOf(array, 0, 2));
         array = new int[]{0, 1, 2, 3, 0};
         testSet.set(4);
@@ -3510,8 +3510,8 @@ public void testIndexOfShortWithStartIndex() {
     @Test
     public void testIndexesOfShort() {
         short[] array = null;
-        BitSet emptySet = new BitSet();
-        BitSet testSet = new BitSet();
+        final BitSet emptySet = new BitSet();
+        final BitSet testSet = new BitSet();
         assertEquals(emptySet, ArrayUtils.indexesOf(array, (short) 0));
         array = new short[]{0, 1, 2, 3, 0};
         testSet.set(0);
@@ -3532,8 +3532,8 @@ public void testIndexesOfShort() {
     @Test
     public void testIndexesOfShortWithStartIndex() {
         short[] array = null;
-        BitSet emptySet = new BitSet();
-        BitSet testSet = new BitSet();
+        final BitSet emptySet = new BitSet();
+        final BitSet testSet = new BitSet();
         assertEquals(emptySet, ArrayUtils.indexesOf(array, (short) 0, 2));
         array = new short[]{0, 1, 2, 3, 0};
         testSet.set(4);
@@ -3621,8 +3621,8 @@ public void testIndexOfCharWithStartIndex() {
     @Test
     public void testIndexesOfChar() {
         char[] array = null;
-        BitSet emptySet = new BitSet();
-        BitSet testSet = new BitSet();
+        final BitSet emptySet = new BitSet();
+        final BitSet testSet = new BitSet();
         assertEquals(emptySet, ArrayUtils.indexesOf(array, 'a'));
         array = new char[]{'a', 'b', 'c', 'd', 'a'};
         testSet.set(0);
@@ -3643,8 +3643,8 @@ public void testIndexesOfChar() {
     @Test
     public void testIndexesOfCharWithStartIndex() {
         char[] array = null;
-        BitSet emptySet = new BitSet();
-        BitSet testSet = new BitSet();
+        final BitSet emptySet = new BitSet();
+        final BitSet testSet = new BitSet();
         assertEquals(emptySet, ArrayUtils.indexesOf(array, 'a', 0));
         array = new char[]{'a', 'b', 'c', 'd', 'a'};
         testSet.set(4);
@@ -3733,8 +3733,8 @@ public void testIndexOfByteWithStartIndex() {
     @Test
     public void testIndexesOfByte() {
         byte[] array = null;
-        BitSet emptySet = new BitSet();
-        BitSet testSet = new BitSet();
+        final BitSet emptySet = new BitSet();
+        final BitSet testSet = new BitSet();
         assertEquals(emptySet, ArrayUtils.indexesOf(array, (byte) 0));
         array = new byte[]{0, 1, 2, 3, 0};
         testSet.set(0);
@@ -3755,8 +3755,8 @@ public void testIndexesOfByte() {
     @Test
     public void testIndexesOfByteWithStartIndex() {
         byte[] array = null;
-        BitSet emptySet = new BitSet();
-        BitSet testSet = new BitSet();
+        final BitSet emptySet = new BitSet();
+        final BitSet testSet = new BitSet();
         assertEquals(emptySet, ArrayUtils.indexesOf(array, (byte) 0, 2));
         array = new byte[]{0, 1, 2, 3, 0};
         testSet.set(4);
@@ -3883,8 +3883,8 @@ public void testIndexOfDoubleWithStartIndexTolerance() {
     @Test
     public void testIndexesOfDouble() {
         double[] array = null;
-        BitSet emptySet = new BitSet();
-        BitSet testSet = new BitSet();
+        final BitSet emptySet = new BitSet();
+        final BitSet testSet = new BitSet();
         assertEquals(emptySet, ArrayUtils.indexesOf(array, 0));
         array = new double[]{0, 1, 2, 3, 0};
         testSet.set(0);
@@ -3906,8 +3906,8 @@ public void testIndexesOfDouble() {
     @Test
     public void testIndexesOfDoubleWithStartIndex() {
         double[] array = null;
-        BitSet emptySet = new BitSet();
-        BitSet testSet = new BitSet();
+        final BitSet emptySet = new BitSet();
+        final BitSet testSet = new BitSet();
         assertEquals(emptySet, ArrayUtils.indexesOf(array, 0, 2));
         array = new double[]{0, 1, 2, 3, 0};
         testSet.set(4);
@@ -3931,8 +3931,8 @@ public void testIndexesOfDoubleWithStartIndex() {
     @Test
     public void testIndexesOfDoubleTolerance() {
         double[] array = null;
-        BitSet emptySet = new BitSet();
-        BitSet testSet = new BitSet();
+        final BitSet emptySet = new BitSet();
+        final BitSet testSet = new BitSet();
         assertEquals(emptySet, ArrayUtils.indexesOf(array, (double) 0, (double) 0));
         array = new double[0];
         assertEquals(emptySet, ArrayUtils.indexesOf(array, (double) 0, (double) 0));
@@ -3952,8 +3952,8 @@ public void testIndexesOfDoubleTolerance() {
     @Test
     public void testIndexesOfDoubleWithStartIndexTolerance() {
         double[] array = null;
-        BitSet emptySet = new BitSet();
-        BitSet testSet = new BitSet();
+        final BitSet emptySet = new BitSet();
+        final BitSet testSet = new BitSet();
         assertEquals(emptySet, ArrayUtils.indexesOf(array, (double) 0, 0, (double) 0));
         array = new double[0];
         assertEquals(emptySet, ArrayUtils.indexesOf(array, (double) 0, 0, (double) 0));
@@ -4102,8 +4102,8 @@ public void testIndexOfFloatWithStartIndex() {
     @Test
     public void testIndexesOfFloat() {
         float[] array = null;
-        BitSet emptySet = new BitSet();
-        BitSet testSet = new BitSet();
+        final BitSet emptySet = new BitSet();
+        final BitSet testSet = new BitSet();
         assertEquals(emptySet, ArrayUtils.indexesOf(array, 0));
         array = new float[]{0, 1, 2, 3, 0};
         testSet.set(0);
@@ -4125,8 +4125,8 @@ public void testIndexesOfFloat() {
     @Test
     public void testIndexesOfFloatWithStartIndex() {
         float[] array = null;
-        BitSet emptySet = new BitSet();
-        BitSet testSet = new BitSet();
+        final BitSet emptySet = new BitSet();
+        final BitSet testSet = new BitSet();
         assertEquals(emptySet, ArrayUtils.indexesOf(array, 0, 2));
         array = new float[]{0, 1, 2, 3, 0};
         testSet.set(4);
@@ -4224,8 +4224,8 @@ public void testIndexOfBooleanWithStartIndex() {
     @Test
     public void testIndexesOfBoolean() {
         boolean[] array = null;
-        BitSet emptySet = new BitSet();
-        BitSet testSet = new BitSet();
+        final BitSet emptySet = new BitSet();
+        final BitSet testSet = new BitSet();
         assertEquals(emptySet, ArrayUtils.indexesOf(array, true));
         array = new boolean[0];
         assertEquals(emptySet, ArrayUtils.indexesOf(array, true));
@@ -4243,8 +4243,8 @@ public void testIndexesOfBoolean() {
     @Test
     public void testIndexesOfBooleanWithStartIndex() {
         boolean[] array = null;
-        BitSet emptySet = new BitSet();
-        BitSet testSet = new BitSet();
+        final BitSet emptySet = new BitSet();
+        final BitSet testSet = new BitSet();
         assertEquals(emptySet, ArrayUtils.indexesOf(array, true, 0));
         array = new boolean[0];
         assertEquals(emptySet, ArrayUtils.indexesOf(array, true, 0));
@@ -5160,7 +5160,7 @@ public void testShuffleDouble() {
     @Test
     public void testIsArrayIndexValid() {
         assertFalse(ArrayUtils.isArrayIndexValid(null, 0));
-        String[] array = new String[1];
+        final String[] array = new String[1];
 
         //too big
         assertFalse(ArrayUtils.isArrayIndexValid(array, 1));
diff --git a/src/test/java/org/apache/commons/lang3/CharRangeTest.java b/src/test/java/org/apache/commons/lang3/CharRangeTest.java
index f8dfe2d523e..18e4e90e776 100644
--- a/src/test/java/org/apache/commons/lang3/CharRangeTest.java
+++ b/src/test/java/org/apache/commons/lang3/CharRangeTest.java
@@ -311,7 +311,7 @@ public void testContains_Charrange() {
     @Test
     public void testContainsNullArg() {
         final CharRange range = CharRange.is('a');
-        IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> range.contains(null));
+        final IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> range.contains(null));
         assertEquals("The Range must not be null", e.getMessage());
     }
 
diff --git a/src/test/java/org/apache/commons/lang3/FunctionsTest.java b/src/test/java/org/apache/commons/lang3/FunctionsTest.java
index ae6bc69d59b..bec8a44b3cb 100644
--- a/src/test/java/org/apache/commons/lang3/FunctionsTest.java
+++ b/src/test/java/org/apache/commons/lang3/FunctionsTest.java
@@ -49,11 +49,11 @@ public static class SomeException extends Exception {
 
         private Throwable t;
 
-        SomeException(String pMsg) {
+        SomeException(final String pMsg) {
             super(pMsg);
         }
 
-        public void setThrowable(Throwable pThrowable) {
+        public void setThrowable(final Throwable pThrowable) {
             t = pThrowable;
         }
 
@@ -66,11 +66,11 @@ public void test() throws Throwable {
     public static class Testable {
         private Throwable t;
 
-        Testable(Throwable pTh) {
+        Testable(final Throwable pTh) {
             t = pTh;
         }
 
-        public void setThrowable(Throwable pThrowable) {
+        public void setThrowable(final Throwable pThrowable) {
             t = pThrowable;
         }
 
@@ -78,7 +78,7 @@ public void test() throws Throwable {
             test(t);
         }
 
-        public void test(Throwable pThrowable) throws Throwable {
+        public void test(final Throwable pThrowable) throws Throwable {
             if (pThrowable != null) {
                 throw pThrowable;
             }
@@ -88,7 +88,7 @@ public Integer testInt() throws Throwable {
             return testInt(t);
         }
 
-        public Integer testInt(Throwable pThrowable) throws Throwable {
+        public Integer testInt(final Throwable pThrowable) throws Throwable {
             if (pThrowable != null) {
                 throw pThrowable;
             }
@@ -117,7 +117,7 @@ static boolean failingBool() throws SomeException {
     public static class CloseableObject {
         private boolean closed;
 
-        public void run(Throwable pTh) throws Throwable {
+        public void run(final Throwable pTh) throws Throwable {
             if (pTh != null) {
                 throw pTh;
             }
@@ -139,7 +139,7 @@ public boolean isClosed() {
     @Test
     void testRunnable() {
         FailureOnOddInvocations.invocation = 0;
-        UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, () ->  Functions.run(FailureOnOddInvocations::new));
+        final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, () ->  Functions.run(FailureOnOddInvocations::new));
         final Throwable cause = e.getCause();
         assertNotNull(cause);
         assertTrue(cause instanceof SomeException);
@@ -152,8 +152,8 @@ void testRunnable() {
     @Test
     void testAsRunnable() {
         FailureOnOddInvocations.invocation = 0;
-        Runnable runnable = Functions.asRunnable(() -> new FailureOnOddInvocations());
-        UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, () ->  runnable.run());
+        final Runnable runnable = Functions.asRunnable(() -> new FailureOnOddInvocations());
+        final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, () ->  runnable.run());
         final Throwable cause = e.getCause();
         assertNotNull(cause);
         assertTrue(cause instanceof SomeException);
@@ -166,7 +166,7 @@ void testAsRunnable() {
     @Test
     void testCallable() {
         FailureOnOddInvocations.invocation = 0;
-        UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, () ->  Functions.run(FailureOnOddInvocations::new));
+        final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, () ->  Functions.run(FailureOnOddInvocations::new));
         final Throwable cause = e.getCause();
         assertNotNull(cause);
         assertTrue(cause instanceof SomeException);
@@ -182,7 +182,7 @@ void testAsCallable() {
             return new FailureOnOddInvocations();
         };
         final Callable callable = Functions.asCallable(failableCallable);
-        UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, () ->  callable.call());
+        final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, () ->  callable.call());
         final Throwable cause = e.getCause();
         assertNotNull(cause);
         assertTrue(cause instanceof SomeException);
@@ -190,7 +190,7 @@ void testAsCallable() {
         final FailureOnOddInvocations instance;
         try {
             instance = callable.call();
-        } catch (Exception ex) {
+        } catch (final Exception ex) {
             throw Functions.rethrow(ex);
         }
         assertNotNull(instance);
@@ -394,7 +394,7 @@ public void testAsBiFunction() {
     @Test
     public void testGetFromSupplier() {
         FailureOnOddInvocations.invocation = 0;
-        UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, () ->  Functions.run(FailureOnOddInvocations::new));
+        final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, () ->  Functions.run(FailureOnOddInvocations::new));
         final Throwable cause = e.getCause();
         assertNotNull(cause);
         assertTrue(cause instanceof SomeException);
@@ -409,7 +409,7 @@ public void testAsPredicate() {
         FailureOnOddInvocations.invocation = 0;
         final Functions.FailablePredicate failablePredicate = (t) -> FailureOnOddInvocations.failingBool();
         final Predicate predicate = Functions.asPredicate(failablePredicate);
-        UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, () -> predicate.test(null));
+        final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, () -> predicate.test(null));
         final Throwable cause = e.getCause();
         assertNotNull(cause);
         assertTrue(cause instanceof SomeException);
@@ -424,7 +424,7 @@ public void testAsBiPredicate() {
         FailureOnOddInvocations.invocation = 0;
         final Functions.FailableBiPredicate failableBiPredicate = (t1, t2) -> FailureOnOddInvocations.failingBool();
         final BiPredicate predicate = Functions.asBiPredicate(failableBiPredicate);
-        UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, () -> predicate.test(null, null));
+        final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, () -> predicate.test(null, null));
         final Throwable cause = e.getCause();
         assertNotNull(cause);
         assertTrue(cause instanceof SomeException);
@@ -438,7 +438,7 @@ public void testAsSupplier() {
         FailureOnOddInvocations.invocation = 0;
         final FailableSupplier failableSupplier = () -> new FailureOnOddInvocations();
         final Supplier supplier = Functions.asSupplier(failableSupplier);
-        UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, () ->  supplier.get());
+        final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, () ->  supplier.get());
         final Throwable cause = e.getCause();
         assertNotNull(cause);
         assertTrue(cause instanceof SomeException);
@@ -464,7 +464,7 @@ public void testTryWithResources() {
         assertTrue(co.isClosed());
         co.reset();
         final IOException ioe = new IOException("Unknown I/O error");
-        UncheckedIOException uioe = assertThrows(UncheckedIOException.class, () ->  Functions.tryWithResources(() -> consumer.accept(ioe), co::close));
+        final UncheckedIOException uioe = assertThrows(UncheckedIOException.class, () ->  Functions.tryWithResources(() -> consumer.accept(ioe), co::close));
         final IOException cause = uioe.getCause();
         assertSame(ioe, cause);
 
diff --git a/src/test/java/org/apache/commons/lang3/LocaleUtilsTest.java b/src/test/java/org/apache/commons/lang3/LocaleUtilsTest.java
index e5c14077332..558b5f9cf33 100644
--- a/src/test/java/org/apache/commons/lang3/LocaleUtilsTest.java
+++ b/src/test/java/org/apache/commons/lang3/LocaleUtilsTest.java
@@ -524,7 +524,7 @@ public void testLang865() {
 
     @ParameterizedTest
     @MethodSource("java.util.Locale#getAvailableLocales")
-    public void testParseAllLocales(Locale l) {
+    public void testParseAllLocales(final Locale l) {
         // Check if it's possible to recreate the Locale using just the standard constructor
         final Locale locale = new Locale(l.getLanguage(), l.getCountry(), l.getVariant());
         if (l.equals(locale)) { // it is possible for LocaleUtils.toLocale to handle these Locales
diff --git a/src/test/java/org/apache/commons/lang3/ObjectUtilsTest.java b/src/test/java/org/apache/commons/lang3/ObjectUtilsTest.java
index 7fcdc4b71d8..373f40ca76c 100644
--- a/src/test/java/org/apache/commons/lang3/ObjectUtilsTest.java
+++ b/src/test/java/org/apache/commons/lang3/ObjectUtilsTest.java
@@ -121,8 +121,8 @@ public void testDefaultIfNull() {
         assertSame(o, ObjectUtils.getIfNull(o, () -> dflt), "dflt was returned when o was not null");
         assertSame(o, ObjectUtils.getIfNull(FOO, () -> dflt), "dflt was returned when o was not null");
         assertSame(o, ObjectUtils.getIfNull("foo", () -> dflt), "dflt was returned when o was not null");
-        MutableInt callsCounter = new MutableInt(0);
-        Supplier countingDefaultSupplier = () -> {
+        final MutableInt callsCounter = new MutableInt(0);
+        final Supplier countingDefaultSupplier = () -> {
             callsCounter.increment();
             return dflt;
         };
@@ -539,7 +539,7 @@ public void testCloneOfNotCloneable() {
     @Test
     public void testCloneOfUncloneable() {
         final UncloneableString string = new UncloneableString("apache");
-        CloneFailedException e = assertThrows(CloneFailedException.class, () -> ObjectUtils.clone(string));
+        final CloneFailedException e = assertThrows(CloneFailedException.class, () -> ObjectUtils.clone(string));
         assertEquals(NoSuchMethodException.class, e.getCause().getClass());
     }
 
@@ -585,7 +585,7 @@ public void testPossibleCloneOfNotCloneable() {
     @Test
     public void testPossibleCloneOfUncloneable() {
         final UncloneableString string = new UncloneableString("apache");
-        CloneFailedException e = assertThrows(CloneFailedException.class, () -> ObjectUtils.cloneIfPossible(string));
+        final CloneFailedException e = assertThrows(CloneFailedException.class, () -> ObjectUtils.cloneIfPossible(string));
         assertEquals(NoSuchMethodException.class, e.getCause().getClass());
     }
 
diff --git a/src/test/java/org/apache/commons/lang3/RandomStringUtilsTest.java b/src/test/java/org/apache/commons/lang3/RandomStringUtilsTest.java
index d18e3c887f6..aee483449a2 100644
--- a/src/test/java/org/apache/commons/lang3/RandomStringUtilsTest.java
+++ b/src/test/java/org/apache/commons/lang3/RandomStringUtilsTest.java
@@ -158,7 +158,7 @@ public void testLANG805() {
 
     @Test
     public void testLANG807() {
-        IllegalArgumentException ex =
+        final IllegalArgumentException ex =
                 assertThrows(IllegalArgumentException.class, () -> RandomStringUtils.random(3, 5, 5, false, false));
         final String msg = ex.getMessage();
         assertTrue(msg.contains("start"), "Message (" + msg + ") must contain 'start'");
diff --git a/src/test/java/org/apache/commons/lang3/SerializationUtilsTest.java b/src/test/java/org/apache/commons/lang3/SerializationUtilsTest.java
index d0dcaa33adf..698962f260d 100644
--- a/src/test/java/org/apache/commons/lang3/SerializationUtilsTest.java
+++ b/src/test/java/org/apache/commons/lang3/SerializationUtilsTest.java
@@ -159,7 +159,7 @@ public void write(final int arg0) throws IOException {
                 throw new IOException(SERIALIZE_IO_EXCEPTION_MESSAGE);
             }
         };
-        SerializationException e =
+        final SerializationException e =
                 assertThrows(SerializationException.class, () -> SerializationUtils.serialize(iMap, streamTest));
         assertEquals("java.io.IOException: " + SERIALIZE_IO_EXCEPTION_MESSAGE, e.getMessage());
     }
@@ -232,7 +232,7 @@ public void testDeserializeStreamClassNotFound() throws Exception {
         oos.close();
 
         final ByteArrayInputStream inTest = new ByteArrayInputStream(streamReal.toByteArray());
-        SerializationException se =
+        final SerializationException se =
                 assertThrows(SerializationException.class, () -> SerializationUtils.deserialize(inTest));
         assertEquals("java.lang.ClassNotFoundException: " + CLASS_NOT_FOUND_MESSAGE, se.getMessage());
     }
diff --git a/src/test/java/org/apache/commons/lang3/StreamsTest.java b/src/test/java/org/apache/commons/lang3/StreamsTest.java
index 3ce713d9321..6769c9b3cf7 100644
--- a/src/test/java/org/apache/commons/lang3/StreamsTest.java
+++ b/src/test/java/org/apache/commons/lang3/StreamsTest.java
@@ -48,7 +48,7 @@ void testSimpleStreamMapFailing() {
         try {
             Functions.stream(input).map((s) -> Integer.valueOf(s)).collect(Collectors.toList());
             fail("Expected Exception");
-        } catch (NumberFormatException nfe) {
+        } catch (final NumberFormatException nfe) {
             assertEquals("For input string: \"4 \"", nfe.getMessage());
         }
     }
@@ -64,7 +64,7 @@ void testSimpleStreamForEach() {
         }
     }
 
-    protected  FailableConsumer asIntConsumer(T pThrowable) {
+    protected  FailableConsumer asIntConsumer(final T pThrowable) {
         return (s) -> {
             final Integer i = Integer.valueOf(s);
             if (i.intValue() == 4) {
@@ -81,7 +81,7 @@ void testSimpleStreamForEachFailing() {
         try {
             Functions.stream(input).forEach(asIntConsumer(ise));
             fail("Expected Exception");
-        } catch (IllegalArgumentException e) {
+        } catch (final IllegalArgumentException e) {
             assertSame(ise, e);
         }
         output.clear();
@@ -89,7 +89,7 @@ void testSimpleStreamForEachFailing() {
         try {
             Functions.stream(input).forEach(asIntConsumer(oome));
             fail("Expected Exception");
-        } catch (Throwable t) {
+        } catch (final Throwable t) {
             assertSame(oome, t);
         }
         output.clear();
@@ -97,7 +97,7 @@ void testSimpleStreamForEachFailing() {
         try {
             Functions.stream(input).forEach(asIntConsumer(se));
             fail("Expected Exception");
-        } catch (UndeclaredThrowableException ute) {
+        } catch (final UndeclaredThrowableException ute) {
             assertSame(se, ute.getCause());
         }
     }
@@ -121,7 +121,7 @@ private void assertEvenNumbers(final List output) {
         }
     }
 
-    protected  FailablePredicate asIntPredicate(T pThrowable) {
+    protected  FailablePredicate asIntPredicate(final T pThrowable) {
         return (i) -> {
             if (i.intValue() == 5) {
                 if (pThrowable != null) {
@@ -149,7 +149,7 @@ void testSimpleStreamFilterFailing() {
                     .filter(asIntPredicate(iae))
                     .collect(Collectors.toList());
             fail("Expected Exception");
-        } catch (IllegalArgumentException e) {
+        } catch (final IllegalArgumentException e) {
             assertSame(iae, e);
         }
 
@@ -161,7 +161,7 @@ void testSimpleStreamFilterFailing() {
                     .filter(asIntPredicate(oome))
                     .collect(Collectors.toList());
             fail("Expected Exception");
-        } catch (Throwable t) {
+        } catch (final Throwable t) {
             assertSame(oome, t);
         }
 
@@ -173,7 +173,7 @@ void testSimpleStreamFilterFailing() {
                     .filter(asIntPredicate(se))
                     .collect(Collectors.toList());
             fail("Expected Exception");
-        } catch (UndeclaredThrowableException t) {
+        } catch (final UndeclaredThrowableException t) {
             assertSame(se, t.getCause());
         }
     }
diff --git a/src/test/java/org/apache/commons/lang3/StringUtilsTest.java b/src/test/java/org/apache/commons/lang3/StringUtilsTest.java
index 7f034c27c0c..e7eb5f075fc 100644
--- a/src/test/java/org/apache/commons/lang3/StringUtilsTest.java
+++ b/src/test/java/org/apache/commons/lang3/StringUtilsTest.java
@@ -239,7 +239,7 @@ private void innerTestSplitPreserveAllTokens(final char separator, final String
     //Fixed LANG-1463
     @Test
     public void testAbbreviateMarkerWithEmptyString() {
-        String greaterThanMaxTest = "much too long text";
+        final String greaterThanMaxTest = "much too long text";
         assertEquals("much too long", StringUtils.abbreviate(greaterThanMaxTest, "", 13));
     }
 
@@ -684,8 +684,8 @@ public void testGetIfBlank_StringStringSupplier() {
         final String s = StringUtils.getIfBlank("abc", () -> "NULL");
         assertEquals("abc", s);
         //Checking that default value supplied only on demand
-        MutableInt numberOfCalls = new MutableInt(0);
-        Supplier countingDefaultSupplier = () -> {
+        final MutableInt numberOfCalls = new MutableInt(0);
+        final Supplier countingDefaultSupplier = () -> {
             numberOfCalls.increment();
             return "NULL";
         };
@@ -752,8 +752,8 @@ public void testGetIfEmpty_StringStringSupplier() {
         final String s = StringUtils.getIfEmpty("abc", () -> "NULL");
         assertEquals("abc", s);
         //Checking that default value supplied only on demand
-        MutableInt numberOfCalls = new MutableInt(0);
-        Supplier countingDefaultSupplier = () -> {
+        final MutableInt numberOfCalls = new MutableInt(0);
+        final Supplier countingDefaultSupplier = () -> {
             numberOfCalls.increment();
             return "NULL";
         };
@@ -3273,7 +3273,7 @@ public void testToRootLowerCase() {
         assertEquals("title", "TITLE".toLowerCase(Locale.ROOT));
         assertEquals("title", StringUtils.toRootLowerCase("TITLE"));
         // Make sure we are not using the default Locale:
-        Locale defaultLocales = Locale.getDefault();
+        final Locale defaultLocales = Locale.getDefault();
         try {
             Locale.setDefault(TURKISH);
             assertEquals("title", StringUtils.toRootLowerCase("TITLE"));
@@ -3293,7 +3293,7 @@ public void testToRootUpperCase() {
         assertEquals("TITLE", "title".toUpperCase(Locale.ROOT));
         assertEquals("TITLE", StringUtils.toRootUpperCase("title"));
         // Make sure we are not using the default Locale:
-        Locale defaultLocales = Locale.getDefault();
+        final Locale defaultLocales = Locale.getDefault();
         try {
             Locale.setDefault(TURKISH);
             assertEquals("TITLE", StringUtils.toRootUpperCase("title"));
diff --git a/src/test/java/org/apache/commons/lang3/ValidateTest.java b/src/test/java/org/apache/commons/lang3/ValidateTest.java
index cf1a907f36d..0aa6edfdbbf 100644
--- a/src/test/java/org/apache/commons/lang3/ValidateTest.java
+++ b/src/test/java/org/apache/commons/lang3/ValidateTest.java
@@ -712,7 +712,7 @@ void shouldNotThrowExceptionForNonEmptyCollection() {
 
                 @Test
                 void shouldReturnSameInstance() {
-                    Set col = Collections.singleton("a");
+                    final Set col = Collections.singleton("a");
                     final Set result = Validate.noNullElements(col);
 
                     assertSame(col, result);
@@ -747,7 +747,7 @@ void shouldNotThrowExceptionForNonEmptyCollection() {
 
                 @Test
                 void shouldReturnSameInstance() {
-                    Set col = Collections.singleton("a");
+                    final Set col = Collections.singleton("a");
                     final Set result = Validate.noNullElements(col, "MSG");
 
                     assertSame(col, result);
diff --git a/src/test/java/org/apache/commons/lang3/builder/EqualsBuilderTest.java b/src/test/java/org/apache/commons/lang3/builder/EqualsBuilderTest.java
index 061d2da0ff4..d487bac04f7 100644
--- a/src/test/java/org/apache/commons/lang3/builder/EqualsBuilderTest.java
+++ b/src/test/java/org/apache/commons/lang3/builder/EqualsBuilderTest.java
@@ -447,7 +447,7 @@ public void testObjectRecursiveGenericInteger() {
     @Test
     public void testObjectRecursiveGenericString() {
         // Note: Do not use literals, because string literals are always mapped by same object (internal() of String))!
-        String s1_a = String.valueOf(1);
+        final String s1_a = String.valueOf(1);
         final TestRecursiveGenericObject o1_a = new TestRecursiveGenericObject<>(s1_a);
         final TestRecursiveGenericObject o1_b = new TestRecursiveGenericObject<>(String.valueOf(1));
         final TestRecursiveGenericObject o2 = new TestRecursiveGenericObject<>(String.valueOf(2));
diff --git a/src/test/java/org/apache/commons/lang3/builder/ReflectionToStringBuilderSummaryTest.java b/src/test/java/org/apache/commons/lang3/builder/ReflectionToStringBuilderSummaryTest.java
index 46e2283c959..dfd549c2499 100644
--- a/src/test/java/org/apache/commons/lang3/builder/ReflectionToStringBuilderSummaryTest.java
+++ b/src/test/java/org/apache/commons/lang3/builder/ReflectionToStringBuilderSummaryTest.java
@@ -23,10 +23,10 @@
 public class ReflectionToStringBuilderSummaryTest {
 
     @SuppressWarnings("unused")
-    private String stringField = "string";
+    private final String stringField = "string";
 
     @ToStringSummary
-    private String summaryString = "summary";
+    private final String summaryString = "summary";
 
     @Test
     public void testSummary() {
diff --git a/src/test/java/org/apache/commons/lang3/concurrent/BackgroundInitializerTest.java b/src/test/java/org/apache/commons/lang3/concurrent/BackgroundInitializerTest.java
index cbb726de057..ecb4a160f99 100644
--- a/src/test/java/org/apache/commons/lang3/concurrent/BackgroundInitializerTest.java
+++ b/src/test/java/org/apache/commons/lang3/concurrent/BackgroundInitializerTest.java
@@ -179,7 +179,7 @@ public void testGetRuntimeException() {
         final RuntimeException rex = new RuntimeException();
         init.ex = rex;
         init.start();
-        Exception ex = assertThrows(Exception.class, init::get);
+        final Exception ex = assertThrows(Exception.class, init::get);
         assertEquals(rex, ex, "Runtime exception not thrown");
     }
 
@@ -193,7 +193,7 @@ public void testGetCheckedException() {
         final Exception ex = new Exception();
         init.ex = ex;
         init.start();
-        ConcurrentException cex = assertThrows(ConcurrentException.class, init::get);
+        final ConcurrentException cex = assertThrows(ConcurrentException.class, init::get);
         assertEquals(ex, cex.getCause(), "Exception not thrown");
     }
 
diff --git a/src/test/java/org/apache/commons/lang3/concurrent/ConcurrentUtilsTest.java b/src/test/java/org/apache/commons/lang3/concurrent/ConcurrentUtilsTest.java
index 8f3159bed5e..075c6f80703 100644
--- a/src/test/java/org/apache/commons/lang3/concurrent/ConcurrentUtilsTest.java
+++ b/src/test/java/org/apache/commons/lang3/concurrent/ConcurrentUtilsTest.java
@@ -107,7 +107,7 @@ public void testExtractCauseNullCause() {
     @Test
     public void testExtractCauseError() {
         final Error err = new AssertionError("Test");
-        AssertionError e =
+        final AssertionError e =
                 assertThrows(AssertionError.class, () -> ConcurrentUtils.extractCause(new ExecutionException(err)));
         assertEquals(err, e, "Wrong error");
     }
@@ -154,7 +154,7 @@ public void testExtractCauseUncheckedNullCause() {
     @Test
     public void testExtractCauseUncheckedError() {
         final Error err = new AssertionError("Test");
-        Error e = assertThrows(Error.class, () -> ConcurrentUtils.extractCauseUnchecked(new ExecutionException(err)));
+        final Error e = assertThrows(Error.class, () -> ConcurrentUtils.extractCauseUnchecked(new ExecutionException(err)));
         assertEquals(err, e, "Wrong error");
     }
 
@@ -164,7 +164,7 @@ public void testExtractCauseUncheckedError() {
     @Test
     public void testExtractCauseUncheckedUncheckedException() {
         final RuntimeException rex = new RuntimeException("Test");
-        RuntimeException r =
+        final RuntimeException r =
                 assertThrows(RuntimeException.class, () -> ConcurrentUtils.extractCauseUnchecked(new ExecutionException(rex)));
         assertEquals(rex, r, "Wrong exception");
     }
@@ -186,7 +186,7 @@ public void testExtractCauseUncheckedChecked() {
     @Test
     public void testHandleCauseError() {
         final Error err = new AssertionError("Test");
-        Error e = assertThrows(Error.class, () -> ConcurrentUtils.handleCause(new ExecutionException(err)));
+        final Error e = assertThrows(Error.class, () -> ConcurrentUtils.handleCause(new ExecutionException(err)));
         assertEquals(err, e, "Wrong error");
     }
 
@@ -196,7 +196,7 @@ public void testHandleCauseError() {
     @Test
     public void testHandleCauseUncheckedException() {
         final RuntimeException rex = new RuntimeException("Test");
-        RuntimeException r =
+        final RuntimeException r =
                 assertThrows(RuntimeException.class, () -> ConcurrentUtils.handleCause(new ExecutionException(rex)));
         assertEquals(rex, r, "Wrong exception");
     }
@@ -207,7 +207,7 @@ public void testHandleCauseUncheckedException() {
     @Test
     public void testHandleCauseChecked() {
         final Exception ex = new Exception("Test");
-        ConcurrentException cex =
+        final ConcurrentException cex =
                 assertThrows(ConcurrentException.class, () -> ConcurrentUtils.handleCause(new ExecutionException(ex)));
         assertEquals(ex, cex.getCause(), "Wrong cause");
     }
@@ -231,7 +231,7 @@ public void testHandleCauseNull() throws ConcurrentException {
     @Test
     public void testHandleCauseUncheckedError() {
         final Error err = new AssertionError("Test");
-        Error e = assertThrows(Error.class, () -> ConcurrentUtils.handleCauseUnchecked(new ExecutionException(err)));
+        final Error e = assertThrows(Error.class, () -> ConcurrentUtils.handleCauseUnchecked(new ExecutionException(err)));
         assertEquals(err, e, "Wrong error");
     }
 
@@ -241,7 +241,7 @@ public void testHandleCauseUncheckedError() {
     @Test
     public void testHandleCauseUncheckedUncheckedException() {
         final RuntimeException rex = new RuntimeException("Test");
-        RuntimeException r =
+        final RuntimeException r =
                 assertThrows(RuntimeException.class, () -> ConcurrentUtils.handleCauseUnchecked(new ExecutionException(rex)));
         assertEquals(rex, r, "Wrong exception");
     }
@@ -252,7 +252,7 @@ public void testHandleCauseUncheckedUncheckedException() {
     @Test
     public void testHandleCauseUncheckedChecked() {
         final Exception ex = new Exception("Test");
-        ConcurrentRuntimeException crex =
+        final ConcurrentRuntimeException crex =
                 assertThrows(ConcurrentRuntimeException.class, () -> ConcurrentUtils.handleCauseUnchecked(new ExecutionException(ex)));
         assertEquals(ex, crex.getCause(), "Wrong cause");
     }
@@ -346,7 +346,7 @@ public void testInitializeUncheckedEx() throws ConcurrentException {
         final Exception cause = new Exception();
         EasyMock.expect(init.get()).andThrow(new ConcurrentException(cause));
         EasyMock.replay(init);
-        ConcurrentRuntimeException crex =
+        final ConcurrentRuntimeException crex =
                 assertThrows(ConcurrentRuntimeException.class, () -> ConcurrentUtils.initializeUnchecked(init));
         assertSame(cause, crex.getCause(), "Wrong cause");
         EasyMock.verify(init);
@@ -524,7 +524,7 @@ public void testCreateIfAbsentUncheckedException()
         final Exception ex = new Exception();
         EasyMock.expect(init.get()).andThrow(new ConcurrentException(ex));
         EasyMock.replay(init);
-        ConcurrentRuntimeException crex =
+        final ConcurrentRuntimeException crex =
                 assertThrows(
                         ConcurrentRuntimeException.class,
                         () -> ConcurrentUtils.createIfAbsentUnchecked(new ConcurrentHashMap<>(), "test", init));
diff --git a/src/test/java/org/apache/commons/lang3/concurrent/EventCountCircuitBreakerTest.java b/src/test/java/org/apache/commons/lang3/concurrent/EventCountCircuitBreakerTest.java
index 2819006b2aa..9e486952c2b 100644
--- a/src/test/java/org/apache/commons/lang3/concurrent/EventCountCircuitBreakerTest.java
+++ b/src/test/java/org/apache/commons/lang3/concurrent/EventCountCircuitBreakerTest.java
@@ -161,8 +161,8 @@ public void testOpeningWhenThresholdReachedThroughBatch() {
         final long timeIncrement = NANO_FACTOR / OPENING_THRESHOLD - 1;
         final EventCountCircuitBreakerTestImpl breaker = new EventCountCircuitBreakerTestImpl(OPENING_THRESHOLD, 1,
             TimeUnit.SECONDS, CLOSING_THRESHOLD, 1, TimeUnit.SECONDS);
-        long startTime = timeIncrement * (OPENING_THRESHOLD + 1);
-        boolean open = !breaker.at(startTime).incrementAndCheckState(OPENING_THRESHOLD + 1);
+        final long startTime = timeIncrement * (OPENING_THRESHOLD + 1);
+        final boolean open = !breaker.at(startTime).incrementAndCheckState(OPENING_THRESHOLD + 1);
         assertTrue(open, "Not open");
         assertFalse(breaker.isClosed(), "Closed");
     }
diff --git a/src/test/java/org/apache/commons/lang3/concurrent/MultiBackgroundInitializerTest.java b/src/test/java/org/apache/commons/lang3/concurrent/MultiBackgroundInitializerTest.java
index 068b5b6dbdc..973f72b6c8b 100644
--- a/src/test/java/org/apache/commons/lang3/concurrent/MultiBackgroundInitializerTest.java
+++ b/src/test/java/org/apache/commons/lang3/concurrent/MultiBackgroundInitializerTest.java
@@ -273,7 +273,7 @@ public void testInitializeRuntimeEx() {
         child.ex = new RuntimeException();
         initializer.addInitializer(CHILD_INIT, child);
         initializer.start();
-        Exception ex = assertThrows(Exception.class, initializer::get);
+        final Exception ex = assertThrows(Exception.class, initializer::get);
         assertEquals(child.ex, ex, "Wrong exception");
     }
 
diff --git a/src/test/java/org/apache/commons/lang3/event/EventUtilsTest.java b/src/test/java/org/apache/commons/lang3/event/EventUtilsTest.java
index 27797b2a5a6..1736e1380aa 100644
--- a/src/test/java/org/apache/commons/lang3/event/EventUtilsTest.java
+++ b/src/test/java/org/apache/commons/lang3/event/EventUtilsTest.java
@@ -69,7 +69,7 @@ public void testAddEventListenerWithNoAddMethod() {
         final PropertyChangeSource src = new PropertyChangeSource();
         final EventCountingInvociationHandler handler = new EventCountingInvociationHandler();
         final ObjectChangeListener listener = handler.createListener(ObjectChangeListener.class);
-        IllegalArgumentException e =
+        final IllegalArgumentException e =
                 assertThrows(IllegalArgumentException.class, () -> EventUtils.addEventListener(src, ObjectChangeListener.class, listener));
         assertEquals("Class " + src.getClass().getName() + " does not have a public add" + ObjectChangeListener.class.getSimpleName() + " method which takes a parameter of type " + ObjectChangeListener.class.getName() + ".",
                 e.getMessage());
@@ -90,7 +90,7 @@ public void testAddEventListenerWithPrivateAddMethod() {
         final PropertyChangeSource src = new PropertyChangeSource();
         final EventCountingInvociationHandler handler = new EventCountingInvociationHandler();
         final VetoableChangeListener listener = handler.createListener(VetoableChangeListener.class);
-        IllegalArgumentException e =
+        final IllegalArgumentException e =
                 assertThrows(IllegalArgumentException.class, () -> EventUtils.addEventListener(src, VetoableChangeListener.class, listener));
         assertEquals("Class " + src.getClass().getName() + " does not have a public add" + VetoableChangeListener.class.getSimpleName() + " method which takes a parameter of type " + VetoableChangeListener.class.getName() + ".",
                 e.getMessage());
diff --git a/src/test/java/org/apache/commons/lang3/exception/ExceptionUtilsTest.java b/src/test/java/org/apache/commons/lang3/exception/ExceptionUtilsTest.java
index 5eafdf30807..fb7a9fbf317 100644
--- a/src/test/java/org/apache/commons/lang3/exception/ExceptionUtilsTest.java
+++ b/src/test/java/org/apache/commons/lang3/exception/ExceptionUtilsTest.java
@@ -566,7 +566,7 @@ public void testRemoveCommonFrames_ListList() {
     @Test
     public void testThrow() {
         final Exception expected = new InterruptedException();
-        Exception actual = assertThrows(Exception.class, () -> ExceptionUtils.rethrow(expected));
+        final Exception actual = assertThrows(Exception.class, () -> ExceptionUtils.rethrow(expected));
         assertSame(expected, actual);
     }
 
@@ -678,25 +678,25 @@ public void testThrowableOfType_ThrowableClassInt() {
 
     @Test
     public void testWrapAndUnwrapCheckedException() {
-        Throwable t = assertThrows(Throwable.class, () -> ExceptionUtils.wrapAndThrow(new IOException()));
+        final Throwable t = assertThrows(Throwable.class, () -> ExceptionUtils.wrapAndThrow(new IOException()));
         assertTrue(ExceptionUtils.hasCause(t, IOException.class));
     }
 
     @Test
     public void testWrapAndUnwrapError() {
-        Throwable t = assertThrows(Throwable.class, () -> ExceptionUtils.wrapAndThrow(new OutOfMemoryError()));
+        final Throwable t = assertThrows(Throwable.class, () -> ExceptionUtils.wrapAndThrow(new OutOfMemoryError()));
         assertTrue(ExceptionUtils.hasCause(t, Error.class));
     }
 
     @Test
     public void testWrapAndUnwrapRuntimeException() {
-        Throwable t = assertThrows(Throwable.class, () -> ExceptionUtils.wrapAndThrow(new IllegalArgumentException()));
+        final Throwable t = assertThrows(Throwable.class, () -> ExceptionUtils.wrapAndThrow(new IllegalArgumentException()));
         assertTrue(ExceptionUtils.hasCause(t, RuntimeException.class));
     }
 
     @Test
     public void testWrapAndUnwrapThrowable() {
-        Throwable t = assertThrows(Throwable.class, () -> ExceptionUtils.wrapAndThrow(new TestThrowable()));
+        final Throwable t = assertThrows(Throwable.class, () -> ExceptionUtils.wrapAndThrow(new TestThrowable()));
         assertTrue(ExceptionUtils.hasCause(t, TestThrowable.class));
     }
 }
diff --git a/src/test/java/org/apache/commons/lang3/reflect/FieldUtilsTest.java b/src/test/java/org/apache/commons/lang3/reflect/FieldUtilsTest.java
index 291e70a20be..9db1f807056 100644
--- a/src/test/java/org/apache/commons/lang3/reflect/FieldUtilsTest.java
+++ b/src/test/java/org/apache/commons/lang3/reflect/FieldUtilsTest.java
@@ -173,7 +173,7 @@ public void testGetAllFields() {
         final Field[] allFields = FieldUtils.getAllFields(PublicChild.class);
         // Under Jacoco,0.8.1 and Java 10, the field count is 7.
         int expected = 5;
-        for (Field field : allFields) {
+        for (final Field field : allFields) {
             if (field.getName().equals(JACOCO_DATA_FIELD_NAME)) {
                 expected++;
             }
@@ -193,7 +193,7 @@ public void testGetAllFieldsList() {
         final List allFields = FieldUtils.getAllFieldsList(PublicChild.class);
         // Under Jacoco,0.8.1 and Java 10, the field count is 7.
         int expected = 5;
-        for (Field field : allFields) {
+        for (final Field field : allFields) {
             if (field.getName().equals(JACOCO_DATA_FIELD_NAME)) {
                 expected++;
             }
@@ -672,7 +672,7 @@ public void testReadDeclaredNamedFieldForceAccess() throws Exception {
 
     @Test
     public void testWriteStaticField() throws Exception {
-        Field field = StaticContainer.class.getDeclaredField("mutablePublic");
+        final Field field = StaticContainer.class.getDeclaredField("mutablePublic");
         FieldUtils.writeStaticField(field, "new");
         assertEquals("new", StaticContainer.mutablePublic);
         assertThrows(
@@ -830,7 +830,7 @@ public void testWriteDeclaredNamedStaticFieldForceAccess() throws Exception {
 
     @Test
     public void testWriteField() throws Exception {
-        Field field = parentClass.getDeclaredField("s");
+        final Field field = parentClass.getDeclaredField("s");
         FieldUtils.writeField(field, publicChild, "S");
         assertEquals("S", field.get(publicChild));
         assertThrows(
@@ -1049,10 +1049,10 @@ public void testRemoveFinalModifierAccessNotNeeded() throws Exception {
      * @param forceAccess {@link Boolean} to be curried into
      *              {@link FieldUtils#removeFinalModifier(Field, boolean)}.
      */
-    private void callRemoveFinalModifierCheckForException(Field field, Boolean forceAccess) {
+    private void callRemoveFinalModifierCheckForException(final Field field, final Boolean forceAccess) {
         try {
             FieldUtils.removeFinalModifier(field, forceAccess);
-        } catch (UnsupportedOperationException exception) {
+        } catch (final UnsupportedOperationException exception) {
             if (SystemUtils.isJavaVersionAtLeast(JavaVersion.JAVA_12)) {
                 assertTrue(exception.getCause() instanceof NoSuchFieldException);
             } else {
diff --git a/src/test/java/org/apache/commons/lang3/text/StrBuilderTest.java b/src/test/java/org/apache/commons/lang3/text/StrBuilderTest.java
index 735b1323422..cd13cdaadfa 100644
--- a/src/test/java/org/apache/commons/lang3/text/StrBuilderTest.java
+++ b/src/test/java/org/apache/commons/lang3/text/StrBuilderTest.java
@@ -521,7 +521,7 @@ public void testGetCharsIntIntCharArrayInt( ) {
         final StrBuilder sb = new StrBuilder();
 
         sb.append("junit");
-        char[] a = new char[5];
+        final char[] a = new char[5];
         sb.getChars(0, 5, a, 0);
         assertArrayEquals(new char[]{'j', 'u', 'n', 'i', 't'}, a);
 
@@ -538,7 +538,7 @@ public void testGetCharsIntIntCharArrayInt( ) {
     //-----------------------------------------------------------------------
     @Test
     public void testDeleteIntInt() {
-        StrBuilder sb = new StrBuilder("abc");
+        final StrBuilder sb = new StrBuilder("abc");
         sb.delete(0, 1);
         assertEquals("bc", sb.toString());
         sb.delete(1, 2);
@@ -679,7 +679,7 @@ public void testDeleteFirst_StrMatcher() {
     // -----------------------------------------------------------------------
     @Test
     public void testReplace_int_int_String() {
-        StrBuilder sb = new StrBuilder("abc");
+        final StrBuilder sb = new StrBuilder("abc");
         sb.replace(0, 1, "d");
         assertEquals("dbc", sb.toString());
         sb.replace(0, 1, "aaa");
@@ -693,12 +693,12 @@ public void testReplace_int_int_String() {
         sb.replace(0, 1000, "text");
         assertEquals("text", sb.toString());
 
-        StrBuilder sb1 = new StrBuilder("atext");
+        final StrBuilder sb1 = new StrBuilder("atext");
         sb1.replace(1, 1, "ny");
         assertEquals("anytext", sb1.toString());
         assertThrows(IndexOutOfBoundsException.class, () -> sb1.replace(2, 1, "anything"));
 
-        StrBuilder sb2 = new StrBuilder();
+        final StrBuilder sb2 = new StrBuilder();
         assertThrows(IndexOutOfBoundsException.class, () -> sb2.replace(1, 2, "anything"));
         assertThrows(IndexOutOfBoundsException.class, () -> sb2.replace(-1, 1, "anything"));
     }
@@ -960,13 +960,13 @@ public void testReplace_StrMatcher_String_int_int_int_VaryStartIndex() {
         sb.replace(StrMatcher.stringMatcher("aa"), "-", 10, sb.length(), -1);
         assertEquals("aaxaaaayaa", sb.toString());
 
-        StrBuilder sb1 = new StrBuilder("aaxaaaayaa");
+        final StrBuilder sb1 = new StrBuilder("aaxaaaayaa");
         assertThrows(
                 IndexOutOfBoundsException.class,
                 () -> sb1.replace(StrMatcher.stringMatcher("aa"), "-", 11, sb1.length(), -1));
         assertEquals("aaxaaaayaa", sb1.toString());
 
-        StrBuilder sb2 = new StrBuilder("aaxaaaayaa");
+        final StrBuilder sb2 = new StrBuilder("aaxaaaayaa");
         assertThrows(
                 IndexOutOfBoundsException.class,
                 () -> sb2.replace(StrMatcher.stringMatcher("aa"), "-", -1, sb2.length(), -1));
@@ -1019,7 +1019,7 @@ public void testReplace_StrMatcher_String_int_int_int_VaryEndIndex() {
         sb.replace(StrMatcher.stringMatcher("aa"), "-", 0, 1000, -1);
         assertEquals("-x--y-", sb.toString());
 
-        StrBuilder sb1 = new StrBuilder("aaxaaaayaa");
+        final StrBuilder sb1 = new StrBuilder("aaxaaaayaa");
         assertThrows(
                 IndexOutOfBoundsException.class,
                 () -> sb1.replace(StrMatcher.stringMatcher("aa"), "-", 2, 1, -1));
diff --git a/src/test/java/org/apache/commons/lang3/text/StrSubstitutorTest.java b/src/test/java/org/apache/commons/lang3/text/StrSubstitutorTest.java
index f2f224dd0f0..a5879b680df 100644
--- a/src/test/java/org/apache/commons/lang3/text/StrSubstitutorTest.java
+++ b/src/test/java/org/apache/commons/lang3/text/StrSubstitutorTest.java
@@ -245,7 +245,7 @@ public void testCyclicReplacement() {
         map.put("critterSpeed", "quick");
         map.put("critterColor", "brown");
         map.put("critterType", "${animal}");
-        StrSubstitutor sub = new StrSubstitutor(map);
+        final StrSubstitutor sub = new StrSubstitutor(map);
         assertThrows(
                 IllegalStateException.class,
                 () -> sub.replace("The ${animal} jumps over the ${target}."),
@@ -253,7 +253,7 @@ public void testCyclicReplacement() {
 
         // also check even when default value is set.
         map.put("critterType", "${animal:-fox}");
-        StrSubstitutor sub2 = new StrSubstitutor(map);
+        final StrSubstitutor sub2 = new StrSubstitutor(map);
         assertThrows(
                 IllegalStateException.class,
                 () -> sub2.replace("The ${animal} jumps over the ${target}."),
diff --git a/src/test/java/org/apache/commons/lang3/time/DateUtilsTest.java b/src/test/java/org/apache/commons/lang3/time/DateUtilsTest.java
index 90070d59f6b..64cfde87d8c 100644
--- a/src/test/java/org/apache/commons/lang3/time/DateUtilsTest.java
+++ b/src/test/java/org/apache/commons/lang3/time/DateUtilsTest.java
@@ -1514,10 +1514,10 @@ public void testWeekIterator() {
 
             it = DateUtils.iterator((Object) now, DateUtils.RANGE_WEEK_CENTER);
             assertWeekIterator(it, centered);
-            Iterator it2 = DateUtils.iterator((Object) now.getTime(), DateUtils.RANGE_WEEK_CENTER);
+            final Iterator it2 = DateUtils.iterator((Object) now.getTime(), DateUtils.RANGE_WEEK_CENTER);
             assertWeekIterator(it2, centered);
             assertThrows(NoSuchElementException.class, it2::next);
-            Iterator it3 = DateUtils.iterator(now, DateUtils.RANGE_WEEK_CENTER);
+            final Iterator it3 = DateUtils.iterator(now, DateUtils.RANGE_WEEK_CENTER);
             it3.next();
             assertThrows(UnsupportedOperationException.class, it3::remove);
 
diff --git a/src/test/java/org/apache/commons/lang3/time/FastDateParserSDFTest.java b/src/test/java/org/apache/commons/lang3/time/FastDateParserSDFTest.java
index e948a249f1a..ce8e4bf2fcd 100644
--- a/src/test/java/org/apache/commons/lang3/time/FastDateParserSDFTest.java
+++ b/src/test/java/org/apache/commons/lang3/time/FastDateParserSDFTest.java
@@ -140,7 +140,7 @@ public void testLowerCasePP(final String format, final String input, final Local
         checkParsePosition(input.toLowerCase(locale), format, locale, valid);
     }
 
-    private void checkParse(final String formattedDate, String format, Locale locale, boolean valid) {
+    private void checkParse(final String formattedDate, final String format, final Locale locale, final boolean valid) {
         final SimpleDateFormat sdf = new SimpleDateFormat(format, locale);
         sdf.setTimeZone(timeZone);
         final DateParser fdf = new FastDateParser(format, timeZone, locale);
@@ -176,7 +176,7 @@ private void checkParse(final String formattedDate, String format, Locale locale
             assertEquals(sdfE, fdfE, locale.toString()+" "+formattedDate + " expected same Exception ");
         }
     }
-    private void checkParsePosition(final String formattedDate, String format, Locale locale, boolean valid) {
+    private void checkParsePosition(final String formattedDate, final String format, final Locale locale, final boolean valid) {
         final SimpleDateFormat sdf = new SimpleDateFormat(format, locale);
         sdf.setTimeZone(timeZone);
         final DateParser fdf = new FastDateParser(format, timeZone, locale);
diff --git a/src/test/java/org/apache/commons/lang3/time/FastDatePrinterTimeZonesTest.java b/src/test/java/org/apache/commons/lang3/time/FastDatePrinterTimeZonesTest.java
index 98a6ea53552..290022922ff 100644
--- a/src/test/java/org/apache/commons/lang3/time/FastDatePrinterTimeZonesTest.java
+++ b/src/test/java/org/apache/commons/lang3/time/FastDatePrinterTimeZonesTest.java
@@ -37,7 +37,7 @@ public static Stream data() {
 
     @ParameterizedTest
     @MethodSource("data")
-    public void testCalendarTimezoneRespected(TimeZone timeZone) {
+    public void testCalendarTimezoneRespected(final TimeZone timeZone) {
         final Calendar cal = Calendar.getInstance(timeZone);
 
         final SimpleDateFormat sdf = new SimpleDateFormat(PATTERN);
diff --git a/src/test/java/org/apache/commons/lang3/time/WeekYearTest.java b/src/test/java/org/apache/commons/lang3/time/WeekYearTest.java
index ca2c710789d..9a3a31741c6 100644
--- a/src/test/java/org/apache/commons/lang3/time/WeekYearTest.java
+++ b/src/test/java/org/apache/commons/lang3/time/WeekYearTest.java
@@ -54,7 +54,7 @@ public static Stream data() {
 
     @ParameterizedTest
     @MethodSource("data")
-    public void testParser(Calendar vulgar, String isoForm) {
+    public void testParser(final Calendar vulgar, final String isoForm) {
         final DateParser parser = new FastDateParser("YYYY-'W'ww-u", TimeZone.getDefault(), Locale.getDefault());
 
         final Calendar cal = Calendar.getInstance();
@@ -68,7 +68,7 @@ public void testParser(Calendar vulgar, String isoForm) {
 
     @ParameterizedTest
     @MethodSource("data")
-    public void testPrinter(Calendar vulgar, String isoForm) {
+    public void testPrinter(final Calendar vulgar, final String isoForm) {
         final FastDatePrinter printer = new FastDatePrinter("YYYY-'W'ww-u", TimeZone.getDefault(), Locale.getDefault());
 
         vulgar.setMinimalDaysInFirstWeek(4);
diff --git a/src/test/java/org/apache/commons/lang3/tuple/ImmutablePairTest.java b/src/test/java/org/apache/commons/lang3/tuple/ImmutablePairTest.java
index 218c814190b..f4e189a58bc 100644
--- a/src/test/java/org/apache/commons/lang3/tuple/ImmutablePairTest.java
+++ b/src/test/java/org/apache/commons/lang3/tuple/ImmutablePairTest.java
@@ -154,7 +154,7 @@ public void testPairOfObjects() {
         assertNull(pair2.getLeft());
         assertEquals("bar", pair2.right);
         assertEquals("bar", pair2.getRight());
-        ImmutablePair pair3 = ImmutablePair.of(null, null);
+        final ImmutablePair pair3 = ImmutablePair.of(null, null);
         assertNull(pair3.left);
         assertNull(pair3.right);
     }
@@ -182,11 +182,11 @@ public void testToString() {
 
     @Test
     public void testUseAsKeyOfHashMap() {
-        HashMap, String> map = new HashMap<>();
-        Object o1 = new Object();
-        Object o2 = new Object();
-        ImmutablePair key1 = ImmutablePair.of(o1, o2);
-        String value1 = "a1";
+        final HashMap, String> map = new HashMap<>();
+        final Object o1 = new Object();
+        final Object o2 = new Object();
+        final ImmutablePair key1 = ImmutablePair.of(o1, o2);
+        final String value1 = "a1";
         map.put(key1, value1);
         assertEquals(value1, map.get(key1));
         assertEquals(value1, map.get(ImmutablePair.of(o1, o2)));
@@ -194,17 +194,17 @@ public void testUseAsKeyOfHashMap() {
 
     @Test
     public void testUseAsKeyOfTreeMap() {
-        TreeMap, String> map = new TreeMap<>();
+        final TreeMap, String> map = new TreeMap<>();
         map.put(ImmutablePair.of(1, 2), "12");
         map.put(ImmutablePair.of(1, 1), "11");
         map.put(ImmutablePair.of(0, 1), "01");
-        ArrayList> expected = new ArrayList<>();
+        final ArrayList> expected = new ArrayList<>();
         expected.add(ImmutablePair.of(0, 1));
         expected.add(ImmutablePair.of(1, 1));
         expected.add(ImmutablePair.of(1, 2));
-        Iterator, String>> it = map.entrySet().iterator();
-        for (ImmutablePair item : expected) {
-            Entry, String> entry = it.next();
+        final Iterator, String>> it = map.entrySet().iterator();
+        for (final ImmutablePair item : expected) {
+            final Entry, String> entry = it.next();
             assertEquals(item, entry.getKey());
             assertEquals(item.getLeft() + "" + item.getRight(), entry.getValue());
         }
diff --git a/src/test/java/org/apache/commons/lang3/tuple/ImmutableTripleTest.java b/src/test/java/org/apache/commons/lang3/tuple/ImmutableTripleTest.java
index 4c6cd17fc42..d6d8a64a1df 100644
--- a/src/test/java/org/apache/commons/lang3/tuple/ImmutableTripleTest.java
+++ b/src/test/java/org/apache/commons/lang3/tuple/ImmutableTripleTest.java
@@ -163,12 +163,12 @@ public void testTripleOf() {
 
     @Test
     public void testUseAsKeyOfHashMap() {
-        HashMap, String> map = new HashMap<>();
-        Object o1 = new Object();
-        Object o2 = new Object();
-        Object o3 = new Object();
-        ImmutableTriple key1 = ImmutableTriple.of(o1, o2, o3);
-        String value1 = "a1";
+        final HashMap, String> map = new HashMap<>();
+        final Object o1 = new Object();
+        final Object o2 = new Object();
+        final Object o3 = new Object();
+        final ImmutableTriple key1 = ImmutableTriple.of(o1, o2, o3);
+        final String value1 = "a1";
         map.put(key1, value1);
         assertEquals(value1, map.get(key1));
         assertEquals(value1, map.get(ImmutableTriple.of(o1, o2, o3)));
@@ -176,17 +176,17 @@ public void testUseAsKeyOfHashMap() {
 
     @Test
     public void testUseAsKeyOfTreeMap() {
-        TreeMap, String> map = new TreeMap<>();
+        final TreeMap, String> map = new TreeMap<>();
         map.put(ImmutableTriple.of(0, 1, 2), "012");
         map.put(ImmutableTriple.of(0, 1, 1), "011");
         map.put(ImmutableTriple.of(0, 0, 1), "001");
-        ArrayList> expected = new ArrayList<>();
+        final ArrayList> expected = new ArrayList<>();
         expected.add(ImmutableTriple.of(0, 0, 1));
         expected.add(ImmutableTriple.of(0, 1, 1));
         expected.add(ImmutableTriple.of(0, 1, 2));
-        Iterator, String>> it = map.entrySet().iterator();
-        for (ImmutableTriple item : expected) {
-            Entry, String> entry = it.next();
+        final Iterator, String>> it = map.entrySet().iterator();
+        for (final ImmutableTriple item : expected) {
+            final Entry, String> entry = it.next();
             assertEquals(item, entry.getKey());
             assertEquals(item.getLeft() + "" + item.getMiddle() + "" + item.getRight(), entry.getValue());
         }
diff --git a/src/test/java/org/apache/commons/lang3/tuple/MutablePairTest.java b/src/test/java/org/apache/commons/lang3/tuple/MutablePairTest.java
index 731f17818e6..57a6d490d95 100644
--- a/src/test/java/org/apache/commons/lang3/tuple/MutablePairTest.java
+++ b/src/test/java/org/apache/commons/lang3/tuple/MutablePairTest.java
@@ -123,7 +123,7 @@ public void testPairOfObjects() {
         final MutablePair pair2 = MutablePair.of(null, "bar");
         assertNull(pair2.getLeft());
         assertEquals("bar", pair2.getRight());
-        MutablePair pair3 = MutablePair.of(null, null);
+        final MutablePair pair3 = MutablePair.of(null, null);
         assertNull(pair3.left);
         assertNull(pair3.right);
     }
diff --git a/src/test/java/org/apache/commons/lang3/tuple/PairTest.java b/src/test/java/org/apache/commons/lang3/tuple/PairTest.java
index 6ec78ccaae0..2ad4f50b68f 100644
--- a/src/test/java/org/apache/commons/lang3/tuple/PairTest.java
+++ b/src/test/java/org/apache/commons/lang3/tuple/PairTest.java
@@ -123,7 +123,7 @@ public void testPairOfObjects() {
         assertTrue(pair2 instanceof ImmutablePair);
         assertNull(((ImmutablePair) pair2).left);
         assertEquals("bar", ((ImmutablePair) pair2).right);
-        Pair pair3 = Pair.of(null, null);
+        final Pair pair3 = Pair.of(null, null);
         assertNull(pair3.getLeft());
         assertNull(pair3.getRight());
     }

From 05684561034bff62f8ddb6b61cbbeda6566291bc Mon Sep 17 00:00:00 2001
From: Gary Gregory 
Date: Fri, 14 Feb 2020 09:39:49 -0500
Subject: [PATCH 0012/3230] Remove redundant type arguments and end-of-line
 whitespace.

---
 src/main/java/org/apache/commons/lang3/ClassUtils.java | 2 +-
 src/main/java/org/apache/commons/lang3/Functions.java  | 4 ++--
 src/main/java/org/apache/commons/lang3/Streams.java    | 4 ++--
 3 files changed, 5 insertions(+), 5 deletions(-)

diff --git a/src/main/java/org/apache/commons/lang3/ClassUtils.java b/src/main/java/org/apache/commons/lang3/ClassUtils.java
index 040eb21c924..d0891ddd791 100644
--- a/src/main/java/org/apache/commons/lang3/ClassUtils.java
+++ b/src/main/java/org/apache/commons/lang3/ClassUtils.java
@@ -53,7 +53,7 @@ public enum Interfaces {
 
         /** Includes interfaces. */
         INCLUDE,
-        
+
         /** Excludes interfaces. */
         EXCLUDE
     }
diff --git a/src/main/java/org/apache/commons/lang3/Functions.java b/src/main/java/org/apache/commons/lang3/Functions.java
index 0424e1919a8..91b4c9a08ce 100644
--- a/src/main/java/org/apache/commons/lang3/Functions.java
+++ b/src/main/java/org/apache/commons/lang3/Functions.java
@@ -417,7 +417,7 @@ public static  O get(final FailableSupplier pSuppl
      * @return The created {@link FailableStream}.
      */
     public static  FailableStream stream(final Stream pStream) {
-        return new FailableStream(pStream);
+        return new FailableStream<>(pStream);
     }
 
     /**
@@ -434,7 +434,7 @@ public static  FailableStream stream(final Stream pStream) {
      * @return The created {@link FailableStream}.
      */
     public static  FailableStream stream(final Collection pCollection) {
-        return new FailableStream(pCollection.stream());
+        return new FailableStream<>(pCollection.stream());
     }
 
 
diff --git a/src/main/java/org/apache/commons/lang3/Streams.java b/src/main/java/org/apache/commons/lang3/Streams.java
index f9d590a3672..9510c580f11 100644
--- a/src/main/java/org/apache/commons/lang3/Streams.java
+++ b/src/main/java/org/apache/commons/lang3/Streams.java
@@ -279,7 +279,7 @@ public O reduce(final O pIdentity, final BinaryOperator pAccumulator) {
          */
         public  FailableStream map(final FailableFunction pMapper) {
             assertNotTerminated();
-            return new FailableStream(stream.map(Functions.asFunction(pMapper)));
+            return new FailableStream<>(stream.map(Functions.asFunction(pMapper)));
         }
 
         /**
@@ -376,7 +376,7 @@ public boolean anyMatch(final FailablePredicate pPredicate) {
      *   converting the stream.
      */
     public static  FailableStream stream(final Stream pStream) {
-        return new FailableStream(pStream);
+        return new FailableStream<>(pStream);
     }
 
     /**

From 05588e4ebb03fb0c9c5f908d7bae049849565afb Mon Sep 17 00:00:00 2001
From: Gary Gregory 
Date: Fri, 14 Feb 2020 09:50:53 -0500
Subject: [PATCH 0013/3230] - Javadoc. - Don't use 'p' as a parameter name
 prefix (we don't do that anywhere else.)

---
 .../org/apache/commons/lang3/Streams.java     | 93 ++++++++++---------
 .../lang3/compare/ComparableUtils.java        |  2 +
 2 files changed, 53 insertions(+), 42 deletions(-)

diff --git a/src/main/java/org/apache/commons/lang3/Streams.java b/src/main/java/org/apache/commons/lang3/Streams.java
index 9510c580f11..f89cf1673c0 100644
--- a/src/main/java/org/apache/commons/lang3/Streams.java
+++ b/src/main/java/org/apache/commons/lang3/Streams.java
@@ -32,10 +32,10 @@
 import org.apache.commons.lang3.Functions.FailablePredicate;
 
 /**
- * This class provides utility functions, and classes for working with the
- * java.util.stream package, or more generally, with Java 8 lambdas. More
+ * Provides utility functions, and classes for working with the
+ * {@code java.util.stream} package, or more generally, with Java 8 lambdas. More
  * specifically, it attempts to address the fact that lambdas are supposed
- * not to throw Exceptions, at least not checked Exceptions, aka instances
+ * not to throw Exceptions, at least not checked Exceptions, AKA instances
  * of {@link Exception}. This enforces the use of constructs like
  * 
  *     Consumer<java.lang.reflect.Method> consumer = (m) -> {
@@ -53,20 +53,29 @@
  * 
* Obviously, the second version is much more concise and the spirit of * Lambda expressions is met better than in the first version. + * * @see Stream * @see Functions + * @since 3.10 */ public class Streams { - /** A reduced, and simplified version of a {@link Stream} with - * failable method signatures. - * @param The streams element type. - */ + + /** + * A reduced, and simplified version of a {@link Stream} with + * failable method signatures. + * @param The streams element type. + */ public static class FailableStream { + private Stream stream; private boolean terminated; - public FailableStream(final Stream pStream) { - stream = pStream; + /** + * Constructs a new instance with the given {@code stream}. + * @param stream The stream. + */ + public FailableStream(final Stream stream) { + this.stream = stream; } protected void assertNotTerminated() { @@ -86,13 +95,13 @@ protected void makeTerminated() { * *

This is an intermediate operation. * - * @param pPredicate a non-interfering, stateless predicate to apply to each + * @param predicate a non-interfering, stateless predicate to apply to each * element to determine if it should be included. * @return the new stream */ - public FailableStream filter(final FailablePredicate pPredicate){ + public FailableStream filter(final FailablePredicate predicate){ assertNotTerminated(); - stream = stream.filter(Functions.asPredicate(pPredicate)); + stream = stream.filter(Functions.asPredicate(predicate)); return this; } @@ -109,11 +118,11 @@ public FailableStream filter(final FailablePredicate pPredicate){ * library chooses. If the action accesses shared state, it is * responsible for providing the required synchronization. * - * @param pAction a non-interfering action to perform on the elements + * @param action a non-interfering action to perform on the elements */ - public void forEach(final FailableConsumer pAction) { + public void forEach(final FailableConsumer action) { makeTerminated(); - stream().forEach(Functions.asConsumer(pAction)); + stream().forEach(Functions.asConsumer(action)); } /** @@ -159,14 +168,14 @@ public void forEach(final FailableConsumer pAction) { * * @param the type of the result * @param the intermediate accumulation type of the {@code Collector} - * @param pCollector the {@code Collector} describing the reduction + * @param collector the {@code Collector} describing the reduction * @return the result of the reduction * @see #collect(Supplier, BiConsumer, BiConsumer) * @see Collectors */ - public R collect(final Collector pCollector) { + public R collect(final Collector collector) { makeTerminated(); - return stream().collect(pCollector); + return stream().collect(collector); } /** @@ -204,19 +213,19 @@ public R collect(final Collector pCollector) { * * @param type of the result * @param Type of the accumulator. - * @param pSupplier a function that creates a new result container. For a + * @param pupplier a function that creates a new result container. For a * parallel execution, this function may be called * multiple times and must return a fresh value each time. - * @param pAccumulator An associative, non-interfering, stateless function for + * @param accumulator An associative, non-interfering, stateless function for * incorporating an additional element into a result - * @param pCombiner An associative, non-interfering, stateless + * @param combiner An associative, non-interfering, stateless * function for combining two values, which must be compatible with the * accumulator function * @return The result of the reduction */ - public R collect(final Supplier pSupplier, final BiConsumer pAccumulator, final BiConsumer pCombiner) { + public R collect(final Supplier pupplier, final BiConsumer accumulator, final BiConsumer combiner) { makeTerminated(); - return stream().collect(pSupplier, pAccumulator, pCombiner); + return stream().collect(pupplier, accumulator, combiner); } /** @@ -257,14 +266,14 @@ public R collect(final Supplier pSupplier, final BiConsumer pAccumulator) { + public O reduce(final O identity, final BinaryOperator accumulator) { makeTerminated(); - return stream().reduce(pIdentity, pAccumulator); + return stream().reduce(identity, accumulator); } /** @@ -274,12 +283,12 @@ public O reduce(final O pIdentity, final BinaryOperator pAccumulator) { *

This is an intermediate operation. * * @param The element type of the new stream - * @param pMapper A non-interfering, stateless function to apply to each element + * @param mapper A non-interfering, stateless function to apply to each element * @return the new stream */ - public FailableStream map(final FailableFunction pMapper) { + public FailableStream map(final FailableFunction mapper) { assertNotTerminated(); - return new FailableStream<>(stream.map(Functions.asFunction(pMapper))); + return new FailableStream<>(stream.map(Functions.asFunction(mapper))); } /** @@ -304,14 +313,14 @@ public Stream stream() { * stream is empty, the quantification is said to be vacuously * satisfied and is always {@code true} (regardless of P(x)). * - * @param pPredicate A non-interfering, stateless predicate to apply to + * @param predicate A non-interfering, stateless predicate to apply to * elements of this stream * @return {@code true} If either all elements of the stream match the * provided predicate or the stream is empty, otherwise {@code false}. */ - public boolean allMatch(final FailablePredicate pPredicate) { + public boolean allMatch(final FailablePredicate predicate) { assertNotTerminated(); - return stream().allMatch(Functions.asPredicate(pPredicate)); + return stream().allMatch(Functions.asPredicate(predicate)); } /** @@ -326,14 +335,14 @@ public boolean allMatch(final FailablePredicate pPredicate) { * This method evaluates the existential quantification of the * predicate over the elements of the stream (for some x P(x)). * - * @param pPredicate A non-interfering, stateless predicate to apply to + * @param predicate A non-interfering, stateless predicate to apply to * elements of this stream * @return {@code true} if any elements of the stream match the provided * predicate, otherwise {@code false} */ - public boolean anyMatch(final FailablePredicate pPredicate) { + public boolean anyMatch(final FailablePredicate predicate) { assertNotTerminated(); - return stream().anyMatch(Functions.asPredicate(pPredicate)); + return stream().anyMatch(Functions.asPredicate(predicate)); } } @@ -371,12 +380,12 @@ public boolean anyMatch(final FailablePredicate pPredicate) { * concise, and readable, and meets the spirit of Lambdas better * than the first version. * @param The streams element type. - * @param pStream The stream, which is being converted. + * @param stream The stream, which is being converted. * @return The {@link FailableStream}, which has been created by * converting the stream. */ - public static FailableStream stream(final Stream pStream) { - return new FailableStream<>(pStream); + public static FailableStream stream(final Stream stream) { + return new FailableStream<>(stream); } /** @@ -413,11 +422,11 @@ public static FailableStream stream(final Stream pStream) { * concise, and readable, and meets the spirit of Lambdas better * than the first version. * @param The streams element type. - * @param pStream The stream, which is being converted. + * @param stream The stream, which is being converted. * @return The {@link FailableStream}, which has been created by * converting the stream. */ - public static FailableStream stream(final Collection pStream) { - return stream(pStream.stream()); + public static FailableStream stream(final Collection stream) { + return stream(stream.stream()); } } diff --git a/src/main/java/org/apache/commons/lang3/compare/ComparableUtils.java b/src/main/java/org/apache/commons/lang3/compare/ComparableUtils.java index 4312af7ef17..c757a525407 100644 --- a/src/main/java/org/apache/commons/lang3/compare/ComparableUtils.java +++ b/src/main/java/org/apache/commons/lang3/compare/ComparableUtils.java @@ -31,6 +31,8 @@ public class ComparableUtils { /** * Provides access to the available methods + * + * @param the type of objects that this object may be compared against. */ public static class ComparableCheckBuilder> { From d54c8951d64bfaa7b85dc45dda5406ed05f9b07f Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Fri, 14 Feb 2020 10:00:33 -0500 Subject: [PATCH 0014/3230] Javadoc style. --- .../org/apache/commons/lang3/CharRange.java | 8 ++++---- .../org/apache/commons/lang3/ThreadUtils.java | 20 +++++++++---------- .../lang3/builder/HashCodeBuilder.java | 2 +- .../concurrent/AtomicSafeInitializer.java | 2 +- .../lang3/event/EventListenerSupport.java | 2 +- .../commons/lang3/reflect/MethodUtils.java | 2 +- .../commons/lang3/reflect/TypeUtils.java | 6 +++--- .../lang3/text/ExtendedMessageFormat.java | 2 +- .../commons/lang3/text/FormattableUtils.java | 2 +- .../apache/commons/lang3/time/DateUtils.java | 2 +- .../commons/lang3/time/FastDateParser.java | 16 +++++++-------- 11 files changed, 32 insertions(+), 32 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/CharRange.java b/src/main/java/org/apache/commons/lang3/CharRange.java index 6a416bb632a..be656d2a531 100644 --- a/src/main/java/org/apache/commons/lang3/CharRange.java +++ b/src/main/java/org/apache/commons/lang3/CharRange.java @@ -271,7 +271,7 @@ private static class CharacterIterator implements Iterator { private boolean hasNext; /** - * Construct a new iterator for the character range. + * Constructs a new iterator for the character range. * * @param r The character range */ @@ -296,7 +296,7 @@ private CharacterIterator(final CharRange r) { } /** - * Prepare the next character in the range. + * Prepares the next character in the range. */ private void prepareNext() { if (range.negated) { @@ -329,7 +329,7 @@ public boolean hasNext() { } /** - * Return the next character in the iteration + * Returns the next character in the iteration * * @return {@code Character} for the next character */ @@ -346,7 +346,7 @@ public Character next() { /** * Always throws UnsupportedOperationException. * - * @throws UnsupportedOperationException + * @throws UnsupportedOperationException Always thrown. * @see java.util.Iterator#remove() */ @Override diff --git a/src/main/java/org/apache/commons/lang3/ThreadUtils.java b/src/main/java/org/apache/commons/lang3/ThreadUtils.java index 16986e0de9d..5534194fa98 100644 --- a/src/main/java/org/apache/commons/lang3/ThreadUtils.java +++ b/src/main/java/org/apache/commons/lang3/ThreadUtils.java @@ -36,7 +36,7 @@ public class ThreadUtils { /** - * Return the active thread with the specified id if it belongs to the specified thread group. + * Finds the active thread with the specified id if it belongs to the specified thread group. * * @param threadId The thread id * @param threadGroup The thread group @@ -59,7 +59,7 @@ public static Thread findThreadById(final long threadId, final ThreadGroup threa } /** - * Return the active thread with the specified id if it belongs to a thread group with the specified group name. + * Finds the active thread with the specified id if it belongs to a thread group with the specified group name. * * @param threadId The thread id * @param threadGroupName The thread group name @@ -82,7 +82,7 @@ public static Thread findThreadById(final long threadId, final String threadGrou } /** - * Return active threads with the specified name if they belong to a specified thread group. + * Finds active threads with the specified name if they belong to a specified thread group. * * @param threadName The thread name * @param threadGroup The thread group @@ -100,7 +100,7 @@ public static Collection findThreadsByName(final String threadName, fina } /** - * Return active threads with the specified name if they belong to a thread group with the specified group name. + * Finds active threads with the specified name if they belong to a thread group with the specified group name. * * @param threadName The thread name * @param threadGroupName The thread group name @@ -132,7 +132,7 @@ public static Collection findThreadsByName(final String threadName, fina } /** - * Return active thread groups with the specified group name. + * Finds active thread groups with the specified group name. * * @param threadGroupName The thread group name * @return the thread groups with the specified group name or an empty collection if no such thread group exists. The collection returned is always unmodifiable. @@ -148,7 +148,7 @@ public static Collection findThreadGroupsByName(final String thread } /** - * Return all active thread groups excluding the system thread group (A thread group is active if it has been not destroyed). + * Gets all active thread groups excluding the system thread group (A thread group is active if it has been not destroyed). * * @return all thread groups excluding the system thread group. The collection returned is always unmodifiable. * @throws SecurityException @@ -162,7 +162,7 @@ public static Collection getAllThreadGroups() { } /** - * Return the system thread group (sometimes also referred as "root thread group"). + * Gets the system thread group (sometimes also referred as "root thread group"). * * @return the system thread group * @throws SecurityException if the current thread cannot modify @@ -177,7 +177,7 @@ public static ThreadGroup getSystemThreadGroup() { } /** - * Return all active threads (A thread is active if it has been started and has not yet died). + * Gets all active threads (A thread is active if it has been started and has not yet died). * * @return all active threads. The collection returned is always unmodifiable. * @throws SecurityException @@ -191,7 +191,7 @@ public static Collection getAllThreads() { } /** - * Return active threads with the specified name. + * Finds active threads with the specified name. * * @param threadName The thread name * @return The threads with the specified name or an empty collection if no such thread exists. The collection returned is always unmodifiable. @@ -207,7 +207,7 @@ public static Collection findThreadsByName(final String threadName) { } /** - * Return the active thread with the specified id. + * Finds the active thread with the specified id. * * @param threadId The thread id * @return The thread with the specified id or {@code null} if no such thread exists diff --git a/src/main/java/org/apache/commons/lang3/builder/HashCodeBuilder.java b/src/main/java/org/apache/commons/lang3/builder/HashCodeBuilder.java index 90d4fabbad2..c430b4060a4 100644 --- a/src/main/java/org/apache/commons/lang3/builder/HashCodeBuilder.java +++ b/src/main/java/org/apache/commons/lang3/builder/HashCodeBuilder.java @@ -959,7 +959,7 @@ public HashCodeBuilder appendSuper(final int superHashCode) { /** *

- * Return the computed {@code hashCode}. + * Returns the computed {@code hashCode}. *

* * @return {@code hashCode} based on the fields appended diff --git a/src/main/java/org/apache/commons/lang3/concurrent/AtomicSafeInitializer.java b/src/main/java/org/apache/commons/lang3/concurrent/AtomicSafeInitializer.java index 0b1a500c890..5bc91f1ad02 100644 --- a/src/main/java/org/apache/commons/lang3/concurrent/AtomicSafeInitializer.java +++ b/src/main/java/org/apache/commons/lang3/concurrent/AtomicSafeInitializer.java @@ -62,7 +62,7 @@ public abstract class AtomicSafeInitializer implements private final AtomicReference reference = new AtomicReference<>(); /** - * Get (and initialize, if not initialized yet) the required object + * Gets (and initialize, if not initialized yet) the required object * * @return lazily initialized object * @throws ConcurrentException if the initialization of the object causes an diff --git a/src/main/java/org/apache/commons/lang3/event/EventListenerSupport.java b/src/main/java/org/apache/commons/lang3/event/EventListenerSupport.java index 18133753d69..499032d1dbd 100644 --- a/src/main/java/org/apache/commons/lang3/event/EventListenerSupport.java +++ b/src/main/java/org/apache/commons/lang3/event/EventListenerSupport.java @@ -225,7 +225,7 @@ public void removeListener(final L listener) { } /** - * Get an array containing the currently registered listeners. + * Gets an array containing the currently registered listeners. * Modification to this array's elements will have no effect on the * {@link EventListenerSupport} instance. * @return L[] diff --git a/src/main/java/org/apache/commons/lang3/reflect/MethodUtils.java b/src/main/java/org/apache/commons/lang3/reflect/MethodUtils.java index 905052ff110..8ebc790a46d 100644 --- a/src/main/java/org/apache/commons/lang3/reflect/MethodUtils.java +++ b/src/main/java/org/apache/commons/lang3/reflect/MethodUtils.java @@ -785,7 +785,7 @@ private static int distance(final Class[] classArray, final Class[] toClas } /** - * Get the hierarchy of overridden methods down to {@code result} respecting generics. + * Gets the hierarchy of overridden methods down to {@code result} respecting generics. * @param method lowest to consider * @param interfacesBehavior whether to search interfaces, {@code null} {@code implies} false * @return Set<Method> in ascending order from sub- to superclass diff --git a/src/main/java/org/apache/commons/lang3/reflect/TypeUtils.java b/src/main/java/org/apache/commons/lang3/reflect/TypeUtils.java index e1bbd0e8c63..eced4e08294 100644 --- a/src/main/java/org/apache/commons/lang3/reflect/TypeUtils.java +++ b/src/main/java/org/apache/commons/lang3/reflect/TypeUtils.java @@ -1338,7 +1338,7 @@ public static boolean isArrayType(final Type type) { } /** - * Get the array component type of {@code type}. + * Gets the array component type of {@code type}. * @param type the type to be checked * @return component type or null if type is not an array type */ @@ -1354,7 +1354,7 @@ public static Type getArrayComponentType(final Type type) { } /** - * Get a type representing {@code type} with variable assignments "unrolled." + * Gets a type representing {@code type} with variable assignments "unrolled." * * @param typeArguments as from {@link TypeUtils#getTypeArguments(Type, Class)} * @param type the type to unroll variable assignments for @@ -1540,7 +1540,7 @@ private static Type[] extractTypeArgumentsFrom(final Map, Type> } /** - * Get a {@link WildcardTypeBuilder}. + * Gets a {@link WildcardTypeBuilder}. * @return {@link WildcardTypeBuilder} * @since 3.2 */ diff --git a/src/main/java/org/apache/commons/lang3/text/ExtendedMessageFormat.java b/src/main/java/org/apache/commons/lang3/text/ExtendedMessageFormat.java index f52097bea74..6b921b87a82 100644 --- a/src/main/java/org/apache/commons/lang3/text/ExtendedMessageFormat.java +++ b/src/main/java/org/apache/commons/lang3/text/ExtendedMessageFormat.java @@ -295,7 +295,7 @@ public int hashCode() { } /** - * Get a custom format from a format description. + * Gets a custom format from a format description. * * @param desc String * @return Format diff --git a/src/main/java/org/apache/commons/lang3/text/FormattableUtils.java b/src/main/java/org/apache/commons/lang3/text/FormattableUtils.java index dd95561e9e6..a98299c89a0 100644 --- a/src/main/java/org/apache/commons/lang3/text/FormattableUtils.java +++ b/src/main/java/org/apache/commons/lang3/text/FormattableUtils.java @@ -59,7 +59,7 @@ public FormattableUtils() { //----------------------------------------------------------------------- /** - * Get the default formatted representation of the specified + * Gets the default formatted representation of the specified * {@code Formattable}. * * @param formattable the instance to convert to a string, not null diff --git a/src/main/java/org/apache/commons/lang3/time/DateUtils.java b/src/main/java/org/apache/commons/lang3/time/DateUtils.java index 2d651cf0a7c..9fa254981ed 100644 --- a/src/main/java/org/apache/commons/lang3/time/DateUtils.java +++ b/src/main/java/org/apache/commons/lang3/time/DateUtils.java @@ -1821,7 +1821,7 @@ public boolean hasNext() { } /** - * Return the next calendar in the iteration + * Returns the next calendar in the iteration * * @return Object calendar for the next date */ diff --git a/src/main/java/org/apache/commons/lang3/time/FastDateParser.java b/src/main/java/org/apache/commons/lang3/time/FastDateParser.java index 79fb37d7d88..233cf3f675c 100644 --- a/src/main/java/org/apache/commons/lang3/time/FastDateParser.java +++ b/src/main/java/org/apache/commons/lang3/time/FastDateParser.java @@ -451,7 +451,7 @@ private static StringBuilder simpleQuote(final StringBuilder sb, final String va } /** - * Get the short and long values displayed for a field + * Gets the short and long values displayed for a field * @param cal The calendar to obtain the short and long values * @param locale The locale of display names * @param field The field of interest @@ -606,7 +606,7 @@ private Strategy getStrategy(final char f, final int width, final Calendar defin private static final ConcurrentMap[] caches = new ConcurrentMap[Calendar.FIELD_COUNT]; /** - * Get a cache of Strategies for a particular field + * Gets a cache of Strategies for a particular field * @param field The Calendar field * @return a cache of Locale to Strategy */ @@ -620,7 +620,7 @@ private static ConcurrentMap getCache(final int field) { } /** - * Construct a Strategy that parses a Text field + * Constructs a Strategy that parses a Text field * @param field The Calendar field * @param definingCalendar The calendar to obtain the short and long values * @return a TextStrategy for the field and Locale @@ -648,7 +648,7 @@ private static class CopyQuotedStrategy extends Strategy { private final String formatField; /** - * Construct a Strategy that ensures the formatField has literal text + * Constructs a Strategy that ensures the formatField has literal text * @param formatField The literal text to match */ CopyQuotedStrategy(final String formatField) { @@ -690,7 +690,7 @@ private static class CaseInsensitiveTextStrategy extends PatternStrategy { private final Map lKeyValues; /** - * Construct a Strategy that parses a Text field + * Constructs a Strategy that parses a Text field * @param field The Calendar field * @param definingCalendar The Calendar to use * @param locale The Locale to use @@ -730,7 +730,7 @@ private static class NumberStrategy extends Strategy { private final int field; /** - * Construct a Strategy that parses a Number field + * Constructs a Strategy that parses a Number field * @param field The Calendar field */ NumberStrategy(final int field) { @@ -833,7 +833,7 @@ private static class TzInfo { private static final int ID = 0; /** - * Construct a Strategy that parses a TimeZone + * Constructs a Strategy that parses a TimeZone * @param locale The Locale */ TimeZoneStrategy(final Locale locale) { @@ -912,7 +912,7 @@ private static class ISO8601TimeZoneStrategy extends PatternStrategy { // Z, +hh, -hh, +hhmm, -hhmm, +hh:mm or -hh:mm /** - * Construct a Strategy that parses a TimeZone + * Constructs a Strategy that parses a TimeZone * @param pattern The Pattern */ ISO8601TimeZoneStrategy(final String pattern) { From b19b2d37dafb1f26360ee5e8ac6fa297e9ae86ab Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Fri, 14 Feb 2020 11:43:40 -0500 Subject: [PATCH 0015/3230] Checkstyle: Remove trailing white spaces on all lines. --- src/main/java/org/apache/commons/lang3/Streams.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/apache/commons/lang3/Streams.java b/src/main/java/org/apache/commons/lang3/Streams.java index f89cf1673c0..9898d067063 100644 --- a/src/main/java/org/apache/commons/lang3/Streams.java +++ b/src/main/java/org/apache/commons/lang3/Streams.java @@ -60,7 +60,7 @@ */ public class Streams { - /** + /** * A reduced, and simplified version of a {@link Stream} with * failable method signatures. * @param The streams element type. From 83dd32b901dea25a571adcd6a976464c8a36601c Mon Sep 17 00:00:00 2001 From: "U-EUR\\jwi" Date: Fri, 14 Feb 2020 22:25:06 +0100 Subject: [PATCH 0016/3230] Adding Streams.toArray --- .../org/apache/commons/lang3/Streams.java | 61 +++++++++++++++++++ .../org/apache/commons/lang3/StreamsTest.java | 11 ++++ 2 files changed, 72 insertions(+) diff --git a/src/main/java/org/apache/commons/lang3/Streams.java b/src/main/java/org/apache/commons/lang3/Streams.java index c097d76f371..86edb2f42d1 100644 --- a/src/main/java/org/apache/commons/lang3/Streams.java +++ b/src/main/java/org/apache/commons/lang3/Streams.java @@ -16,7 +16,12 @@ */ package org.apache.commons.lang3; +import java.lang.reflect.Array; +import java.util.ArrayList; import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Set; import java.util.function.BiConsumer; import java.util.function.BinaryOperator; import java.util.function.Consumer; @@ -420,4 +425,60 @@ public static FailableStream stream(Stream pStream) { public static FailableStream stream(Collection pStream) { return stream(pStream.stream()); } + + public static class ArrayCollector implements Collector, O[]> { + private static final Set characteristics = Collections.emptySet(); + private final Class elementType; + + public ArrayCollector(Class pElementType) { + elementType = pElementType; + } + + @Override + public Supplier> supplier() { + return () -> new ArrayList(); + } + + @Override + public BiConsumer, O> accumulator() { + return (list, o) -> { + list.add(o); + }; + } + + @Override + public BinaryOperator> combiner() { + return (left, right) -> { + left.addAll(right); + return left; + }; + } + + @Override + public Function, O[]> finisher() { + return (list) -> { + @SuppressWarnings("unchecked") + final O[] array = (O[]) Array.newInstance(elementType, list.size()); + return list.toArray(array); + }; + } + + @Override + public Set characteristics() { + return characteristics; + } + } + + /** + * Returns a {@code Collector} that accumulates the input elements into a + * new array. + * + * @param pElementType Type of an element in the array. + * @param the type of the input elements + * @return a {@code Collector} which collects all the input elements into an + * array, in encounter order + */ + public static Collector toArray(Class pElementType) { + return new ArrayCollector(pElementType); + } } diff --git a/src/test/java/org/apache/commons/lang3/StreamsTest.java b/src/test/java/org/apache/commons/lang3/StreamsTest.java index 3ce713d9321..da98397d31d 100644 --- a/src/test/java/org/apache/commons/lang3/StreamsTest.java +++ b/src/test/java/org/apache/commons/lang3/StreamsTest.java @@ -17,6 +17,7 @@ package org.apache.commons.lang3; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.fail; @@ -64,6 +65,16 @@ void testSimpleStreamForEach() { } } + @Test + void testToArray() { + final String[] array = Arrays.asList("2", "3", "1").stream().collect(Streams.toArray(String.class)); + assertNotNull(array); + assertEquals(3, array.length); + assertEquals("2", array[0]); + assertEquals("3", array[1]); + assertEquals("1", array[2]); + } + protected FailableConsumer asIntConsumer(T pThrowable) { return (s) -> { final Integer i = Integer.valueOf(s); From 53f223d3e397fe04ea76bf445e2db37fd09753be Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Fri, 14 Feb 2020 18:51:24 -0500 Subject: [PATCH 0017/3230] Remove redundant type arguments. Use final. --- src/main/java/org/apache/commons/lang3/Streams.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/Streams.java b/src/main/java/org/apache/commons/lang3/Streams.java index 6a3572583c1..07a400d1a9c 100644 --- a/src/main/java/org/apache/commons/lang3/Streams.java +++ b/src/main/java/org/apache/commons/lang3/Streams.java @@ -439,13 +439,13 @@ public static class ArrayCollector implements Collector, O[]> { private static final Set characteristics = Collections.emptySet(); private final Class elementType; - public ArrayCollector(Class pElementType) { + public ArrayCollector(final Class pElementType) { elementType = pElementType; } @Override public Supplier> supplier() { - return () -> new ArrayList(); + return () -> new ArrayList<>(); } @Override @@ -487,7 +487,7 @@ public Set characteristics() { * @return a {@code Collector} which collects all the input elements into an * array, in encounter order */ - public static Collector toArray(Class pElementType) { - return new ArrayCollector(pElementType); + public static Collector toArray(final Class pElementType) { + return new ArrayCollector<>(pElementType); } } From 84197ae4e791b8b01fde1dd246c06b1922ecc605 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Fri, 14 Feb 2020 18:52:57 -0500 Subject: [PATCH 0018/3230] Don't use 'p' as a parameter name prefix (we don't do that anywhere else.) Add missing Javadoc. --- src/main/java/org/apache/commons/lang3/Streams.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/Streams.java b/src/main/java/org/apache/commons/lang3/Streams.java index 07a400d1a9c..b5e7d43128b 100644 --- a/src/main/java/org/apache/commons/lang3/Streams.java +++ b/src/main/java/org/apache/commons/lang3/Streams.java @@ -439,8 +439,8 @@ public static class ArrayCollector implements Collector, O[]> { private static final Set characteristics = Collections.emptySet(); private final Class elementType; - public ArrayCollector(final Class pElementType) { - elementType = pElementType; + public ArrayCollector(final Class elementType) { + this.elementType = elementType; } @Override From 772edb9112d39eb981ce34dfeacbd1cdfde6d08a Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Mon, 17 Feb 2020 08:50:05 -0500 Subject: [PATCH 0019/3230] SpotBugs 4.4.0-RC3 -> 4.0.0. --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index b2503f1c98c..512ffe5b674 100644 --- a/pom.xml +++ b/pom.xml @@ -764,7 +764,7 @@ com.github.spotbugs spotbugs - 4.0.0-RC3 + 4.0.0 From d3e5953b597bb3b149dae16b7109e84de98e6773 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Mon, 17 Feb 2020 09:01:08 -0500 Subject: [PATCH 0020/3230] Checkstyle 8.27 -> 8.29. --- checkstyle.xml | 1 - pom.xml | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/checkstyle.xml b/checkstyle.xml index 0adaecc1eda..ad7c68a7dd8 100644 --- a/checkstyle.xml +++ b/checkstyle.xml @@ -45,7 +45,6 @@ limitations under the License. - diff --git a/pom.xml b/pom.xml index 512ffe5b674..a76c799517e 100644 --- a/pom.xml +++ b/pom.xml @@ -600,7 +600,7 @@ utf-8 3.1.0 - 8.27 + 8.29 3.1.12.2 false From f20df2124907ec20479bff5f8784a8dbbdc48425 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Mon, 17 Feb 2020 09:23:27 -0500 Subject: [PATCH 0021/3230] De-clutter root folder by moving Checkstyle configuration files into src. --- pom.xml | 5 +++-- .../site/resources/checkstyle/checkstyle-suppressions.xml | 0 .../site/resources/checkstyle/checkstyle.xml | 2 +- 3 files changed, 4 insertions(+), 3 deletions(-) rename checkstyle-suppressions.xml => src/site/resources/checkstyle/checkstyle-suppressions.xml (100%) rename checkstyle.xml => src/site/resources/checkstyle/checkstyle.xml (95%) diff --git a/pom.xml b/pom.xml index a76c799517e..b3c484bf9af 100644 --- a/pom.xml +++ b/pom.xml @@ -601,6 +601,7 @@ 3.1.0 8.29 + src/site/resources/checkstyle 3.1.12.2 false @@ -744,7 +745,7 @@ maven-checkstyle-plugin ${checkstyle.plugin.version} - ${basedir}/checkstyle.xml + ${checkstyle.configdir}/checkstyle.xml true false @@ -781,7 +782,7 @@ maven-checkstyle-plugin ${checkstyle.plugin.version} - ${basedir}/checkstyle.xml + ${checkstyle.configdir}/checkstyle.xml true false diff --git a/checkstyle-suppressions.xml b/src/site/resources/checkstyle/checkstyle-suppressions.xml similarity index 100% rename from checkstyle-suppressions.xml rename to src/site/resources/checkstyle/checkstyle-suppressions.xml diff --git a/checkstyle.xml b/src/site/resources/checkstyle/checkstyle.xml similarity index 95% rename from checkstyle.xml rename to src/site/resources/checkstyle/checkstyle.xml index ad7c68a7dd8..279bd8cc9af 100644 --- a/checkstyle.xml +++ b/src/site/resources/checkstyle/checkstyle.xml @@ -36,7 +36,7 @@ limitations under the License. - + From 80839be4577e298335a1d3887518bf1ef4455f64 Mon Sep 17 00:00:00 2001 From: Peter Verhas Date: Mon, 17 Feb 2020 15:58:19 +0100 Subject: [PATCH 0022/3230] JavaDoc was modified adding {@code around pre formatted text so there is no need for HTML escape sequences (#490) --- .../org/apache/commons/lang3/Functions.java | 24 +++++++++---------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/Functions.java b/src/main/java/org/apache/commons/lang3/Functions.java index 91b4c9a08ce..e7808acc9ae 100644 --- a/src/main/java/org/apache/commons/lang3/Functions.java +++ b/src/main/java/org/apache/commons/lang3/Functions.java @@ -40,21 +40,21 @@ * More specifically, it attempts to address the fact that lambdas are supposed * not to throw Exceptions, at least not checked Exceptions, aka instances of * {@link Exception}. This enforces the use of constructs like - *
- *   Consumer<java.lang.reflect.Method> consumer = (m) -> {
+ * 
{@code
+ *   Consumer consumer = (m) -> {
  *       try {
  *           m.invoke(o, args);
  *       } catch (Throwable t) {
  *           throw Functions.rethrow(t);
  *       }
  *   };
- * 
+ * }
* By replacing a {@link java.util.function.Consumer Consumer<O>} with a * {@link FailableConsumer FailableConsumer<O,? extends Throwable>}, this can be * written like follows: - *
- *   Functions.accept((m) -> m.invoke(o,args));
- * 
+ *
{@code
+ *   Functions.accept((m) -> m.invoke(o,args));
+ * }
* Obviously, the second version is much more concise and the spirit of * Lambda expressions is met better than the second version. */ @@ -446,10 +446,10 @@ public static FailableStream stream(final Collection pCollection) { * and regardless of success, or failure. If either the original action, or * any of the resource action fails, then the first failure (aka * {@link Throwable} is rethrown. Example use: - *
+     * 
{@code
      *   final FileInputStream fis = new FileInputStream("my.file");
-     *   Functions.tryWithResources(useInputStream(fis), null, () -> fis.close());
-     * 
+ * Functions.tryWithResources(useInputStream(fis), null, () -> fis.close()); + * }
* @param pAction The action to execute. This object will always * be invoked. * @param pErrorHandler An optional error handler, which will be invoked finally, @@ -509,10 +509,10 @@ public static void tryWithResources(final FailableRunnable * and regardless of success, or failure. If either the original action, or * any of the resource action fails, then the first failure (aka * {@link Throwable} is rethrown. Example use: - *
+     * 
{@code
      *   final FileInputStream fis = new FileInputStream("my.file");
-     *   Functions.tryWithResources(useInputStream(fis), () -> fis.close());
-     * 
+ * Functions.tryWithResources(useInputStream(fis), () -> fis.close()); + * }
* @param pAction The action to execute. This object will always * be invoked. * @param pResources The resource actions to execute. All resource From 2cceff590d4e38d51c210927c611186a4dc0b654 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Mon, 17 Feb 2020 10:00:02 -0500 Subject: [PATCH 0023/3230] Use Javadoc {@code} instead of pre tags. #490. --- pom.xml | 4 ++-- src/changes/changes.xml | 1 + 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index b3c484bf9af..e13d8d9013c 100644 --- a/pom.xml +++ b/pom.xml @@ -623,8 +623,8 @@ RC1 true scm:svn:https://dist.apache.org/repos/dist/dev/commons/lang - Rob Tompkins - B6E73D84EA4FCC47166087253FAAD2CD5ECBB314 + Gary Gregory + 86fdc7e2a11262cb diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 66c37836d76..e44264254fe 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -100,6 +100,7 @@ The type attribute can be add,update,fix,remove. org.easymock:easymock 4.1 -> 4.2. org.junit-pioneer:junit-pioneer 0.4.2 -> 0.5.3. org.junit.jupiter:junit-jupiter 5.5.2 -> 5.6.0. + Use Javadoc {@code} instead of pre tags. #490. From f46f4e35c3d84b11bd30bcf8b3078b3ba4337a4d Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Mon, 17 Feb 2020 10:10:40 -0500 Subject: [PATCH 0024/3230] Don't prefix parameter names with 'p'. --- .../org/apache/commons/lang3/Functions.java | 242 +++++++++--------- 1 file changed, 121 insertions(+), 121 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/Functions.java b/src/main/java/org/apache/commons/lang3/Functions.java index e7808acc9ae..fdcabbdd9e1 100644 --- a/src/main/java/org/apache/commons/lang3/Functions.java +++ b/src/main/java/org/apache/commons/lang3/Functions.java @@ -83,67 +83,67 @@ public interface FailableCallable { public interface FailableConsumer { /** * Accepts the consumer. - * @param pObject the parameter for the consumable to accept + * @param object the parameter for the consumable to accept * @throws T if the consumer fails */ - void accept(O pObject) throws T; + void accept(O object) throws T; } @FunctionalInterface public interface FailableBiConsumer { /** * Accepts the consumer. - * @param pObject1 the first parameter for the consumable to accept - * @param pObject2 the second parameter for the consumable to accept + * @param object1 the first parameter for the consumable to accept + * @param object2 the second parameter for the consumable to accept * @throws T if the consumer fails */ - void accept(O1 pObject1, O2 pObject2) throws T; + void accept(O1 object1, O2 object2) throws T; } @FunctionalInterface public interface FailableFunction { /** * Apply the function. - * @param pInput the input for the function + * @param input the input for the function * @return the result of the function * @throws T if the function fails */ - O apply(I pInput) throws T; + O apply(I input) throws T; } @FunctionalInterface public interface FailableBiFunction { /** * Apply the function. - * @param pInput1 the first input for the function - * @param pInput2 the second input for the function + * @param input1 the first input for the function + * @param input2 the second input for the function * @return the result of the function * @throws T if the function fails */ - O apply(I1 pInput1, I2 pInput2) throws T; + O apply(I1 input1, I2 input2) throws T; } @FunctionalInterface public interface FailablePredicate { /** * Test the predicate. - * @param pObject the object to test the predicate on + * @param object the object to test the predicate on * @return the predicate's evaluation * @throws T if the predicate fails */ - boolean test(O pObject) throws T; + boolean test(O object) throws T; } @FunctionalInterface public interface FailableBiPredicate { /** * Test the predicate. - * @param pObject1 the first object to test the predicate on - * @param pObject2 the second object to test the predicate on + * @param object1 the first object to test the predicate on + * @param object2 the second object to test the predicate on * @return the predicate's evaluation * @throws T if the predicate fails */ - boolean test(O1 pObject1, O2 pObject2) throws T; + boolean test(O1 object1, O2 object2) throws T; } @FunctionalInterface @@ -159,33 +159,33 @@ public interface FailableSupplier { /** * Converts the given {@link FailableRunnable} into a standard {@link Runnable}. * - * @param pRunnable a {@code FailableRunnable} + * @param runnable a {@code FailableRunnable} * @return a standard {@code Runnable} */ - public static Runnable asRunnable(final FailableRunnable pRunnable) { - return () -> run(pRunnable); + public static Runnable asRunnable(final FailableRunnable runnable) { + return () -> run(runnable); } /** * Converts the given {@link FailableConsumer} into a standard {@link Consumer}. * * @param the type used by the consumers - * @param pConsumer a {@code FailableConsumer} + * @param consumer a {@code FailableConsumer} * @return a standard {@code Consumer} */ - public static Consumer asConsumer(final FailableConsumer pConsumer) { - return (pInput) -> accept(pConsumer, pInput); + public static Consumer asConsumer(final FailableConsumer consumer) { + return input -> accept(consumer, input); } /** * Converts the given {@link FailableCallable} into a standard {@link Callable}. * * @param the type used by the callables - * @param pCallable a {@code FailableCallable} + * @param callable a {@code FailableCallable} * @return a standard {@code Callable} */ - public static Callable asCallable(final FailableCallable pCallable) { - return () -> call(pCallable); + public static Callable asCallable(final FailableCallable callable) { + return () -> call(callable); } /** @@ -193,11 +193,11 @@ public static Callable asCallable(final FailableCallable pCallable) * * @param the type of the first argument of the consumers * @param the type of the second argument of the consumers - * @param pConsumer a failable {@code BiConsumer} + * @param consumer a failable {@code BiConsumer} * @return a standard {@code BiConsumer} */ - public static BiConsumer asBiConsumer(final FailableBiConsumer pConsumer) { - return (pInput1, pInput2) -> accept(pConsumer, pInput1, pInput2); + public static BiConsumer asBiConsumer(final FailableBiConsumer consumer) { + return (input1, input2) -> accept(consumer, input1, input2); } /** @@ -205,11 +205,11 @@ public static BiConsumer asBiConsumer(final FailableBiConsumer< * * @param the type of the input of the functions * @param the type of the output of the functions - * @param pFunction a {code FailableFunction} + * @param function a {code FailableFunction} * @return a standard {@code Function} */ - public static Function asFunction(final FailableFunction pFunction) { - return (pInput) -> apply(pFunction, pInput); + public static Function asFunction(final FailableFunction function) { + return input -> apply(function, input); } /** @@ -218,22 +218,22 @@ public static Function asFunction(final FailableFunction p * @param the type of the first argument of the input of the functions * @param the type of the second argument of the input of the functions * @param the type of the output of the functions - * @param pFunction a {@code FailableBiFunction} + * @param function a {@code FailableBiFunction} * @return a standard {@code BiFunction} */ - public static BiFunction asBiFunction(final FailableBiFunction pFunction) { - return (pInput1, pInput2) -> apply(pFunction, pInput1, pInput2); + public static BiFunction asBiFunction(final FailableBiFunction function) { + return (input1, input2) -> apply(function, input1, input2); } /** * Converts the given {@link FailablePredicate} into a standard {@link Predicate}. * * @param the type used by the predicates - * @param pPredicate a {@code FailablePredicate} + * @param predicate a {@code FailablePredicate} * @return a standard {@code Predicate} */ - public static Predicate asPredicate(final FailablePredicate pPredicate) { - return (pInput) -> test(pPredicate, pInput); + public static Predicate asPredicate(final FailablePredicate predicate) { + return input -> test(predicate, input); } /** @@ -241,32 +241,32 @@ public static Predicate asPredicate(final FailablePredicate pPredic * * @param the type of the first argument used by the predicates * @param the type of the second argument used by the predicates - * @param pPredicate a {@code FailableBiPredicate} + * @param predicate a {@code FailableBiPredicate} * @return a standard {@code BiPredicate} */ - public static BiPredicate asBiPredicate(final FailableBiPredicate pPredicate) { - return (pInput1, pInput2) -> test(pPredicate, pInput1, pInput2); + public static BiPredicate asBiPredicate(final FailableBiPredicate predicate) { + return (input1, input2) -> test(predicate, input1, input2); } /** * Converts the given {@link FailableSupplier} into a standard {@link Supplier}. * * @param the type supplied by the suppliers - * @param pSupplier a {@code FailableSupplier} + * @param supplier a {@code FailableSupplier} * @return a standard {@code Supplier} */ - public static Supplier asSupplier(final FailableSupplier pSupplier) { - return () -> get(pSupplier); + public static Supplier asSupplier(final FailableSupplier supplier) { + return () -> get(supplier); } /** * Runs a runnable and rethrows any exception as a {@link RuntimeException}. - * @param pRunnable The runnable to run + * @param runnable The runnable to run * @param the type of checked exception the runnable may throw */ - public static void run(final FailableRunnable pRunnable) { + public static void run(final FailableRunnable runnable) { try { - pRunnable.run(); + runnable.run(); } catch (final Throwable t) { throw rethrow(t); } @@ -274,14 +274,14 @@ public static void run(final FailableRunnable pRunnable /** * Calls a callable and rethrows any exception as a {@link RuntimeException}. - * @param pCallable the callable to call + * @param callable the callable to call * @param the return type of the callable * @param the type of checked exception the callable may throw * @return the value returned from the callable */ - public static O call(final FailableCallable pCallable) { + public static O call(final FailableCallable callable) { try { - return pCallable.call(); + return callable.call(); } catch (final Throwable t) { throw rethrow(t); } @@ -289,14 +289,14 @@ public static O call(final FailableCallable pCall /** * Consumes a consumer and rethrows any exception as a {@link RuntimeException}. - * @param pConsumer the consumer to consume - * @param pObject the object to consume by {@code pConsumer} + * @param consumer the consumer to consume + * @param object the object to consume by {@code consumer} * @param the type the consumer accepts * @param the type of checked exception the consumer may throw */ - public static void accept(final FailableConsumer pConsumer, final O pObject) { + public static void accept(final FailableConsumer consumer, final O object) { try { - pConsumer.accept(pObject); + consumer.accept(object); } catch (final Throwable t) { throw rethrow(t); } @@ -304,16 +304,16 @@ public static void accept(final FailableConsumer /** * Consumes a consumer and rethrows any exception as a {@link RuntimeException}. - * @param pConsumer the consumer to consume - * @param pObject1 the first object to consume by {@code pConsumer} - * @param pObject2 the second object to consume by {@code pConsumer} + * @param consumer the consumer to consume + * @param object1 the first object to consume by {@code consumer} + * @param object2 the second object to consume by {@code consumer} * @param the type of the first argument the consumer accepts * @param the type of the second argument the consumer accepts * @param the type of checked exception the consumer may throw */ - public static void accept(final FailableBiConsumer pConsumer, final O1 pObject1, final O2 pObject2) { + public static void accept(final FailableBiConsumer consumer, final O1 object1, final O2 object2) { try { - pConsumer.accept(pObject1, pObject2); + consumer.accept(object1, object2); } catch (final Throwable t) { throw rethrow(t); } @@ -321,16 +321,16 @@ public static void accept(final FailableBiConsumer /** * Applies a function and rethrows any exception as a {@link RuntimeException}. - * @param pFunction the function to apply - * @param pInput the input to apply {@code pFunction} on + * @param function the function to apply + * @param input the input to apply {@code function} on * @param the type of the argument the function accepts * @param the return type of the function * @param the type of checked exception the function may throw * @return the value returned from the function */ - public static O apply(final FailableFunction pFunction, final I pInput) { + public static O apply(final FailableFunction function, final I input) { try { - return pFunction.apply(pInput); + return function.apply(input); } catch (final Throwable t) { throw rethrow(t); } @@ -338,18 +338,18 @@ public static O apply(final FailableFunction the type of the first argument the function accepts * @param the type of the second argument the function accepts * @param the return type of the function * @param the type of checked exception the function may throw * @return the value returned from the function */ - public static O apply(final FailableBiFunction pFunction, final I1 pInput1, final I2 pInput2) { + public static O apply(final FailableBiFunction function, final I1 input1, final I2 input2) { try { - return pFunction.apply(pInput1, pInput2); + return function.apply(input1, input2); } catch (final Throwable t) { throw rethrow(t); } @@ -357,15 +357,15 @@ public static O apply(final FailableBiFunction< /** * Tests a predicate and rethrows any exception as a {@link RuntimeException}. - * @param pPredicate the predicate to test - * @param pObject the input to test by {@code pPredicate} + * @param predicate the predicate to test + * @param object the input to test by {@code predicate} * @param the type of argument the predicate tests * @param the type of checked exception the predicate may throw * @return the boolean value returned by the predicate */ - public static boolean test(final FailablePredicate pPredicate, final O pObject) { + public static boolean test(final FailablePredicate predicate, final O object) { try { - return pPredicate.test(pObject); + return predicate.test(object); } catch (final Throwable t) { throw rethrow(t); } @@ -373,17 +373,17 @@ public static boolean test(final FailablePredicate the type of the first argument the predicate tests * @param the type of the second argument the predicate tests * @param the type of checked exception the predicate may throw * @return the boolean value returned by the predicate */ - public static boolean test(final FailableBiPredicate pPredicate, final O1 pObject1, final O2 pObject2) { + public static boolean test(final FailableBiPredicate predicate, final O1 object1, final O2 object2) { try { - return pPredicate.test(pObject1, pObject2); + return predicate.test(object1, object2); } catch (final Throwable t) { throw rethrow(t); } @@ -391,14 +391,14 @@ public static boolean test(final FailableBiPredica /** * Invokes the supplier, and returns the result. - * @param pSupplier The supplier to invoke. + * @param supplier The supplier to invoke. * @param The suppliers output type. * @param The type of checked exception, which the supplier can throw. * @return The object, which has been created by the supplier */ - public static O get(final FailableSupplier pSupplier) { + public static O get(final FailableSupplier supplier) { try { - return pSupplier.get(); + return supplier.get(); } catch (final Throwable t) { throw rethrow(t); } @@ -411,13 +411,13 @@ public static O get(final FailableSupplier pSuppl * {@link FailablePredicate}, {@link FailableFunction}, and * {@link FailableConsumer} may be applied, rather than * {@link Predicate}, {@link Function}, {@link Consumer}, etc. - * @param pStream The stream, which is being converted into a + * @param stream The stream, which is being converted into a * {@link FailableStream}. * @param The streams element type. * @return The created {@link FailableStream}. */ - public static FailableStream stream(final Stream pStream) { - return new FailableStream<>(pStream); + public static FailableStream stream(final Stream stream) { + return new FailableStream<>(stream); } /** @@ -425,24 +425,24 @@ public static FailableStream stream(final Stream pStream) { * The {@link FailableStream} consists of the collections * elements. Shortcut for *
-     *   Functions.stream(pCollection.stream());
+     *   Functions.stream(collection.stream());
      * 
- * @param pCollection The collection, which is being converted into a + * @param collection The collection, which is being converted into a * {@link FailableStream}. * @param The collections element type. (In turn, the result * streams element type.) * @return The created {@link FailableStream}. */ - public static FailableStream stream(final Collection pCollection) { - return new FailableStream<>(pCollection.stream()); + public static FailableStream stream(final Collection collection) { + return new FailableStream<>(collection.stream()); } /** * A simple try-with-resources implementation, that can be used, if your * objects do not implement the {@link AutoCloseable} interface. The method - * executes the {@code pAction}. The method guarantees, that all - * the {@code pResources} are being executed, in the given order, afterwards, + * executes the {@code action}. The method guarantees, that all + * the {@code resources} are being executed, in the given order, afterwards, * and regardless of success, or failure. If either the original action, or * any of the resource action fails, then the first failure (aka * {@link Throwable} is rethrown. Example use: @@ -450,39 +450,39 @@ public static FailableStream stream(final Collection pCollection) { * final FileInputStream fis = new FileInputStream("my.file"); * Functions.tryWithResources(useInputStream(fis), null, () -> fis.close()); * } - * @param pAction The action to execute. This object will always + * @param action The action to execute. This object will always * be invoked. - * @param pErrorHandler An optional error handler, which will be invoked finally, + * @param errorHandler An optional error handler, which will be invoked finally, * if any error occurred. The error handler will receive the first * error, aka {@link Throwable}. - * @param pResources The resource actions to execute. All resource + * @param resources The resource actions to execute. All resource * actions will be invoked, in the given order. A resource action is an * instance of {@link FailableRunnable}, which will be executed. * @see #tryWithResources(FailableRunnable, FailableRunnable...) */ @SafeVarargs - public static void tryWithResources(final FailableRunnable pAction, - final FailableConsumer pErrorHandler, - final FailableRunnable... pResources) { - final FailableConsumer errorHandler; - if (pErrorHandler == null) { - errorHandler = (t) -> rethrow(t); + public static void tryWithResources(final FailableRunnable action, + final FailableConsumer errorHandler, + final FailableRunnable... resources) { + final FailableConsumer actualErrorHandler; + if (errorHandler == null) { + actualErrorHandler = (t) -> rethrow(t); } else { - errorHandler = pErrorHandler; + actualErrorHandler = errorHandler; } - if (pResources != null) { - for (final FailableRunnable failableRunnable : pResources) { + if (resources != null) { + for (final FailableRunnable failableRunnable : resources) { Objects.requireNonNull(failableRunnable, "runnable"); } } Throwable th = null; try { - pAction.run(); + action.run(); } catch (final Throwable t) { th = t; } - if (pResources != null) { - for (final FailableRunnable runnable : pResources) { + if (resources != null) { + for (final FailableRunnable runnable : resources) { try { runnable.run(); } catch (final Throwable t) { @@ -494,7 +494,7 @@ public static void tryWithResources(final FailableRunnable } if (th != null) { try { - errorHandler.accept(th); + actualErrorHandler.accept(th); } catch (final Throwable t) { throw rethrow(t); } @@ -504,8 +504,8 @@ public static void tryWithResources(final FailableRunnable /** * A simple try-with-resources implementation, that can be used, if your * objects do not implement the {@link AutoCloseable} interface. The method - * executes the {@code pAction}. The method guarantees, that all - * the {@code pResources} are being executed, in the given order, afterwards, + * executes the {@code action}. The method guarantees, that all + * the {@code resources} are being executed, in the given order, afterwards, * and regardless of success, or failure. If either the original action, or * any of the resource action fails, then the first failure (aka * {@link Throwable} is rethrown. Example use: @@ -513,17 +513,17 @@ public static void tryWithResources(final FailableRunnable * final FileInputStream fis = new FileInputStream("my.file"); * Functions.tryWithResources(useInputStream(fis), () -> fis.close()); * } - * @param pAction The action to execute. This object will always + * @param action The action to execute. This object will always * be invoked. - * @param pResources The resource actions to execute. All resource + * @param resources The resource actions to execute. All resource * actions will be invoked, in the given order. A resource action is an * instance of {@link FailableRunnable}, which will be executed. * @see #tryWithResources(FailableRunnable, FailableConsumer, FailableRunnable...) */ @SafeVarargs - public static void tryWithResources(final FailableRunnable pAction, - final FailableRunnable... pResources) { - tryWithResources(pAction, null, pResources); + public static void tryWithResources(final FailableRunnable action, + final FailableRunnable... resources) { + tryWithResources(action, null, resources); } /** @@ -542,23 +542,23 @@ public static void tryWithResources(final FailableRunnable * * *

instead of just calling the method. This pattern may help the Java compiler to - * recognize that at that point an exception will be thrown and the code flow + * recognize that at that oint an exception will be thrown and the code flow * analysis will not demand otherwise mandatory commands that could follow the * method call, like a {@code return} statement from a value returning method.

* - * @param pThrowable The throwable to rethrow possibly wrapped into an unchecked exception + * @param throwable The throwable to rethrow ossibly wrapped into an unchecked exception * @return Never returns anything, this method never terminates normally. */ - public static RuntimeException rethrow(final Throwable pThrowable) { - Objects.requireNonNull(pThrowable, "pThrowable"); - if (pThrowable instanceof RuntimeException) { - throw (RuntimeException) pThrowable; - } else if (pThrowable instanceof Error) { - throw (Error) pThrowable; - } else if (pThrowable instanceof IOException) { - throw new UncheckedIOException((IOException) pThrowable); + public static RuntimeException rethrow(final Throwable throwable) { + Objects.requireNonNull(throwable, "throwable"); + if (throwable instanceof RuntimeException) { + throw (RuntimeException) throwable; + } else if (throwable instanceof Error) { + throw (Error) throwable; + } else if (throwable instanceof IOException) { + throw new UncheckedIOException((IOException) throwable); } else { - throw new UndeclaredThrowableException(pThrowable); + throw new UndeclaredThrowableException(throwable); } } } From 473c050cc9e52931dfbb1c8430a4093454147ebb Mon Sep 17 00:00:00 2001 From: Peter Verhas Date: Mon, 17 Feb 2020 16:13:27 +0100 Subject: [PATCH 0025/3230] Exceptionutilstest to 100p (#486) * unit tests were added to top up the test coverage of ExceptionUtils to 100% * unit tests were added to top up the test coverage of ExceptionUtils to 100% * unit tests were added to top up the test coverage of ExceptionUtils to 100% * unit tests were added to top up the test coverage of ExceptionUtils to 100% * unit tests were added to top up the test coverage of ExceptionUtils to 100% --- .../lang3/exception/ExceptionUtilsTest.java | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/src/test/java/org/apache/commons/lang3/exception/ExceptionUtilsTest.java b/src/test/java/org/apache/commons/lang3/exception/ExceptionUtilsTest.java index fb7a9fbf317..68354a47675 100644 --- a/src/test/java/org/apache/commons/lang3/exception/ExceptionUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/exception/ExceptionUtilsTest.java @@ -16,6 +16,7 @@ */ package org.apache.commons.lang3.exception; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; @@ -35,6 +36,7 @@ import org.apache.commons.lang3.test.NotVisibleExceptionFactory; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; /** @@ -699,4 +701,34 @@ public void testWrapAndUnwrapThrowable() { final Throwable t = assertThrows(Throwable.class, () -> ExceptionUtils.wrapAndThrow(new TestThrowable())); assertTrue(ExceptionUtils.hasCause(t, TestThrowable.class)); } + + @Test + @DisplayName("getStackFrames returns the string array of the stack frames when there is a real exception") + public void testgetStackFramesNullArg() { + final String[] actual = ExceptionUtils.getStackFrames((Throwable) null); + assertEquals(0, actual.length); + } + + @Test + @DisplayName("getStackFrames returns empty string array when the argument is null") + public void testgetStackFramesHappyPath() { + final String[] actual = ExceptionUtils.getStackFrames(new Throwable() { + // provide static stack trace to make test stable + public void printStackTrace(PrintWriter s) { + s.write("org.apache.commons.lang3.exception.ExceptionUtilsTest$1\n" + + "\tat org.apache.commons.lang3.exception.ExceptionUtilsTest.testgetStackFramesGappyPath(ExceptionUtilsTest.java:706)\n" + + "\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n" + + "\tat com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)\n" + + "\tat com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)\n"); + } + }); + + assertArrayEquals(new String[]{ + "org.apache.commons.lang3.exception.ExceptionUtilsTest$1", + "\tat org.apache.commons.lang3.exception.ExceptionUtilsTest.testgetStackFramesGappyPath(ExceptionUtilsTest.java:706)", + "\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)", + "\tat com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)", + "\tat com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)" + }, actual); + } } From d3112e4306ef1008673f0e8f0f087bdf273bed0b Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Mon, 17 Feb 2020 10:19:17 -0500 Subject: [PATCH 0026/3230] ExceptionUtilsTest to 100% #486. --- src/changes/changes.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index e44264254fe..dc315a962ef 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -101,6 +101,7 @@ The type attribute can be add,update,fix,remove. org.junit-pioneer:junit-pioneer 0.4.2 -> 0.5.3. org.junit.jupiter:junit-jupiter 5.5.2 -> 5.6.0. Use Javadoc {@code} instead of pre tags. #490. + ExceptionUtilsTest to 100% #486.
From 553a0474ea11a9b61a8de618a3512f29f5a17368 Mon Sep 17 00:00:00 2001 From: Christian Franzen Date: Mon, 17 Feb 2020 16:29:34 +0100 Subject: [PATCH 0027/3230] LANG-1433: MethodUtils will throw a NPE if invokeMethod() is called for a var-args method (#407) * LANG-1433: MethodUtils will throw a NPE if invokeMethod() is called for a var-args method with null parameter value * LANG-1433: Result of invokeMethod() is not deterministic for overloaded methods that can not be uniquly resolved from parameter types * LANG-1433: Fixed checkstyle errors --- .../commons/lang3/reflect/MemberUtils.java | 5 +- .../commons/lang3/reflect/MethodUtils.java | 47 +++++++++++++------ .../lang3/reflect/MethodUtilsTest.java | 16 +++++++ 3 files changed, 53 insertions(+), 15 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/reflect/MemberUtils.java b/src/main/java/org/apache/commons/lang3/reflect/MemberUtils.java index d7e2bd2c936..73fa2f1c03d 100644 --- a/src/main/java/org/apache/commons/lang3/reflect/MemberUtils.java +++ b/src/main/java/org/apache/commons/lang3/reflect/MemberUtils.java @@ -162,7 +162,7 @@ private static float getTotalTransformationCost(final Class[] srcArgs, final // When isVarArgs is true, srcArgs and dstArgs may differ in length. // There are two special cases to consider: final boolean noVarArgsPassed = srcArgs.length < destArgs.length; - final boolean explicitArrayForVarags = srcArgs.length == destArgs.length && srcArgs[srcArgs.length-1].isArray(); + final boolean explicitArrayForVarags = srcArgs.length == destArgs.length && srcArgs[srcArgs.length-1] != null && srcArgs[srcArgs.length-1].isArray(); final float varArgsCost = 0.001f; final Class destClass = destArgs[destArgs.length-1].getComponentType(); @@ -227,6 +227,9 @@ private static float getObjectTransformationCost(Class srcClass, final Class< * @return The cost of promoting the primitive */ private static float getPrimitivePromotionCost(final Class srcClass, final Class destClass) { + if (srcClass == null) { + return 1.5f; + } float cost = 0.0f; Class cls = srcClass; if (!cls.isPrimitive()) { diff --git a/src/main/java/org/apache/commons/lang3/reflect/MethodUtils.java b/src/main/java/org/apache/commons/lang3/reflect/MethodUtils.java index 8ebc790a46d..c014450b082 100644 --- a/src/main/java/org/apache/commons/lang3/reflect/MethodUtils.java +++ b/src/main/java/org/apache/commons/lang3/reflect/MethodUtils.java @@ -25,6 +25,8 @@ import java.lang.reflect.TypeVariable; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; @@ -59,6 +61,13 @@ */ public class MethodUtils { + private static final Comparator METHOD_BY_SIGNATURE = new Comparator() { + @Override + public int compare(final Method m1, final Method m2) { + return m1.toString ().compareTo (m2.toString ()); + } + }; + /** *

{@link MethodUtils} instances should NOT be constructed in standard programming. * Instead, the class should be used as @@ -462,8 +471,8 @@ private static Object[] toVarArgs(final Method method, Object[] args) { * @since 3.5 */ static Object[] getVarArgs(final Object[] args, final Class[] methodParameterTypes) { - if (args.length == methodParameterTypes.length - && args[args.length - 1].getClass().equals(methodParameterTypes[methodParameterTypes.length - 1])) { + if (args.length == methodParameterTypes.length && (args[args.length - 1] == null || + args[args.length - 1].getClass().equals(methodParameterTypes[methodParameterTypes.length - 1]))) { // The args array is already in the canonical form for the method. return args; } @@ -679,20 +688,28 @@ public static Method getMatchingAccessibleMethod(final Class cls, } catch (final NoSuchMethodException e) { // NOPMD - Swallow the exception } // search through all methods - Method bestMatch = null; final Method[] methods = cls.getMethods(); + final List matchingMethods = new ArrayList<>(); for (final Method method : methods) { // compare name and parameters if (method.getName().equals(methodName) && MemberUtils.isMatchingMethod(method, parameterTypes)) { - // get accessible version of method - final Method accessibleMethod = getAccessibleMethod(method); - if (accessibleMethod != null && (bestMatch == null || MemberUtils.compareMethodFit( - accessibleMethod, - bestMatch, - parameterTypes) < 0)) { - bestMatch = accessibleMethod; - } + matchingMethods.add (method); + } + } + + // Sort methods by signature to force deterministic result + Collections.sort (matchingMethods, METHOD_BY_SIGNATURE); + + Method bestMatch = null; + for (final Method method : matchingMethods) { + // get accessible version of method + final Method accessibleMethod = getAccessibleMethod(method); + if (accessibleMethod != null && (bestMatch == null || MemberUtils.compareMethodFit( + accessibleMethod, + bestMatch, + parameterTypes) < 0)) { + bestMatch = accessibleMethod; } } if (bestMatch != null) { @@ -703,10 +720,12 @@ public static Method getMatchingAccessibleMethod(final Class cls, final Class[] methodParameterTypes = bestMatch.getParameterTypes(); final Class methodParameterComponentType = methodParameterTypes[methodParameterTypes.length - 1].getComponentType(); final String methodParameterComponentTypeName = ClassUtils.primitiveToWrapper(methodParameterComponentType).getName(); - final String parameterTypeName = parameterTypes[parameterTypes.length - 1].getName(); - final String parameterTypeSuperClassName = parameterTypes[parameterTypes.length - 1].getSuperclass().getName(); - if (!methodParameterComponentTypeName.equals(parameterTypeName) + final Class lastParameterType = parameterTypes[parameterTypes.length - 1]; + final String parameterTypeName = (lastParameterType==null) ? null : lastParameterType.getName(); + final String parameterTypeSuperClassName = (lastParameterType==null) ? null : lastParameterType.getSuperclass().getName(); + + if (parameterTypeName!= null && parameterTypeSuperClassName != null && !methodParameterComponentTypeName.equals(parameterTypeName) && !methodParameterComponentTypeName.equals(parameterTypeSuperClassName)) { return null; } diff --git a/src/test/java/org/apache/commons/lang3/reflect/MethodUtilsTest.java b/src/test/java/org/apache/commons/lang3/reflect/MethodUtilsTest.java index 9df5a14f37f..168bc2ae4e2 100644 --- a/src/test/java/org/apache/commons/lang3/reflect/MethodUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/reflect/MethodUtilsTest.java @@ -446,6 +446,22 @@ public void testInvokeMethod() throws Exception { MethodUtils.invokeMethod(testBean, "varOverloadEcho", 17, 23, 42)); } + @Test + public void testInvokeMethod_VarArgsWithNullValues() throws Exception { + assertEquals("String...", MethodUtils.invokeMethod(testBean, "varOverload", + "a", null, "c")); + assertEquals("String...", MethodUtils.invokeMethod(testBean, "varOverload", + "a", "b", null)); + } + + @Test + public void testInvokeMethod_VarArgsNotUniqueResolvable() throws Exception { + assertEquals("Boolean...", MethodUtils.invokeMethod(testBean, "varOverload", + new Object[] {null})); + assertEquals("Object...", MethodUtils.invokeMethod(testBean, "varOverload", + (Object[]) null)); + } + @Test public void testInvokeExactMethod() throws Exception { assertEquals("foo()", MethodUtils.invokeExactMethod(testBean, "foo", From a3edc1b6a6e25e3432b7cdb518219af16a45d55e Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Mon, 17 Feb 2020 10:32:12 -0500 Subject: [PATCH 0028/3230] [LANG-1433] MethodUtils will throw a NPE if invokeMethod() is called for a var-args method #407. --- src/changes/changes.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index dc315a962ef..611d025bef3 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -102,6 +102,7 @@ The type attribute can be add,update,fix,remove. org.junit.jupiter:junit-jupiter 5.5.2 -> 5.6.0. Use Javadoc {@code} instead of pre tags. #490. ExceptionUtilsTest to 100% #486. + MethodUtils will throw a NPE if invokeMethod() is called for a var-args method #407. From bd147ae86c646cb6b03235ad924e35c42cec842c Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Mon, 17 Feb 2020 13:13:57 -0500 Subject: [PATCH 0029/3230] Update build plugins and Javadoc link. maven-pmd-plugin 3.12.0 -> 3.13.0. maven-checkstyle-plugin -> 3.1.0 -> 3.1.1. jacoco 0.8.4 -> 0.8.5. commons.javadoc.version -> 3.1.0 -> 3.1.1. commons.japicmp.version -> 0.14.1 -> 0.14.3. ommons.surefire.version 3.0.0-M3 -> 3.0.0-M4. Link to Java 8 Javadoc. --- pom.xml | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/pom.xml b/pom.xml index e13d8d9013c..88b8208ff98 100644 --- a/pom.xml +++ b/pom.xml @@ -599,7 +599,7 @@ site-content utf-8 - 3.1.0 + 3.1.1 8.29 src/site/resources/checkstyle @@ -610,13 +610,13 @@ 1.21 benchmarks - 0.8.4 - 3.0.0-M3 - 3.1.0 + 0.8.5 + 3.0.0-M4 + 3.1.1 false - 0.14.1 + 0.14.3 3.9 @@ -665,7 +665,7 @@ utf-8 true - http://docs.oracle.com/javase/7/docs/api/ + https://docs.oracle.com/javase/8/docs/api/ http://docs.oracle.com/javaee/6/api/ @@ -805,7 +805,7 @@ maven-pmd-plugin - 3.12.0 + 3.13.0 ${maven.compiler.target} From 179e8f4775add4236ad76595e5eaed83f2c3e1b6 Mon Sep 17 00:00:00 2001 From: Peter Verhas Date: Wed, 19 Feb 2020 06:58:33 +0100 Subject: [PATCH 0030/3230] try to cleanup merging (#493) --- .../org/apache/commons/lang3/Functions.java | 48 ++++--------------- 1 file changed, 10 insertions(+), 38 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/Functions.java b/src/main/java/org/apache/commons/lang3/Functions.java index fdcabbdd9e1..4f580b792cb 100644 --- a/src/main/java/org/apache/commons/lang3/Functions.java +++ b/src/main/java/org/apache/commons/lang3/Functions.java @@ -280,11 +280,7 @@ public static void run(final FailableRunnable runnable) * @return the value returned from the callable */ public static O call(final FailableCallable callable) { - try { - return callable.call(); - } catch (final Throwable t) { - throw rethrow(t); - } + return get(callable::call); } /** @@ -295,11 +291,7 @@ public static O call(final FailableCallable calla * @param the type of checked exception the consumer may throw */ public static void accept(final FailableConsumer consumer, final O object) { - try { - consumer.accept(object); - } catch (final Throwable t) { - throw rethrow(t); - } + run(() -> consumer.accept(object)); } /** @@ -312,11 +304,7 @@ public static void accept(final FailableConsumer * @param the type of checked exception the consumer may throw */ public static void accept(final FailableBiConsumer consumer, final O1 object1, final O2 object2) { - try { - consumer.accept(object1, object2); - } catch (final Throwable t) { - throw rethrow(t); - } + run(() -> consumer.accept(object1, object2)); } /** @@ -329,11 +317,7 @@ public static void accept(final FailableBiConsumer * @return the value returned from the function */ public static O apply(final FailableFunction function, final I input) { - try { - return function.apply(input); - } catch (final Throwable t) { - throw rethrow(t); - } + return get(() -> function.apply(input)); } /** @@ -348,11 +332,7 @@ public static O apply(final FailableFunction O apply(final FailableBiFunction function, final I1 input1, final I2 input2) { - try { - return function.apply(input1, input2); - } catch (final Throwable t) { - throw rethrow(t); - } + return get(() -> function.apply(input1, input2)); } /** @@ -364,11 +344,7 @@ public static O apply(final FailableBiFunction< * @return the boolean value returned by the predicate */ public static boolean test(final FailablePredicate predicate, final O object) { - try { - return predicate.test(object); - } catch (final Throwable t) { - throw rethrow(t); - } + return get(() -> predicate.test(object)); } /** @@ -382,11 +358,7 @@ public static boolean test(final FailablePredicate boolean test(final FailableBiPredicate predicate, final O1 object1, final O2 object2) { - try { - return predicate.test(object1, object2); - } catch (final Throwable t) { - throw rethrow(t); - } + return get(() -> predicate.test(object1, object2)); } /** @@ -466,7 +438,7 @@ public static void tryWithResources(final FailableRunnable final FailableRunnable... resources) { final FailableConsumer actualErrorHandler; if (errorHandler == null) { - actualErrorHandler = (t) -> rethrow(t); + actualErrorHandler = Functions::rethrow; } else { actualErrorHandler = errorHandler; } @@ -482,7 +454,7 @@ public static void tryWithResources(final FailableRunnable th = t; } if (resources != null) { - for (final FailableRunnable runnable : resources) { + for (final FailableRunnable runnable : resources) { try { runnable.run(); } catch (final Throwable t) { @@ -542,7 +514,7 @@ public static void tryWithResources(final FailableRunnable * * *

instead of just calling the method. This pattern may help the Java compiler to - * recognize that at that oint an exception will be thrown and the code flow + * recognize that at that point an exception will be thrown and the code flow * analysis will not demand otherwise mandatory commands that could follow the * method call, like a {@code return} statement from a value returning method.

* From eb8d069089364e396e37ed5273cf7710e41eb06d Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Wed, 19 Feb 2020 01:00:08 -0500 Subject: [PATCH 0031/3230] Reuse own code in Functions.java #493. --- src/changes/changes.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 611d025bef3..7cb0f965058 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -103,6 +103,7 @@ The type attribute can be add,update,fix,remove. Use Javadoc {@code} instead of pre tags. #490. ExceptionUtilsTest to 100% #486. MethodUtils will throw a NPE if invokeMethod() is called for a var-args method #407. + Reuse own code in Functions.java #493.
From f4c2ed4995d19c595ec0bf5c49d210df9046fda9 Mon Sep 17 00:00:00 2001 From: Michele Preti Date: Sat, 22 Feb 2020 14:28:33 +0100 Subject: [PATCH 0032/3230] LANG-1518 - fix searchSupers for generic classes (#494) * fix searchSupers for generic classes * fix checkstyle --- .../commons/lang3/reflect/MethodUtils.java | 18 +++++++----------- .../commons/lang3/reflect/MethodUtilsTest.java | 18 ++++++++++++++++++ .../lang3/reflect/testbed/GenericParent.java | 6 ++++++ .../testbed/StringParameterizedChild.java | 15 +++++++++++++++ 4 files changed, 46 insertions(+), 11 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/reflect/MethodUtils.java b/src/main/java/org/apache/commons/lang3/reflect/MethodUtils.java index c014450b082..f724c5c82d7 100644 --- a/src/main/java/org/apache/commons/lang3/reflect/MethodUtils.java +++ b/src/main/java/org/apache/commons/lang3/reflect/MethodUtils.java @@ -974,17 +974,13 @@ public static
A getAnnotation(final Method method, final final Class mcls = method.getDeclaringClass(); final List> classes = getAllSuperclassesAndInterfaces(mcls); for (final Class acls : classes) { - Method equivalentMethod; - try { - equivalentMethod = (ignoreAccess ? acls.getDeclaredMethod(method.getName(), method.getParameterTypes()) - : acls.getMethod(method.getName(), method.getParameterTypes())); - } catch (final NoSuchMethodException e) { - // if not found, just keep searching - continue; - } - annotation = equivalentMethod.getAnnotation(annotationCls); - if (annotation != null) { - break; + Method equivalentMethod = (ignoreAccess ? MethodUtils.getMatchingMethod(acls, method.getName(), method.getParameterTypes()) + : MethodUtils.getMatchingAccessibleMethod(acls, method.getName(), method.getParameterTypes())); + if (equivalentMethod != null) { + annotation = equivalentMethod.getAnnotation(annotationCls); + if (annotation != null) { + break; + } } } } diff --git a/src/test/java/org/apache/commons/lang3/reflect/MethodUtilsTest.java b/src/test/java/org/apache/commons/lang3/reflect/MethodUtilsTest.java index 168bc2ae4e2..ab40b22df90 100644 --- a/src/test/java/org/apache/commons/lang3/reflect/MethodUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/reflect/MethodUtilsTest.java @@ -799,6 +799,15 @@ public void testGetAnnotationSearchSupersAndIgnoreAccess() throws NoSuchMethodEx Annotated.class, true, true)); assertNotNull(MethodUtils.getAnnotation(PublicChild.class.getMethod("publicAnnotatedMethod"), Annotated.class, true, true)); + + assertNull(MethodUtils.getAnnotation(StringParameterizedChild.class.getMethod("parentNotAnnotatedMethod", String.class), + Annotated.class, true, true)); + assertNotNull(MethodUtils.getAnnotation(StringParameterizedChild.class.getMethod("parentProtectedAnnotatedMethod", String.class), + Annotated.class, true, true)); + assertNotNull(MethodUtils.getAnnotation(StringParameterizedChild.class.getDeclaredMethod("privateAnnotatedMethod", String.class), + Annotated.class, true, true)); + assertNotNull(MethodUtils.getAnnotation(StringParameterizedChild.class.getMethod("publicAnnotatedMethod", String.class), + Annotated.class, true, true)); } @Test @@ -827,6 +836,15 @@ public void testGetAnnotationSearchSupersButNotIgnoreAccess() throws NoSuchMetho Annotated.class, true, false)); assertNotNull(MethodUtils.getAnnotation(PublicChild.class.getMethod("publicAnnotatedMethod"), Annotated.class, true, false)); + + assertNull(MethodUtils.getAnnotation(StringParameterizedChild.class.getMethod("parentNotAnnotatedMethod", String.class), + Annotated.class, true, false)); + assertNull(MethodUtils.getAnnotation(StringParameterizedChild.class.getMethod("parentProtectedAnnotatedMethod", String.class), + Annotated.class, true, false)); + assertNull(MethodUtils.getAnnotation(StringParameterizedChild.class.getDeclaredMethod("privateAnnotatedMethod", String.class), + Annotated.class, true, false)); + assertNotNull(MethodUtils.getAnnotation(StringParameterizedChild.class.getMethod("publicAnnotatedMethod", String.class), + Annotated.class, true, false)); } @Test diff --git a/src/test/java/org/apache/commons/lang3/reflect/testbed/GenericParent.java b/src/test/java/org/apache/commons/lang3/reflect/testbed/GenericParent.java index f848567b9b3..73b1446f0f8 100644 --- a/src/test/java/org/apache/commons/lang3/reflect/testbed/GenericParent.java +++ b/src/test/java/org/apache/commons/lang3/reflect/testbed/GenericParent.java @@ -25,4 +25,10 @@ public class GenericParent implements GenericConsumer { public void consume(final T t) { } + @Annotated + protected void parentProtectedAnnotatedMethod(final T t) { + } + + public void parentNotAnnotatedMethod(final T t) { + } } diff --git a/src/test/java/org/apache/commons/lang3/reflect/testbed/StringParameterizedChild.java b/src/test/java/org/apache/commons/lang3/reflect/testbed/StringParameterizedChild.java index dd285bc4fe5..36b7156b878 100644 --- a/src/test/java/org/apache/commons/lang3/reflect/testbed/StringParameterizedChild.java +++ b/src/test/java/org/apache/commons/lang3/reflect/testbed/StringParameterizedChild.java @@ -24,4 +24,19 @@ public class StringParameterizedChild extends GenericParent { public void consume(final String t) { super.consume(t); } + + @Override + public void parentProtectedAnnotatedMethod(final String t) { + } + + public void parentNotAnnotatedMethod(final String t) { + } + + @Annotated + private void privateAnnotatedMethod(final String t) { + } + + @Annotated + public void publicAnnotatedMethod(final String t) { + } } From b8499c108e5665a87248f2dfa6d8c8c459681748 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sat, 22 Feb 2020 08:32:02 -0500 Subject: [PATCH 0033/3230] [LANG-1518] MethodUtils.getAnnotation() with searchSupers = true does not work if super is generic #494. --- src/changes/changes.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 7cb0f965058..6c286f69e8a 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -104,6 +104,7 @@ The type attribute can be add,update,fix,remove. ExceptionUtilsTest to 100% #486. MethodUtils will throw a NPE if invokeMethod() is called for a var-args method #407. Reuse own code in Functions.java #493. + MethodUtils.getAnnotation() with searchSupers = true does not work if super is generic #494. From 62d5c1037f6ff068128ce1fe164a6d2e6be46bea Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sat, 22 Feb 2020 08:39:18 -0500 Subject: [PATCH 0034/3230] org.junit-pioneer:junit-pioneer 0.5.3 -> 0.5.4. --- pom.xml | 2 +- src/changes/changes.xml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 88b8208ff98..19472d3bdb1 100644 --- a/pom.xml +++ b/pom.xml @@ -522,7 +522,7 @@ org.junit-pioneer junit-pioneer - 0.5.3 + 0.5.4 test diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 6c286f69e8a..f4fd3b6a1a8 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -98,7 +98,7 @@ The type attribute can be add,update,fix,remove. ObjectUtils: Get first non-null supplier value. Added the Streams class, and Functions.stream() as an accessor thereof. org.easymock:easymock 4.1 -> 4.2. - org.junit-pioneer:junit-pioneer 0.4.2 -> 0.5.3. + org.junit-pioneer:junit-pioneer 0.4.2 -> 0.5.4. org.junit.jupiter:junit-jupiter 5.5.2 -> 5.6.0. Use Javadoc {@code} instead of pre tags. #490. ExceptionUtilsTest to 100% #486. From e182888fb7897c9c21740aa6eeb471a57eb2e6da Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sat, 22 Feb 2020 08:49:44 -0500 Subject: [PATCH 0035/3230] Fix weird formatting. --- .../commons/lang3/math/NumberUtilsTest.java | 38 +++++++++---------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/src/test/java/org/apache/commons/lang3/math/NumberUtilsTest.java b/src/test/java/org/apache/commons/lang3/math/NumberUtilsTest.java index 7485842c26f..5e5c554e890 100644 --- a/src/test/java/org/apache/commons/lang3/math/NumberUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/math/NumberUtilsTest.java @@ -1447,25 +1447,25 @@ private void compareIsNumberWithCreateNumber(final String val, final boolean exp @Test public void testIsParsable() { - assertFalse( NumberUtils.isParsable(null) ); - assertFalse( NumberUtils.isParsable("") ); - assertFalse( NumberUtils.isParsable("0xC1AB") ); - assertFalse( NumberUtils.isParsable("65CBA2") ); - assertFalse( NumberUtils.isParsable("pendro") ); - assertFalse( NumberUtils.isParsable("64, 2") ); - assertFalse( NumberUtils.isParsable("64.2.2") ); - assertFalse( NumberUtils.isParsable("64.") ); - assertFalse( NumberUtils.isParsable("64L") ); - assertFalse( NumberUtils.isParsable("-") ); - assertFalse( NumberUtils.isParsable("--2") ); - assertTrue( NumberUtils.isParsable("64.2") ); - assertTrue( NumberUtils.isParsable("64") ); - assertTrue( NumberUtils.isParsable("018") ); - assertTrue( NumberUtils.isParsable(".18") ); - assertTrue( NumberUtils.isParsable("-65") ); - assertTrue( NumberUtils.isParsable("-018") ); - assertTrue( NumberUtils.isParsable("-018.2") ); - assertTrue( NumberUtils.isParsable("-.236") ); + assertFalse(NumberUtils.isParsable(null)); + assertFalse(NumberUtils.isParsable("")); + assertFalse(NumberUtils.isParsable("0xC1AB")); + assertFalse(NumberUtils.isParsable("65CBA2")); + assertFalse(NumberUtils.isParsable("pendro")); + assertFalse(NumberUtils.isParsable("64, 2")); + assertFalse(NumberUtils.isParsable("64.2.2")); + assertFalse(NumberUtils.isParsable("64.")); + assertFalse(NumberUtils.isParsable("64L")); + assertFalse(NumberUtils.isParsable("-")); + assertFalse(NumberUtils.isParsable("--2")); + assertTrue(NumberUtils.isParsable("64.2")); + assertTrue(NumberUtils.isParsable("64")); + assertTrue(NumberUtils.isParsable("018")); + assertTrue(NumberUtils.isParsable(".18")); + assertTrue(NumberUtils.isParsable("-65")); + assertTrue(NumberUtils.isParsable("-018")); + assertTrue(NumberUtils.isParsable("-018.2")); + assertTrue(NumberUtils.isParsable("-.236")); } private boolean checkCreateNumber(final String val) { From 01175ec91173a4741c721bc6a9e7e298750ff29f Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sat, 22 Feb 2020 08:53:33 -0500 Subject: [PATCH 0036/3230] Use final. --- src/main/java/org/apache/commons/lang3/reflect/MethodUtils.java | 2 +- .../org/apache/commons/lang3/exception/ExceptionUtilsTest.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/reflect/MethodUtils.java b/src/main/java/org/apache/commons/lang3/reflect/MethodUtils.java index f724c5c82d7..be48fb9b561 100644 --- a/src/main/java/org/apache/commons/lang3/reflect/MethodUtils.java +++ b/src/main/java/org/apache/commons/lang3/reflect/MethodUtils.java @@ -974,7 +974,7 @@ public static A getAnnotation(final Method method, final final Class mcls = method.getDeclaringClass(); final List> classes = getAllSuperclassesAndInterfaces(mcls); for (final Class acls : classes) { - Method equivalentMethod = (ignoreAccess ? MethodUtils.getMatchingMethod(acls, method.getName(), method.getParameterTypes()) + final Method equivalentMethod = (ignoreAccess ? MethodUtils.getMatchingMethod(acls, method.getName(), method.getParameterTypes()) : MethodUtils.getMatchingAccessibleMethod(acls, method.getName(), method.getParameterTypes())); if (equivalentMethod != null) { annotation = equivalentMethod.getAnnotation(annotationCls); diff --git a/src/test/java/org/apache/commons/lang3/exception/ExceptionUtilsTest.java b/src/test/java/org/apache/commons/lang3/exception/ExceptionUtilsTest.java index 68354a47675..32e276fd3e4 100644 --- a/src/test/java/org/apache/commons/lang3/exception/ExceptionUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/exception/ExceptionUtilsTest.java @@ -714,7 +714,7 @@ public void testgetStackFramesNullArg() { public void testgetStackFramesHappyPath() { final String[] actual = ExceptionUtils.getStackFrames(new Throwable() { // provide static stack trace to make test stable - public void printStackTrace(PrintWriter s) { + public void printStackTrace(final PrintWriter s) { s.write("org.apache.commons.lang3.exception.ExceptionUtilsTest$1\n" + "\tat org.apache.commons.lang3.exception.ExceptionUtilsTest.testgetStackFramesGappyPath(ExceptionUtilsTest.java:706)\n" + "\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n" + From 0697258b6aabceaed851e12c2ab7f7ff9297517f Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sat, 22 Feb 2020 08:56:50 -0500 Subject: [PATCH 0037/3230] Use lambda. Fix formatting. --- .../org/apache/commons/lang3/reflect/MethodUtils.java | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/reflect/MethodUtils.java b/src/main/java/org/apache/commons/lang3/reflect/MethodUtils.java index be48fb9b561..98e1b4d1042 100644 --- a/src/main/java/org/apache/commons/lang3/reflect/MethodUtils.java +++ b/src/main/java/org/apache/commons/lang3/reflect/MethodUtils.java @@ -61,12 +61,7 @@ */ public class MethodUtils { - private static final Comparator METHOD_BY_SIGNATURE = new Comparator() { - @Override - public int compare(final Method m1, final Method m2) { - return m1.toString ().compareTo (m2.toString ()); - } - }; + private static final Comparator METHOD_BY_SIGNATURE = (m1, m2) -> m1.toString().compareTo(m2.toString()); /** *

{@link MethodUtils} instances should NOT be constructed in standard programming. @@ -699,7 +694,7 @@ public static Method getMatchingAccessibleMethod(final Class cls, } // Sort methods by signature to force deterministic result - Collections.sort (matchingMethods, METHOD_BY_SIGNATURE); + Collections.sort(matchingMethods, METHOD_BY_SIGNATURE); Method bestMatch = null; for (final Method method : matchingMethods) { From 8e5b10a0b032988789a242d4f08add9989ee8539 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sat, 22 Feb 2020 08:57:35 -0500 Subject: [PATCH 0038/3230] Add missing annotations. --- .../org/apache/commons/lang3/exception/ExceptionUtilsTest.java | 1 + .../commons/lang3/reflect/testbed/StringParameterizedChild.java | 1 + 2 files changed, 2 insertions(+) diff --git a/src/test/java/org/apache/commons/lang3/exception/ExceptionUtilsTest.java b/src/test/java/org/apache/commons/lang3/exception/ExceptionUtilsTest.java index 32e276fd3e4..7a4b338c778 100644 --- a/src/test/java/org/apache/commons/lang3/exception/ExceptionUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/exception/ExceptionUtilsTest.java @@ -714,6 +714,7 @@ public void testgetStackFramesNullArg() { public void testgetStackFramesHappyPath() { final String[] actual = ExceptionUtils.getStackFrames(new Throwable() { // provide static stack trace to make test stable + @Override public void printStackTrace(final PrintWriter s) { s.write("org.apache.commons.lang3.exception.ExceptionUtilsTest$1\n" + "\tat org.apache.commons.lang3.exception.ExceptionUtilsTest.testgetStackFramesGappyPath(ExceptionUtilsTest.java:706)\n" + diff --git a/src/test/java/org/apache/commons/lang3/reflect/testbed/StringParameterizedChild.java b/src/test/java/org/apache/commons/lang3/reflect/testbed/StringParameterizedChild.java index 36b7156b878..18555e2907a 100644 --- a/src/test/java/org/apache/commons/lang3/reflect/testbed/StringParameterizedChild.java +++ b/src/test/java/org/apache/commons/lang3/reflect/testbed/StringParameterizedChild.java @@ -29,6 +29,7 @@ public void consume(final String t) { public void parentProtectedAnnotatedMethod(final String t) { } + @Override public void parentNotAnnotatedMethod(final String t) { } From 0f119ef2a6ab2ac56cdcfd2b73858bdc4f216a85 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sat, 22 Feb 2020 09:21:57 -0500 Subject: [PATCH 0039/3230] Javadoc tweaks. --- src/main/java/org/apache/commons/lang3/CharUtils.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/CharUtils.java b/src/main/java/org/apache/commons/lang3/CharUtils.java index 3c8ad3e6688..be0aea44248 100644 --- a/src/main/java/org/apache/commons/lang3/CharUtils.java +++ b/src/main/java/org/apache/commons/lang3/CharUtils.java @@ -33,7 +33,7 @@ public class CharUtils { private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; /** - * {@code \u000a} linefeed LF ('\n'). + * Linefeed character LF ({@code '\n'}, Unicode 000a). * * @see JLF: Escape Sequences * for Character and String Literals @@ -42,7 +42,7 @@ public class CharUtils { public static final char LF = '\n'; /** - * {@code \u000d} carriage return CR ('\r'). + * Carriage return characterf CR ('\r', Unicode 000d). * * @see JLF: Escape Sequences * for Character and String Literals From 94b3784fdec5d0e9d63e4aec6772144b68283790 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sat, 22 Feb 2020 18:33:04 -0500 Subject: [PATCH 0040/3230] Simpler NPE message for new method. --- src/main/java/org/apache/commons/lang3/Range.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/apache/commons/lang3/Range.java b/src/main/java/org/apache/commons/lang3/Range.java index 628653acb9a..b7f0b1c039f 100644 --- a/src/main/java/org/apache/commons/lang3/Range.java +++ b/src/main/java/org/apache/commons/lang3/Range.java @@ -475,7 +475,7 @@ public boolean isStartedBy(final T element) { */ public T fit(final T element) { // Comparable API says throw NPE on null - Validate.notNull(element, "Element is null"); + Validate.notNull(element, "element"); if (isAfter(element)) { return minimum; } else if (isBefore(element)) { From e9d7afbe2bf667167614869c7ea10e91f96ffceb Mon Sep 17 00:00:00 2001 From: Edgar Asatryan <17509127+nstdio@users.noreply.github.com> Date: Wed, 4 Mar 2020 18:11:23 +0400 Subject: [PATCH 0041/3230] [LANG-1523] Avoid unnecessary allocation in wrapIfMissing. (#496) Now `StringUtils#wrapIfMissing(String, char)` and `StringUtils#wrapIfMissing(String, String)` does not allocate buffer when input is already wrapped. --- .../org/apache/commons/lang3/StringUtils.java | 27 +++++++++++++++---- .../apache/commons/lang3/StringUtilsTest.java | 8 ++++-- 2 files changed, 28 insertions(+), 7 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/StringUtils.java b/src/main/java/org/apache/commons/lang3/StringUtils.java index 2668731eb18..5c31d7bcd60 100644 --- a/src/main/java/org/apache/commons/lang3/StringUtils.java +++ b/src/main/java/org/apache/commons/lang3/StringUtils.java @@ -9448,6 +9448,8 @@ public static String wrap(final String str, final String wrapWith) { * Wraps a string with a char if that char is missing from the start or end of the given string. *

* + *

A new {@code String} will not be created if {@code str} is already wrapped.

+ * *
      * StringUtils.wrapIfMissing(null, *)        = null
      * StringUtils.wrapIfMissing("", *)          = ""
@@ -9472,12 +9474,18 @@ public static String wrapIfMissing(final String str, final char wrapWith) {
         if (isEmpty(str) || wrapWith == CharUtils.NUL) {
             return str;
         }
+        final boolean wrapStart = str.charAt(0) != wrapWith;
+        final boolean wrapEnd = str.charAt(str.length() - 1) != wrapWith;
+        if (!wrapStart && !wrapEnd) {
+            return str;
+        }
+
         final StringBuilder builder = new StringBuilder(str.length() + 2);
-        if (str.charAt(0) != wrapWith) {
+        if (wrapStart) {
             builder.append(wrapWith);
         }
         builder.append(str);
-        if (str.charAt(str.length() - 1) != wrapWith) {
+        if (wrapEnd) {
             builder.append(wrapWith);
         }
         return builder.toString();
@@ -9488,6 +9496,8 @@ public static String wrapIfMissing(final String str, final char wrapWith) {
      * Wraps a string with a string if that string is missing from the start or end of the given string.
      * 

* + *

A new {@code String} will not be created if {@code str} is already wrapped.

+ * *
      * StringUtils.wrapIfMissing(null, *)         = null
      * StringUtils.wrapIfMissing("", *)           = ""
@@ -9508,7 +9518,7 @@ public static String wrapIfMissing(final String str, final char wrapWith) {
      * @param str
      *            the string to be wrapped, may be {@code null}
      * @param wrapWith
-     *            the char that will wrap {@code str}
+     *            the string that will wrap {@code str}
      * @return the wrapped string, or {@code null} if {@code str==null}
      * @since 3.5
      */
@@ -9516,12 +9526,19 @@ public static String wrapIfMissing(final String str, final String wrapWith) {
         if (isEmpty(str) || isEmpty(wrapWith)) {
             return str;
         }
+
+        final boolean wrapStart = !str.startsWith(wrapWith);
+        final boolean wrapEnd = !str.endsWith(wrapWith);
+        if (!wrapStart && !wrapEnd) {
+            return str;
+        }
+
         final StringBuilder builder = new StringBuilder(str.length() + wrapWith.length() + wrapWith.length());
-        if (!str.startsWith(wrapWith)) {
+        if (wrapStart) {
             builder.append(wrapWith);
         }
         builder.append(str);
-        if (!str.endsWith(wrapWith)) {
+        if (wrapEnd) {
             builder.append(wrapWith);
         }
         return builder.toString();
diff --git a/src/test/java/org/apache/commons/lang3/StringUtilsTest.java b/src/test/java/org/apache/commons/lang3/StringUtilsTest.java
index e7eb5f075fc..30263de6b33 100644
--- a/src/test/java/org/apache/commons/lang3/StringUtilsTest.java
+++ b/src/test/java/org/apache/commons/lang3/StringUtilsTest.java
@@ -3237,7 +3237,9 @@ public void testWrapIfMissing_StringChar() {
         assertEquals("/x/y/z/", StringUtils.wrapIfMissing("x/y/z", '/'));
         assertEquals("/x/y/z/", StringUtils.wrapIfMissing("/x/y/z", '/'));
         assertEquals("/x/y/z/", StringUtils.wrapIfMissing("x/y/z/", '/'));
-        assertEquals("/", StringUtils.wrapIfMissing("/", '/'));
+
+        assertSame("/", StringUtils.wrapIfMissing("/", '/'));
+        assertSame("/x/", StringUtils.wrapIfMissing("/x/", '/'));
     }
 
     @Test
@@ -3259,7 +3261,9 @@ public void testWrapIfMissing_StringString() {
         assertEquals("/x/y/z/", StringUtils.wrapIfMissing("x/y/z/", "/"));
         assertEquals("/", StringUtils.wrapIfMissing("/", "/"));
         assertEquals("ab/ab", StringUtils.wrapIfMissing("/", "ab"));
-        assertEquals("ab/ab", StringUtils.wrapIfMissing("ab/ab", "ab"));
+
+        assertSame("ab/ab", StringUtils.wrapIfMissing("ab/ab", "ab"));
+        assertSame("//x//", StringUtils.wrapIfMissing("//x//", "//"));
     }
 
     @Test

From 200d8e97453aa755af78f10dbc268c5d4f2a3e01 Mon Sep 17 00:00:00 2001
From: Gary Gregory 
Date: Wed, 4 Mar 2020 09:13:58 -0500
Subject: [PATCH 0042/3230] [LANG-1523] Avoid unnecessary allocation in
 StringUtils.wrapIfMissing. #496.

---
 src/changes/changes.xml | 1 +
 1 file changed, 1 insertion(+)

diff --git a/src/changes/changes.xml b/src/changes/changes.xml
index f4fd3b6a1a8..5aa8be24f86 100644
--- a/src/changes/changes.xml
+++ b/src/changes/changes.xml
@@ -105,6 +105,7 @@ The  type attribute can be add,update,fix,remove.
     MethodUtils will throw a NPE if invokeMethod() is called for a var-args method #407.
     Reuse own code in Functions.java #493.
     MethodUtils.getAnnotation() with searchSupers = true does not work if super is generic #494.
+    Avoid unnecessary allocation in StringUtils.wrapIfMissing. #496.
   
 
   

From ba607f525b842661d40195d0d4778528e2384e70 Mon Sep 17 00:00:00 2001
From: Gary Gregory 
Date: Fri, 6 Mar 2020 11:08:22 -0500
Subject: [PATCH 0043/3230] [LANG-1525] Internally use Validate.notNull(foo,
 ...) instead of Validate.isTrue(foo != null, ...).

---
 src/changes/changes.xml                       |  1 +
 .../org/apache/commons/lang3/CharRange.java   |  2 +-
 .../org/apache/commons/lang3/CharUtils.java   |  6 +-
 .../org/apache/commons/lang3/EnumUtils.java   |  4 +-
 .../commons/lang3/SerializationUtils.java     |  6 +-
 .../org/apache/commons/lang3/ThreadUtils.java | 18 ++---
 .../commons/lang3/builder/DiffBuilder.java    |  8 +-
 .../commons/lang3/builder/DiffResult.java     |  6 +-
 .../lang3/builder/HashCodeBuilder.java        |  2 +-
 .../builder/ReflectionToStringBuilder.java    |  3 +-
 .../lang3/builder/ToStringBuilder.java        |  3 +-
 .../CallableBackgroundInitializer.java        |  2 +-
 .../MultiBackgroundInitializer.java           |  4 +-
 .../lang3/exception/ExceptionUtils.java       |  4 +-
 .../apache/commons/lang3/math/Fraction.java   |  8 +-
 .../commons/lang3/math/IEEE754rUtils.java     |  8 +-
 .../commons/lang3/math/NumberUtils.java       |  2 +-
 .../commons/lang3/reflect/FieldUtils.java     | 34 ++++----
 .../commons/lang3/reflect/MethodUtils.java    |  4 +-
 .../apache/commons/lang3/time/DateUtils.java  |  2 +-
 .../apache/commons/lang3/CharRangeTest.java   |  2 +-
 .../apache/commons/lang3/CharUtilsTest.java   |  6 +-
 .../apache/commons/lang3/EnumUtilsTest.java   |  4 +-
 .../commons/lang3/SerializationUtilsTest.java |  8 +-
 .../apache/commons/lang3/ThreadUtilsTest.java | 24 +++---
 .../lang3/builder/DiffBuilderTest.java        |  4 +-
 .../commons/lang3/builder/DiffResultTest.java |  6 +-
 .../lang3/builder/HashCodeBuilderTest.java    |  2 +-
 .../ReflectionToStringBuilderTest.java        |  2 +-
 .../lang3/builder/ToStringBuilderTest.java    |  4 +-
 .../CallableBackgroundInitializerTest.java    |  4 +-
 .../MultiBackgroundInitializerTest.java       |  4 +-
 .../lang3/exception/ExceptionUtilsTest.java   |  4 +-
 .../commons/lang3/math/FractionTest.java      | 10 +--
 .../commons/lang3/math/IEEE754rUtilsTest.java |  8 +-
 .../commons/lang3/math/NumberUtilsTest.java   | 26 +++----
 .../commons/lang3/reflect/FieldUtilsTest.java | 78 +++++++++----------
 .../lang3/reflect/MethodUtilsTest.java        | 12 +--
 .../lang3/time/DateUtilsFragmentTest.java     | 10 +--
 .../commons/lang3/time/DateUtilsTest.java     |  8 +-
 40 files changed, 176 insertions(+), 177 deletions(-)

diff --git a/src/changes/changes.xml b/src/changes/changes.xml
index 5aa8be24f86..a97452f5829 100644
--- a/src/changes/changes.xml
+++ b/src/changes/changes.xml
@@ -106,6 +106,7 @@ The  type attribute can be add,update,fix,remove.
     Reuse own code in Functions.java #493.
     MethodUtils.getAnnotation() with searchSupers = true does not work if super is generic #494.
     Avoid unnecessary allocation in StringUtils.wrapIfMissing. #496.
+    Internally use Validate.notNull(foo, ...) instead of Validate.isTrue(foo != null, ...).
   
 
   
diff --git a/src/main/java/org/apache/commons/lang3/CharRange.java b/src/main/java/org/apache/commons/lang3/CharRange.java
index be656d2a531..0504bedaa17 100644
--- a/src/main/java/org/apache/commons/lang3/CharRange.java
+++ b/src/main/java/org/apache/commons/lang3/CharRange.java
@@ -179,7 +179,7 @@ public boolean contains(final char ch) {
      * @throws IllegalArgumentException if {@code null} input
      */
     public boolean contains(final CharRange range) {
-        Validate.isTrue(range != null, "The Range must not be null");
+        Validate.notNull(range, "The Range must not be null");
         if (negated) {
             if (range.negated) {
                 return start >= range.start && end <= range.end;
diff --git a/src/main/java/org/apache/commons/lang3/CharUtils.java b/src/main/java/org/apache/commons/lang3/CharUtils.java
index be0aea44248..b872ac0f8d5 100644
--- a/src/main/java/org/apache/commons/lang3/CharUtils.java
+++ b/src/main/java/org/apache/commons/lang3/CharUtils.java
@@ -134,7 +134,7 @@ public static Character toCharacterObject(final String str) {
      * @throws IllegalArgumentException if the Character is null
      */
     public static char toChar(final Character ch) {
-        Validate.isTrue(ch != null, "The Character must not be null");
+        Validate.notNull(ch, "The Character must not be null");
         return ch.charValue();
     }
 
@@ -175,7 +175,7 @@ public static char toChar(final Character ch, final char defaultValue) {
      * @throws IllegalArgumentException if the String is empty
      */
     public static char toChar(final String str) {
-        Validate.isTrue(StringUtils.isNotEmpty(str), "The String must not be empty");
+        Validate.notEmpty(str, "The String must not be empty");
         return str.charAt(0);
     }
 
@@ -263,7 +263,7 @@ public static int toIntValue(final char ch, final int defaultValue) {
      * @throws IllegalArgumentException if the Character is not ASCII numeric or is null
      */
     public static int toIntValue(final Character ch) {
-        Validate.isTrue(ch != null, "The character must not be null");
+        Validate.notNull(ch, "The character must not be null");
         return toIntValue(ch.charValue());
     }
 
diff --git a/src/main/java/org/apache/commons/lang3/EnumUtils.java b/src/main/java/org/apache/commons/lang3/EnumUtils.java
index 75b052a9fcf..1df43013abf 100644
--- a/src/main/java/org/apache/commons/lang3/EnumUtils.java
+++ b/src/main/java/org/apache/commons/lang3/EnumUtils.java
@@ -116,7 +116,7 @@ public static > long generateBitVector(final Class enumClas
         Validate.notNull(values);
         long total = 0;
         for (final E constant : values) {
-            Validate.isTrue(constant != null, NULL_ELEMENTS_NOT_PERMITTED);
+            Validate.notNull(constant, NULL_ELEMENTS_NOT_PERMITTED);
             total |= 1L << constant.ordinal();
         }
         return total;
@@ -173,7 +173,7 @@ public static > long[] generateBitVectors(final Class enumC
         Validate.notNull(values);
         final EnumSet condensed = EnumSet.noneOf(enumClass);
         for (final E constant : values) {
-            Validate.isTrue(constant != null, NULL_ELEMENTS_NOT_PERMITTED);
+            Validate.notNull(constant, NULL_ELEMENTS_NOT_PERMITTED);
             condensed.add(constant);
         }
         final long[] result = new long[(enumClass.getEnumConstants().length - 1) / Long.SIZE + 1];
diff --git a/src/main/java/org/apache/commons/lang3/SerializationUtils.java b/src/main/java/org/apache/commons/lang3/SerializationUtils.java
index 28f8d76ea61..14bfc1dc7cf 100644
--- a/src/main/java/org/apache/commons/lang3/SerializationUtils.java
+++ b/src/main/java/org/apache/commons/lang3/SerializationUtils.java
@@ -133,7 +133,7 @@ public static  T roundtrip(final T msg) {
      * @throws SerializationException (runtime) if the serialization fails
      */
     public static void serialize(final Serializable obj, final OutputStream outputStream) {
-        Validate.isTrue(outputStream != null, "The OutputStream must not be null");
+        Validate.notNull(outputStream, "The OutputStream must not be null");
         try (ObjectOutputStream out = new ObjectOutputStream(outputStream)) {
             out.writeObject(obj);
         } catch (final IOException ex) {
@@ -188,7 +188,7 @@ public static byte[] serialize(final Serializable obj) {
      *             (runtime) if the serialization fails
      */
     public static  T deserialize(final InputStream inputStream) {
-        Validate.isTrue(inputStream != null, "The InputStream must not be null");
+        Validate.notNull(inputStream, "The InputStream must not be null");
         try (ObjectInputStream in = new ObjectInputStream(inputStream)) {
             @SuppressWarnings("unchecked")
             final T obj = (T) in.readObject();
@@ -219,7 +219,7 @@ public static  T deserialize(final InputStream inputStream) {
      *             (runtime) if the serialization fails
      */
     public static  T deserialize(final byte[] objectData) {
-        Validate.isTrue(objectData != null, "The byte[] must not be null");
+        Validate.notNull(objectData, "The byte[] must not be null");
         return deserialize(new ByteArrayInputStream(objectData));
     }
 
diff --git a/src/main/java/org/apache/commons/lang3/ThreadUtils.java b/src/main/java/org/apache/commons/lang3/ThreadUtils.java
index 5534194fa98..fef3dc85025 100644
--- a/src/main/java/org/apache/commons/lang3/ThreadUtils.java
+++ b/src/main/java/org/apache/commons/lang3/ThreadUtils.java
@@ -50,7 +50,7 @@ public class ThreadUtils {
      *          thread groups from this thread's thread group up to the system thread group
      */
     public static Thread findThreadById(final long threadId, final ThreadGroup threadGroup) {
-        Validate.isTrue(threadGroup != null, "The thread group must not be null");
+        Validate.notNull(threadGroup, "The thread group must not be null");
         final Thread thread = findThreadById(threadId);
         if (thread != null && threadGroup.equals(thread.getThreadGroup())) {
             return thread;
@@ -73,7 +73,7 @@ public static Thread findThreadById(final long threadId, final ThreadGroup threa
      *          thread groups from this thread's thread group up to the system thread group
      */
     public static Thread findThreadById(final long threadId, final String threadGroupName) {
-        Validate.isTrue(threadGroupName != null, "The thread group name must not be null");
+        Validate.notNull(threadGroupName, "The thread group name must not be null");
         final Thread thread = findThreadById(threadId);
         if (thread != null && thread.getThreadGroup() != null && thread.getThreadGroup().getName().equals(threadGroupName)) {
             return thread;
@@ -114,8 +114,8 @@ public static Collection findThreadsByName(final String threadName, fina
      *          thread groups from this thread's thread group up to the system thread group
      */
     public static Collection findThreadsByName(final String threadName, final String threadGroupName) {
-        Validate.isTrue(threadName != null, "The thread name must not be null");
-        Validate.isTrue(threadGroupName != null, "The thread group name must not be null");
+        Validate.notNull(threadName, "The thread name must not be null");
+        Validate.notNull(threadGroupName, "The thread group name must not be null");
 
         final Collection threadGroups = findThreadGroups(new NamePredicate(threadGroupName));
 
@@ -305,7 +305,7 @@ public static class NamePredicate implements ThreadPredicate, ThreadGroupPredica
          */
         public NamePredicate(final String name) {
             super();
-            Validate.isTrue(name != null, "The name must not be null");
+            Validate.notNull(name, "The name must not be null");
             this.name = name;
         }
 
@@ -390,8 +390,8 @@ public static Collection findThreadGroups(final ThreadGroupPredicat
      *          thread groups from this thread's thread group up to the system thread group
      */
     public static Collection findThreads(final ThreadGroup group, final boolean recurse, final ThreadPredicate predicate) {
-        Validate.isTrue(group != null, "The group must not be null");
-        Validate.isTrue(predicate != null, "The predicate must not be null");
+        Validate.notNull(group, "The group must not be null");
+        Validate.notNull(predicate, "The predicate must not be null");
 
         int count = group.activeCount();
         Thread[] threads;
@@ -422,8 +422,8 @@ public static Collection findThreads(final ThreadGroup group, final bool
      *          thread groups from this thread's thread group up to the system thread group
      */
     public static Collection findThreadGroups(final ThreadGroup group, final boolean recurse, final ThreadGroupPredicate predicate) {
-        Validate.isTrue(group != null, "The group must not be null");
-        Validate.isTrue(predicate != null, "The predicate must not be null");
+        Validate.notNull(group, "The group must not be null");
+        Validate.notNull(predicate, "The predicate must not be null");
 
         int count = group.activeGroupCount();
         ThreadGroup[] threadGroups;
diff --git a/src/main/java/org/apache/commons/lang3/builder/DiffBuilder.java b/src/main/java/org/apache/commons/lang3/builder/DiffBuilder.java
index 6beeaf7b60b..2ea1f69e634 100644
--- a/src/main/java/org/apache/commons/lang3/builder/DiffBuilder.java
+++ b/src/main/java/org/apache/commons/lang3/builder/DiffBuilder.java
@@ -104,8 +104,8 @@ public class DiffBuilder implements Builder> {
     public DiffBuilder(final T lhs, final T rhs,
             final ToStringStyle style, final boolean testTriviallyEqual) {
 
-        Validate.isTrue(lhs != null, "lhs cannot be null");
-        Validate.isTrue(rhs != null, "rhs cannot be null");
+        Validate.notNull(lhs, "lhs cannot be null");
+        Validate.notNull(rhs, "rhs cannot be null");
 
         this.diffs = new ArrayList<>();
         this.left = lhs;
@@ -950,7 +950,7 @@ public Object[] getRight() {
     public DiffBuilder append(final String fieldName,
             final DiffResult diffResult) {
         validateFieldNameNotNull(fieldName);
-        Validate.isTrue(diffResult != null, "Diff result cannot be null");
+        Validate.notNull(diffResult, "Diff result cannot be null");
         if (objectsTriviallyEqual) {
             return this;
         }
@@ -978,7 +978,7 @@ public DiffResult build() {
     }
 
     private void validateFieldNameNotNull(final String fieldName) {
-        Validate.isTrue(fieldName != null, "Field name cannot be null");
+        Validate.notNull(fieldName, "Field name cannot be null");
     }
 
 }
diff --git a/src/main/java/org/apache/commons/lang3/builder/DiffResult.java b/src/main/java/org/apache/commons/lang3/builder/DiffResult.java
index 8132dd4f0ca..b8594ad6b7c 100644
--- a/src/main/java/org/apache/commons/lang3/builder/DiffResult.java
+++ b/src/main/java/org/apache/commons/lang3/builder/DiffResult.java
@@ -74,9 +74,9 @@ public class DiffResult implements Iterable> {
      */
     DiffResult(final T lhs, final T rhs, final List> diffs,
             final ToStringStyle style) {
-        Validate.isTrue(lhs != null, "Left hand object cannot be null");
-        Validate.isTrue(rhs != null, "Right hand object cannot be null");
-        Validate.isTrue(diffs != null, "List of differences cannot be null");
+        Validate.notNull(lhs, "Left hand object cannot be null");
+        Validate.notNull(rhs, "Right hand object cannot be null");
+        Validate.notNull(diffs, "List of differences cannot be null");
 
         this.diffs = diffs;
         this.lhs = lhs;
diff --git a/src/main/java/org/apache/commons/lang3/builder/HashCodeBuilder.java b/src/main/java/org/apache/commons/lang3/builder/HashCodeBuilder.java
index c430b4060a4..7b7bbb01588 100644
--- a/src/main/java/org/apache/commons/lang3/builder/HashCodeBuilder.java
+++ b/src/main/java/org/apache/commons/lang3/builder/HashCodeBuilder.java
@@ -358,7 +358,7 @@ public static int reflectionHashCode(final int initialNonZeroOddNumber, final in
      */
     public static  int reflectionHashCode(final int initialNonZeroOddNumber, final int multiplierNonZeroOddNumber, final T object,
             final boolean testTransients, final Class reflectUpToClass, final String... excludeFields) {
-        Validate.isTrue(object != null, "The object to build a hash code for must not be null");
+        Validate.notNull(object, "The object to build a hash code for must not be null");
         final HashCodeBuilder builder = new HashCodeBuilder(initialNonZeroOddNumber, multiplierNonZeroOddNumber);
         Class clazz = object.getClass();
         reflectionAppend(object, clazz, builder, testTransients, excludeFields);
diff --git a/src/main/java/org/apache/commons/lang3/builder/ReflectionToStringBuilder.java b/src/main/java/org/apache/commons/lang3/builder/ReflectionToStringBuilder.java
index 3996a59a39a..d19aa13fa55 100644
--- a/src/main/java/org/apache/commons/lang3/builder/ReflectionToStringBuilder.java
+++ b/src/main/java/org/apache/commons/lang3/builder/ReflectionToStringBuilder.java
@@ -434,8 +434,7 @@ public static String toStringExclude(final Object object, final String... exclud
     }
 
     private static Object checkNotNull(final Object obj) {
-        Validate.isTrue(obj != null, "The Object passed in should not be null.");
-        return obj;
+        return Validate.notNull(obj, "The Object passed in should not be null.");
     }
 
     /**
diff --git a/src/main/java/org/apache/commons/lang3/builder/ToStringBuilder.java b/src/main/java/org/apache/commons/lang3/builder/ToStringBuilder.java
index ace1f835612..3522ec34b7e 100644
--- a/src/main/java/org/apache/commons/lang3/builder/ToStringBuilder.java
+++ b/src/main/java/org/apache/commons/lang3/builder/ToStringBuilder.java
@@ -133,8 +133,7 @@ public static ToStringStyle getDefaultStyle() {
      * @throws IllegalArgumentException if the style is {@code null}
      */
     public static void setDefaultStyle(final ToStringStyle style) {
-        Validate.isTrue(style != null, "The style must not be null");
-        defaultStyle = style;
+        defaultStyle = Validate.notNull(style, "The style must not be null");
     }
 
     //----------------------------------------------------------------------------
diff --git a/src/main/java/org/apache/commons/lang3/concurrent/CallableBackgroundInitializer.java b/src/main/java/org/apache/commons/lang3/concurrent/CallableBackgroundInitializer.java
index c1d07353e12..6fca65c8d0e 100644
--- a/src/main/java/org/apache/commons/lang3/concurrent/CallableBackgroundInitializer.java
+++ b/src/main/java/org/apache/commons/lang3/concurrent/CallableBackgroundInitializer.java
@@ -120,6 +120,6 @@ protected T initialize() throws Exception {
      * @throws IllegalArgumentException if the {@code Callable} is null
      */
     private void checkCallable(final Callable call) {
-        Validate.isTrue(call != null, "Callable must not be null!");
+        Validate.notNull(call, "Callable must not be null!");
     }
 }
diff --git a/src/main/java/org/apache/commons/lang3/concurrent/MultiBackgroundInitializer.java b/src/main/java/org/apache/commons/lang3/concurrent/MultiBackgroundInitializer.java
index 6a6a9a09261..7e36fd9db55 100644
--- a/src/main/java/org/apache/commons/lang3/concurrent/MultiBackgroundInitializer.java
+++ b/src/main/java/org/apache/commons/lang3/concurrent/MultiBackgroundInitializer.java
@@ -133,8 +133,8 @@ public MultiBackgroundInitializer(final ExecutorService exec) {
      * @throws IllegalStateException if {@code start()} has already been called
      */
     public void addInitializer(final String name, final BackgroundInitializer init) {
-        Validate.isTrue(name != null, "Name of child initializer must not be null!");
-        Validate.isTrue(init != null, "Child initializer must not be null!");
+        Validate.notNull(name, "Name of child initializer must not be null!");
+        Validate.notNull(init, "Child initializer must not be null!");
 
         synchronized (this) {
             if (isStarted()) {
diff --git a/src/main/java/org/apache/commons/lang3/exception/ExceptionUtils.java b/src/main/java/org/apache/commons/lang3/exception/ExceptionUtils.java
index 6bfc79ef60c..a2a67b4bc0d 100644
--- a/src/main/java/org/apache/commons/lang3/exception/ExceptionUtils.java
+++ b/src/main/java/org/apache/commons/lang3/exception/ExceptionUtils.java
@@ -632,7 +632,7 @@ public static void printRootCauseStackTrace(final Throwable throwable, final Pri
         if (throwable == null) {
             return;
         }
-        Validate.isTrue(stream != null, "The PrintStream must not be null");
+        Validate.notNull(stream, "The PrintStream must not be null");
         final String trace[] = getRootCauseStackTrace(throwable);
         for (final String element : trace) {
             stream.println(element);
@@ -663,7 +663,7 @@ public static void printRootCauseStackTrace(final Throwable throwable, final Pri
         if (throwable == null) {
             return;
         }
-        Validate.isTrue(writer != null, "The PrintWriter must not be null");
+        Validate.notNull(writer, "The PrintWriter must not be null");
         final String trace[] = getRootCauseStackTrace(throwable);
         for (final String element : trace) {
             writer.println(element);
diff --git a/src/main/java/org/apache/commons/lang3/math/Fraction.java b/src/main/java/org/apache/commons/lang3/math/Fraction.java
index 7d452c14179..7c11f2a2f86 100644
--- a/src/main/java/org/apache/commons/lang3/math/Fraction.java
+++ b/src/main/java/org/apache/commons/lang3/math/Fraction.java
@@ -312,7 +312,7 @@ public static Fraction getFraction(double value) {
      * @throws NumberFormatException if the number format is invalid
      */
     public static Fraction getFraction(String str) {
-        Validate.isTrue(str != null, "The string must not be null");
+        Validate.notNull(str, "The string must not be null");
         // parse double format
         int pos = str.indexOf('.');
         if (pos >= 0) {
@@ -730,7 +730,7 @@ public Fraction subtract(final Fraction fraction) {
      *   cannot be represented in an {@code int}.
      */
     private Fraction addSub(final Fraction fraction, final boolean isAdd) {
-        Validate.isTrue(fraction != null, "The fraction must not be null");
+        Validate.notNull(fraction, "The fraction must not be null");
         // zero is identity for addition.
         if (numerator == 0) {
             return isAdd ? fraction : fraction.negate();
@@ -778,7 +778,7 @@ private Fraction addSub(final Fraction fraction, final boolean isAdd) {
      *  {@code Integer.MAX_VALUE}
      */
     public Fraction multiplyBy(final Fraction fraction) {
-        Validate.isTrue(fraction != null, "The fraction must not be null");
+        Validate.notNull(fraction, "The fraction must not be null");
         if (numerator == 0 || fraction.numerator == 0) {
             return ZERO;
         }
@@ -801,7 +801,7 @@ public Fraction multiplyBy(final Fraction fraction) {
      *  {@code Integer.MAX_VALUE}
      */
     public Fraction divideBy(final Fraction fraction) {
-        Validate.isTrue(fraction != null, "The fraction must not be null");
+        Validate.notNull(fraction, "The fraction must not be null");
         if (fraction.numerator == 0) {
             throw new ArithmeticException("The fraction to divide by must not be zero");
         }
diff --git a/src/main/java/org/apache/commons/lang3/math/IEEE754rUtils.java b/src/main/java/org/apache/commons/lang3/math/IEEE754rUtils.java
index d9fb5fa0425..ae737cf6039 100644
--- a/src/main/java/org/apache/commons/lang3/math/IEEE754rUtils.java
+++ b/src/main/java/org/apache/commons/lang3/math/IEEE754rUtils.java
@@ -37,7 +37,7 @@ public class IEEE754rUtils {
       * @since 3.4 Changed signature from min(double[]) to min(double...)
      */
     public static double min(final double... array) {
-        Validate.isTrue(array != null, "The Array must not be null");
+        Validate.notNull(array, "The Array must not be null");
         Validate.isTrue(array.length != 0, "Array cannot be empty.");
 
         // Finds and returns min
@@ -59,7 +59,7 @@ public static double min(final double... array) {
      * @since 3.4 Changed signature from min(float[]) to min(float...)
      */
     public static float min(final float... array) {
-        Validate.isTrue(array != null, "The Array must not be null");
+        Validate.notNull(array, "The Array must not be null");
         Validate.isTrue(array.length != 0, "Array cannot be empty.");
 
         // Finds and returns min
@@ -149,7 +149,7 @@ public static float min(final float a, final float b) {
      * @since 3.4 Changed signature from max(double[]) to max(double...)
      */
     public static double max(final double... array) {
-        Validate.isTrue(array != null, "The Array must not be null");
+        Validate.notNull(array, "The Array must not be null");
         Validate.isTrue(array.length != 0, "Array cannot be empty.");
 
         // Finds and returns max
@@ -171,7 +171,7 @@ public static double max(final double... array) {
      * @since 3.4 Changed signature from max(float[]) to max(float...)
      */
     public static float max(final float... array) {
-        Validate.isTrue(array != null, "The Array must not be null");
+        Validate.notNull(array, "The Array must not be null");
         Validate.isTrue(array.length != 0, "Array cannot be empty.");
 
         // Finds and returns max
diff --git a/src/main/java/org/apache/commons/lang3/math/NumberUtils.java b/src/main/java/org/apache/commons/lang3/math/NumberUtils.java
index 97aee235c28..ab7badc19c0 100644
--- a/src/main/java/org/apache/commons/lang3/math/NumberUtils.java
+++ b/src/main/java/org/apache/commons/lang3/math/NumberUtils.java
@@ -1312,7 +1312,7 @@ public static float max(final float... array) {
      * @throws IllegalArgumentException if {@code array} is either {@code null} or empty
      */
     private static void validateArray(final Object array) {
-        Validate.isTrue(array != null, "The Array must not be null");
+        Validate.notNull(array, "The Array must not be null");
         Validate.isTrue(Array.getLength(array) != 0, "Array cannot be empty.");
     }
 
diff --git a/src/main/java/org/apache/commons/lang3/reflect/FieldUtils.java b/src/main/java/org/apache/commons/lang3/reflect/FieldUtils.java
index 07eb8395a6b..4d2ce164da3 100644
--- a/src/main/java/org/apache/commons/lang3/reflect/FieldUtils.java
+++ b/src/main/java/org/apache/commons/lang3/reflect/FieldUtils.java
@@ -86,7 +86,7 @@ public static Field getField(final Class cls, final String fieldName) {
      *             in the inheritance hierarchy
      */
     public static Field getField(final Class cls, final String fieldName, final boolean forceAccess) {
-        Validate.isTrue(cls != null, "The class must not be null");
+        Validate.notNull(cls, "The class must not be null");
         Validate.isTrue(StringUtils.isNotBlank(fieldName), "The field name must not be blank/empty");
         // FIXME is this workaround still needed? lang requires Java 6
         // Sun Java 1.3 has a bugged implementation of getField hence we write the
@@ -169,7 +169,7 @@ public static Field getDeclaredField(final Class cls, final String fieldName)
      *             if the class is {@code null}, or the field name is blank or empty
      */
     public static Field getDeclaredField(final Class cls, final String fieldName, final boolean forceAccess) {
-        Validate.isTrue(cls != null, "The class must not be null");
+        Validate.notNull(cls, "The class must not be null");
         Validate.isTrue(StringUtils.isNotBlank(fieldName), "The field name must not be blank/empty");
         try {
             // only consider the specified class by using getDeclaredField()
@@ -214,7 +214,7 @@ public static Field[] getAllFields(final Class cls) {
      * @since 3.2
      */
     public static List getAllFieldsList(final Class cls) {
-        Validate.isTrue(cls != null, "The class must not be null");
+        Validate.notNull(cls, "The class must not be null");
         final List allFields = new ArrayList<>();
         Class currentClass = cls;
         while (currentClass != null) {
@@ -253,7 +253,7 @@ public static Field[] getFieldsWithAnnotation(final Class cls, final Class getFieldsListWithAnnotation(final Class cls, final Class annotationCls) {
-        Validate.isTrue(annotationCls != null, "The annotation class must not be null");
+        Validate.notNull(annotationCls, "The annotation class must not be null");
         final List allFields = getAllFieldsList(cls);
         final List annotatedFields = new ArrayList<>();
         for (final Field field : allFields) {
@@ -294,7 +294,7 @@ public static Object readStaticField(final Field field) throws IllegalAccessExce
      *             if the field is not made accessible
      */
     public static Object readStaticField(final Field field, final boolean forceAccess) throws IllegalAccessException {
-        Validate.isTrue(field != null, "The field must not be null");
+        Validate.notNull(field, "The field must not be null");
         Validate.isTrue(Modifier.isStatic(field.getModifiers()), "The field '%s' is not static", field.getName());
         return readField(field, (Object) null, forceAccess);
     }
@@ -337,7 +337,7 @@ public static Object readStaticField(final Class cls, final String fieldName)
      */
     public static Object readStaticField(final Class cls, final String fieldName, final boolean forceAccess) throws IllegalAccessException {
         final Field field = getField(cls, fieldName, forceAccess);
-        Validate.isTrue(field != null, "Cannot locate field '%s' on %s", fieldName, cls);
+        Validate.notNull(field, "Cannot locate field '%s' on %s", fieldName, cls);
         // already forced access above, don't repeat it here:
         return readStaticField(field, false);
     }
@@ -381,7 +381,7 @@ public static Object readDeclaredStaticField(final Class cls, final String fi
      */
     public static Object readDeclaredStaticField(final Class cls, final String fieldName, final boolean forceAccess) throws IllegalAccessException {
         final Field field = getDeclaredField(cls, fieldName, forceAccess);
-        Validate.isTrue(field != null, "Cannot locate declared field %s.%s", cls.getName(), fieldName);
+        Validate.notNull(field, "Cannot locate declared field %s.%s", cls.getName(), fieldName);
         // already forced access above, don't repeat it here:
         return readStaticField(field, false);
     }
@@ -420,7 +420,7 @@ public static Object readField(final Field field, final Object target) throws Il
      *             if the field is not made accessible
      */
     public static Object readField(final Field field, final Object target, final boolean forceAccess) throws IllegalAccessException {
-        Validate.isTrue(field != null, "The field must not be null");
+        Validate.notNull(field, "The field must not be null");
         if (forceAccess && !field.isAccessible()) {
             field.setAccessible(true);
         } else {
@@ -464,7 +464,7 @@ public static Object readField(final Object target, final String fieldName) thro
      *             if the named field is not made accessible
      */
     public static Object readField(final Object target, final String fieldName, final boolean forceAccess) throws IllegalAccessException {
-        Validate.isTrue(target != null, "target object must not be null");
+        Validate.notNull(target, "target object must not be null");
         final Class cls = target.getClass();
         final Field field = getField(cls, fieldName, forceAccess);
         Validate.isTrue(field != null, "Cannot locate field %s on %s", fieldName, cls);
@@ -507,7 +507,7 @@ public static Object readDeclaredField(final Object target, final String fieldNa
      *             if the field is not made accessible
      */
     public static Object readDeclaredField(final Object target, final String fieldName, final boolean forceAccess) throws IllegalAccessException {
-        Validate.isTrue(target != null, "target object must not be null");
+        Validate.notNull(target, "target object must not be null");
         final Class cls = target.getClass();
         final Field field = getDeclaredField(cls, fieldName, forceAccess);
         Validate.isTrue(field != null, "Cannot locate declared field %s.%s", cls, fieldName);
@@ -548,7 +548,7 @@ public static void writeStaticField(final Field field, final Object value) throw
      *             if the field is not made accessible or is {@code final}
      */
     public static void writeStaticField(final Field field, final Object value, final boolean forceAccess) throws IllegalAccessException {
-        Validate.isTrue(field != null, "The field must not be null");
+        Validate.notNull(field, "The field must not be null");
         Validate.isTrue(Modifier.isStatic(field.getModifiers()), "The field %s.%s is not static", field.getDeclaringClass().getName(),
                 field.getName());
         writeField(field, (Object) null, value, forceAccess);
@@ -595,7 +595,7 @@ public static void writeStaticField(final Class cls, final String fieldName,
     public static void writeStaticField(final Class cls, final String fieldName, final Object value, final boolean forceAccess)
             throws IllegalAccessException {
         final Field field = getField(cls, fieldName, forceAccess);
-        Validate.isTrue(field != null, "Cannot locate field %s on %s", fieldName, cls);
+        Validate.notNull(field, "Cannot locate field %s on %s", fieldName, cls);
         // already forced access above, don't repeat it here:
         writeStaticField(field, value, false);
     }
@@ -640,7 +640,7 @@ public static void writeDeclaredStaticField(final Class cls, final String fie
     public static void writeDeclaredStaticField(final Class cls, final String fieldName, final Object value, final boolean forceAccess)
             throws IllegalAccessException {
         final Field field = getDeclaredField(cls, fieldName, forceAccess);
-        Validate.isTrue(field != null, "Cannot locate declared field %s.%s", cls.getName(), fieldName);
+        Validate.notNull(field, "Cannot locate declared field %s.%s", cls.getName(), fieldName);
         // already forced access above, don't repeat it here:
         writeField(field, (Object) null, value, false);
     }
@@ -682,7 +682,7 @@ public static void writeField(final Field field, final Object target, final Obje
      */
     public static void writeField(final Field field, final Object target, final Object value, final boolean forceAccess)
             throws IllegalAccessException {
-        Validate.isTrue(field != null, "The field must not be null");
+        Validate.notNull(field, "The field must not be null");
         if (forceAccess && !field.isAccessible()) {
             field.setAccessible(true);
         } else {
@@ -722,7 +722,7 @@ public static void removeFinalModifier(final Field field) {
      */
     @Deprecated
     public static void removeFinalModifier(final Field field, final boolean forceAccess) {
-        Validate.isTrue(field != null, "The field must not be null");
+        Validate.notNull(field, "The field must not be null");
 
         try {
             if (Modifier.isFinal(field.getModifiers())) {
@@ -791,7 +791,7 @@ public static void writeField(final Object target, final String fieldName, final
      */
     public static void writeField(final Object target, final String fieldName, final Object value, final boolean forceAccess)
             throws IllegalAccessException {
-        Validate.isTrue(target != null, "target object must not be null");
+        Validate.notNull(target, "target object must not be null");
         final Class cls = target.getClass();
         final Field field = getField(cls, fieldName, forceAccess);
         Validate.isTrue(field != null, "Cannot locate declared field %s.%s", cls.getName(), fieldName);
@@ -839,7 +839,7 @@ public static void writeDeclaredField(final Object target, final String fieldNam
      */
     public static void writeDeclaredField(final Object target, final String fieldName, final Object value, final boolean forceAccess)
             throws IllegalAccessException {
-        Validate.isTrue(target != null, "target object must not be null");
+        Validate.notNull(target, "target object must not be null");
         final Class cls = target.getClass();
         final Field field = getDeclaredField(cls, fieldName, forceAccess);
         Validate.isTrue(field != null, "Cannot locate declared field %s.%s", cls.getName(), fieldName);
diff --git a/src/main/java/org/apache/commons/lang3/reflect/MethodUtils.java b/src/main/java/org/apache/commons/lang3/reflect/MethodUtils.java
index 98e1b4d1042..1d76ce611c0 100644
--- a/src/main/java/org/apache/commons/lang3/reflect/MethodUtils.java
+++ b/src/main/java/org/apache/commons/lang3/reflect/MethodUtils.java
@@ -914,7 +914,7 @@ public static List getMethodsListWithAnnotation(final Class cls,
                                                             final Class annotationCls,
                                                             final boolean searchSupers, final boolean ignoreAccess) {
 
-        Validate.isTrue(cls != null, "The class must not be null");
+        Validate.notNull(cls, "The class must not be null");
         Validate.isTrue(annotationCls != null, "The annotation class must not be null");
         final List> classes = (searchSupers ? getAllSuperclassesAndInterfaces(cls)
                 : new ArrayList<>());
@@ -957,7 +957,7 @@ public static List getMethodsListWithAnnotation(final Class cls,
     public static  A getAnnotation(final Method method, final Class annotationCls,
                                                          final boolean searchSupers, final boolean ignoreAccess) {
 
-        Validate.isTrue(method != null, "The method must not be null");
+        Validate.notNull(method, "The method must not be null");
         Validate.isTrue(annotationCls != null, "The annotation class must not be null");
         if (!ignoreAccess && !MemberUtils.isAccessible(method)) {
             return null;
diff --git a/src/main/java/org/apache/commons/lang3/time/DateUtils.java b/src/main/java/org/apache/commons/lang3/time/DateUtils.java
index 9fa254981ed..300b7ea94ee 100644
--- a/src/main/java/org/apache/commons/lang3/time/DateUtils.java
+++ b/src/main/java/org/apache/commons/lang3/time/DateUtils.java
@@ -1786,7 +1786,7 @@ public static int truncatedCompareTo(final Date date1, final Date date2, final i
     }
 
     private static void validateDateNotNull(final Date date) {
-        Validate.isTrue(date != null, "The date must not be null");
+        Validate.notNull(date, "The date must not be null");
     }
 
     //-----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/lang3/CharRangeTest.java b/src/test/java/org/apache/commons/lang3/CharRangeTest.java
index 18e4e90e776..8d59a5522c9 100644
--- a/src/test/java/org/apache/commons/lang3/CharRangeTest.java
+++ b/src/test/java/org/apache/commons/lang3/CharRangeTest.java
@@ -311,7 +311,7 @@ public void testContains_Charrange() {
     @Test
     public void testContainsNullArg() {
         final CharRange range = CharRange.is('a');
-        final IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> range.contains(null));
+        final NullPointerException e = assertThrows(NullPointerException.class, () -> range.contains(null));
         assertEquals("The Range must not be null", e.getMessage());
     }
 
diff --git a/src/test/java/org/apache/commons/lang3/CharUtilsTest.java b/src/test/java/org/apache/commons/lang3/CharUtilsTest.java
index ae6be1c9784..49b1a9300fa 100644
--- a/src/test/java/org/apache/commons/lang3/CharUtilsTest.java
+++ b/src/test/java/org/apache/commons/lang3/CharUtilsTest.java
@@ -200,7 +200,7 @@ public void testIsAsciiPrintable_char() {
     public void testToChar_Character() {
         assertEquals('A', CharUtils.toChar(CHARACTER_A));
         assertEquals('B', CharUtils.toChar(CHARACTER_B));
-        assertThrows(IllegalArgumentException.class, () -> CharUtils.toChar((Character) null));
+        assertThrows(NullPointerException.class, () -> CharUtils.toChar((Character) null));
     }
 
     @Test
@@ -214,7 +214,7 @@ public void testToChar_Character_char() {
     public void testToChar_String() {
         assertEquals('A', CharUtils.toChar("A"));
         assertEquals('B', CharUtils.toChar("BA"));
-        assertThrows(IllegalArgumentException.class, () -> CharUtils.toChar((String) null));
+        assertThrows(NullPointerException.class, () -> CharUtils.toChar((String) null));
         assertThrows(IllegalArgumentException.class, () -> CharUtils.toChar(""));
     }
 
@@ -284,7 +284,7 @@ public void testToIntValue_char_int() {
     public void testToIntValue_Character() {
         assertEquals(0, CharUtils.toIntValue(Character.valueOf('0')));
         assertEquals(3, CharUtils.toIntValue(Character.valueOf('3')));
-        assertThrows(IllegalArgumentException.class, () -> CharUtils.toIntValue(null));
+        assertThrows(NullPointerException.class, () -> CharUtils.toIntValue(null));
         assertThrows(IllegalArgumentException.class, () -> CharUtils.toIntValue(CHARACTER_A));
     }
 
diff --git a/src/test/java/org/apache/commons/lang3/EnumUtilsTest.java b/src/test/java/org/apache/commons/lang3/EnumUtilsTest.java
index 90e8f51b953..1e79f457146 100644
--- a/src/test/java/org/apache/commons/lang3/EnumUtilsTest.java
+++ b/src/test/java/org/apache/commons/lang3/EnumUtilsTest.java
@@ -186,13 +186,13 @@ public void test_generateBitVectors_nullIterable() {
 
     @Test
     public void test_generateBitVector_nullElement() {
-        assertThrows(IllegalArgumentException.class,
+        assertThrows(NullPointerException.class,
                 () -> EnumUtils.generateBitVector(Traffic.class, Arrays.asList(Traffic.RED, null)));
     }
 
     @Test
     public void test_generateBitVectors_nullElement() {
-        assertThrows(IllegalArgumentException.class,
+        assertThrows(NullPointerException.class,
                 () -> EnumUtils.generateBitVectors(Traffic.class, Arrays.asList(Traffic.RED, null)));
     }
 
diff --git a/src/test/java/org/apache/commons/lang3/SerializationUtilsTest.java b/src/test/java/org/apache/commons/lang3/SerializationUtilsTest.java
index 698962f260d..a03b4597ec5 100644
--- a/src/test/java/org/apache/commons/lang3/SerializationUtilsTest.java
+++ b/src/test/java/org/apache/commons/lang3/SerializationUtilsTest.java
@@ -141,12 +141,12 @@ public void testSerializeStreamNullObj() throws Exception {
 
     @Test
     public void testSerializeStreamObjNull() {
-        assertThrows(IllegalArgumentException.class, () -> SerializationUtils.serialize(iMap, null));
+        assertThrows(NullPointerException.class, () -> SerializationUtils.serialize(iMap, null));
     }
 
     @Test
     public void testSerializeStreamNullNull() {
-        assertThrows(IllegalArgumentException.class, () -> SerializationUtils.serialize(null, null));
+        assertThrows(NullPointerException.class, () -> SerializationUtils.serialize(null, null));
     }
 
     @Test
@@ -214,7 +214,7 @@ public void testDeserializeStreamOfNull() throws Exception {
 
     @Test
     public void testDeserializeStreamNull() {
-        assertThrows(IllegalArgumentException.class, () -> SerializationUtils.deserialize((InputStream) null));
+        assertThrows(NullPointerException.class, () -> SerializationUtils.deserialize((InputStream) null));
     }
 
     @Test
@@ -317,7 +317,7 @@ public void testDeserializeBytesOfNull() throws Exception {
 
     @Test
     public void testDeserializeBytesNull() {
-        assertThrows(IllegalArgumentException.class, () -> SerializationUtils.deserialize((byte[]) null));
+        assertThrows(NullPointerException.class, () -> SerializationUtils.deserialize((byte[]) null));
     }
 
     @Test
diff --git a/src/test/java/org/apache/commons/lang3/ThreadUtilsTest.java b/src/test/java/org/apache/commons/lang3/ThreadUtilsTest.java
index 4e8df276e97..3942ff8e7d9 100644
--- a/src/test/java/org/apache/commons/lang3/ThreadUtilsTest.java
+++ b/src/test/java/org/apache/commons/lang3/ThreadUtilsTest.java
@@ -42,42 +42,42 @@ public class ThreadUtilsTest {
 
     @Test
     public void testNullThreadName() {
-        assertThrows(IllegalArgumentException.class, () -> ThreadUtils.findThreadsByName(null));
+        assertThrows(NullPointerException.class, () -> ThreadUtils.findThreadsByName(null));
     }
 
     @Test
     public void testNullThreadGroupName() {
-        assertThrows(IllegalArgumentException.class, () -> ThreadUtils.findThreadGroupsByName(null));
+        assertThrows(NullPointerException.class, () -> ThreadUtils.findThreadGroupsByName(null));
     }
 
     @Test
     public void testNullThreadThreadGroupName1() {
-        assertThrows(IllegalArgumentException.class, () -> ThreadUtils.findThreadsByName(null, "tgname"));
+        assertThrows(NullPointerException.class, () -> ThreadUtils.findThreadsByName(null, "tgname"));
     }
 
     @Test
     public void testNullThreadThreadGroupName2() {
-        assertThrows(IllegalArgumentException.class, () -> ThreadUtils.findThreadsByName("tname", (String) null));
+        assertThrows(NullPointerException.class, () -> ThreadUtils.findThreadsByName("tname", (String) null));
     }
 
     @Test
     public void testNullThreadThreadGroupName3() {
-        assertThrows(IllegalArgumentException.class, () -> ThreadUtils.findThreadsByName(null, (String) null));
+        assertThrows(NullPointerException.class, () -> ThreadUtils.findThreadsByName(null, (String) null));
     }
 
     @Test
     public void testNullThreadThreadGroup1() {
-        assertThrows(IllegalArgumentException.class, () -> ThreadUtils.findThreadsByName("tname", (ThreadGroup) null));
+        assertThrows(NullPointerException.class, () -> ThreadUtils.findThreadsByName("tname", (ThreadGroup) null));
     }
 
     @Test
     public void testNullThreadThreadGroup2() {
-        assertThrows(IllegalArgumentException.class, () -> ThreadUtils.findThreadById(1L, (ThreadGroup) null));
+        assertThrows(NullPointerException.class, () -> ThreadUtils.findThreadById(1L, (ThreadGroup) null));
     }
 
     @Test
     public void testNullThreadThreadGroup3() {
-        assertThrows(IllegalArgumentException.class, () -> ThreadUtils.findThreadsByName(null, (ThreadGroup) null));
+        assertThrows(NullPointerException.class, () -> ThreadUtils.findThreadsByName(null, (ThreadGroup) null));
     }
 
     @Test
@@ -87,24 +87,24 @@ public void testInvalidThreadId() {
 
     @Test
     public void testThreadGroupsByIdFail() {
-        assertThrows(IllegalArgumentException.class,
+        assertThrows(NullPointerException.class,
                 () -> ThreadUtils.findThreadById(Thread.currentThread().getId(), (String) null));
     }
 
     @Test
     public void testThreadgroupsNullParent() {
-        assertThrows(IllegalArgumentException.class,
+        assertThrows(NullPointerException.class,
                 () -> ThreadUtils.findThreadGroups(null, true, ThreadUtils.ALWAYS_TRUE_PREDICATE));
     }
 
     @Test
     public void testThreadgroupsNullPredicate() {
-        assertThrows(IllegalArgumentException.class, () -> ThreadUtils.findThreadGroups(null));
+        assertThrows(NullPointerException.class, () -> ThreadUtils.findThreadGroups(null));
     }
 
     @Test
     public void testThreadsNullPredicate() {
-        assertThrows(IllegalArgumentException.class, () -> ThreadUtils.findThreads(null));
+        assertThrows(NullPointerException.class, () -> ThreadUtils.findThreads(null));
     }
 
     @Test
diff --git a/src/test/java/org/apache/commons/lang3/builder/DiffBuilderTest.java b/src/test/java/org/apache/commons/lang3/builder/DiffBuilderTest.java
index 263a50bbe5e..a9e62de23ed 100644
--- a/src/test/java/org/apache/commons/lang3/builder/DiffBuilderTest.java
+++ b/src/test/java/org/apache/commons/lang3/builder/DiffBuilderTest.java
@@ -308,12 +308,12 @@ public void testLongArray() {
 
     @Test
     public void testNullLhs() {
-        assertThrows(IllegalArgumentException.class, () -> new DiffBuilder<>(null, this, ToStringStyle.DEFAULT_STYLE));
+        assertThrows(NullPointerException.class, () -> new DiffBuilder<>(null, this, ToStringStyle.DEFAULT_STYLE));
     }
 
     @Test
     public void testNullRhs() {
-        assertThrows(IllegalArgumentException.class, () -> new DiffBuilder<>(this, null, ToStringStyle.DEFAULT_STYLE));
+        assertThrows(NullPointerException.class, () -> new DiffBuilder<>(this, null, ToStringStyle.DEFAULT_STYLE));
     }
 
     @Test
diff --git a/src/test/java/org/apache/commons/lang3/builder/DiffResultTest.java b/src/test/java/org/apache/commons/lang3/builder/DiffResultTest.java
index b92b34fb0f9..2045f012e0c 100644
--- a/src/test/java/org/apache/commons/lang3/builder/DiffResultTest.java
+++ b/src/test/java/org/apache/commons/lang3/builder/DiffResultTest.java
@@ -117,19 +117,19 @@ public void testToStringSpecifyStyleOutput() {
 
     @Test
     public void testNullLhs() {
-        assertThrows(IllegalArgumentException.class,
+        assertThrows(NullPointerException.class,
             () -> new DiffResult(null, SIMPLE_FALSE, SIMPLE_TRUE.diff(SIMPLE_FALSE).getDiffs(), SHORT_STYLE));
     }
 
     @Test
     public void testNullRhs() {
-        assertThrows(IllegalArgumentException.class,
+        assertThrows(NullPointerException.class,
             () -> new DiffResult(SIMPLE_TRUE, null, SIMPLE_TRUE.diff(SIMPLE_FALSE).getDiffs(), SHORT_STYLE));
     }
 
     @Test
     public void testNullList() {
-        assertThrows(IllegalArgumentException.class,
+        assertThrows(NullPointerException.class,
             () -> new DiffResult(SIMPLE_TRUE, SIMPLE_FALSE, null, SHORT_STYLE));
     }
 
diff --git a/src/test/java/org/apache/commons/lang3/builder/HashCodeBuilderTest.java b/src/test/java/org/apache/commons/lang3/builder/HashCodeBuilderTest.java
index 598f8998fb6..d43ea021b2d 100644
--- a/src/test/java/org/apache/commons/lang3/builder/HashCodeBuilderTest.java
+++ b/src/test/java/org/apache/commons/lang3/builder/HashCodeBuilderTest.java
@@ -180,7 +180,7 @@ public void testReflectionHashCodeEx2() {
 
     @Test
     public void testReflectionHashCodeEx3() {
-        assertThrows(IllegalArgumentException.class, () -> HashCodeBuilder.reflectionHashCode(13, 19, null, true));
+        assertThrows(NullPointerException.class, () -> HashCodeBuilder.reflectionHashCode(13, 19, null, true));
     }
 
     @Test
diff --git a/src/test/java/org/apache/commons/lang3/builder/ReflectionToStringBuilderTest.java b/src/test/java/org/apache/commons/lang3/builder/ReflectionToStringBuilderTest.java
index 39a926b21c5..b85bd9a7557 100644
--- a/src/test/java/org/apache/commons/lang3/builder/ReflectionToStringBuilderTest.java
+++ b/src/test/java/org/apache/commons/lang3/builder/ReflectionToStringBuilderTest.java
@@ -24,7 +24,7 @@ public class ReflectionToStringBuilderTest {
 
     @Test
     public void testConstructorWithNullObject() {
-        assertThrows(IllegalArgumentException.class,
+        assertThrows(NullPointerException.class,
             () -> new ReflectionToStringBuilder(null, ToStringStyle.DEFAULT_STYLE, new StringBuffer()));
     }
 
diff --git a/src/test/java/org/apache/commons/lang3/builder/ToStringBuilderTest.java b/src/test/java/org/apache/commons/lang3/builder/ToStringBuilderTest.java
index 647cd2e881f..4ca52bd8a2c 100644
--- a/src/test/java/org/apache/commons/lang3/builder/ToStringBuilderTest.java
+++ b/src/test/java/org/apache/commons/lang3/builder/ToStringBuilderTest.java
@@ -81,7 +81,7 @@ public void testGetSetDefault() {
 
     @Test
     public void testSetDefaultEx() {
-        assertThrows(IllegalArgumentException.class, () -> ToStringBuilder.setDefaultStyle(null));
+        assertThrows(NullPointerException.class, () -> ToStringBuilder.setDefaultStyle(null));
     }
 
     @Test
@@ -1278,7 +1278,7 @@ class InheritedReflectionStaticFieldsFixture extends SimpleReflectionStaticField
 
     @Test
     public void testReflectionNull() {
-        assertThrows(IllegalArgumentException.class, () -> ReflectionToStringBuilder.toString(null));
+        assertThrows(NullPointerException.class, () -> ReflectionToStringBuilder.toString(null));
     }
 
     /**
diff --git a/src/test/java/org/apache/commons/lang3/concurrent/CallableBackgroundInitializerTest.java b/src/test/java/org/apache/commons/lang3/concurrent/CallableBackgroundInitializerTest.java
index accef5c78d1..61746cc2757 100644
--- a/src/test/java/org/apache/commons/lang3/concurrent/CallableBackgroundInitializerTest.java
+++ b/src/test/java/org/apache/commons/lang3/concurrent/CallableBackgroundInitializerTest.java
@@ -39,7 +39,7 @@ public class CallableBackgroundInitializerTest  {
      */
     @Test()
     public void testInitNullCallable() {
-        assertThrows(IllegalArgumentException.class, () -> new CallableBackgroundInitializer<>(null));
+        assertThrows(NullPointerException.class, () -> new CallableBackgroundInitializer<>(null));
     }
 
     /**
@@ -64,7 +64,7 @@ public void testInitExecutor() throws InterruptedException {
     public void testInitExecutorNullCallable() throws InterruptedException {
         final ExecutorService exec = Executors.newSingleThreadExecutor();
         try {
-            assertThrows(IllegalArgumentException.class, () -> new CallableBackgroundInitializer(null, exec));
+            assertThrows(NullPointerException.class, () -> new CallableBackgroundInitializer(null, exec));
         } finally {
             exec.shutdown();
             exec.awaitTermination(1, TimeUnit.SECONDS);
diff --git a/src/test/java/org/apache/commons/lang3/concurrent/MultiBackgroundInitializerTest.java b/src/test/java/org/apache/commons/lang3/concurrent/MultiBackgroundInitializerTest.java
index 973f72b6c8b..e93005b6f12 100644
--- a/src/test/java/org/apache/commons/lang3/concurrent/MultiBackgroundInitializerTest.java
+++ b/src/test/java/org/apache/commons/lang3/concurrent/MultiBackgroundInitializerTest.java
@@ -72,7 +72,7 @@ private void checkChild(final BackgroundInitializer child,
      */
     @Test
     public void testAddInitializerNullName() {
-        assertThrows(IllegalArgumentException.class, () -> initializer.addInitializer(null, new ChildBackgroundInitializer()));
+        assertThrows(NullPointerException.class, () -> initializer.addInitializer(null, new ChildBackgroundInitializer()));
     }
 
     /**
@@ -81,7 +81,7 @@ public void testAddInitializerNullName() {
      */
     @Test
     public void testAddInitializerNullInit() {
-        assertThrows(IllegalArgumentException.class, () -> initializer.addInitializer(CHILD_INIT, null));
+        assertThrows(NullPointerException.class, () -> initializer.addInitializer(CHILD_INIT, null));
     }
 
     /**
diff --git a/src/test/java/org/apache/commons/lang3/exception/ExceptionUtilsTest.java b/src/test/java/org/apache/commons/lang3/exception/ExceptionUtilsTest.java
index 7a4b338c778..28650568bca 100644
--- a/src/test/java/org/apache/commons/lang3/exception/ExceptionUtilsTest.java
+++ b/src/test/java/org/apache/commons/lang3/exception/ExceptionUtilsTest.java
@@ -521,7 +521,7 @@ public void testPrintRootCauseStackTrace_ThrowableStream() {
 
         out = new ByteArrayOutputStream(1024);
         assertThrows(
-                IllegalArgumentException.class,
+                NullPointerException.class,
                 () -> ExceptionUtils.printRootCauseStackTrace(withCause, (PrintStream) null));
 
         out = new ByteArrayOutputStream(1024);
@@ -545,7 +545,7 @@ public void testPrintRootCauseStackTrace_ThrowableWriter() {
 
         writer = new StringWriter(1024);
         assertThrows(
-                IllegalArgumentException.class,
+                NullPointerException.class,
                 () -> ExceptionUtils.printRootCauseStackTrace(withCause, (PrintWriter) null));
 
         writer = new StringWriter(1024);
diff --git a/src/test/java/org/apache/commons/lang3/math/FractionTest.java b/src/test/java/org/apache/commons/lang3/math/FractionTest.java
index 10daae01ceb..ff953cfba2f 100644
--- a/src/test/java/org/apache/commons/lang3/math/FractionTest.java
+++ b/src/test/java/org/apache/commons/lang3/math/FractionTest.java
@@ -324,7 +324,7 @@ public void testFactory_double() {
 
     @Test
     public void testFactory_String() {
-        assertThrows(IllegalArgumentException.class, () -> Fraction.getFraction(null));
+        assertThrows(NullPointerException.class, () -> Fraction.getFraction(null));
     }
 
 
@@ -741,7 +741,7 @@ public void testAdd() {
         assertEquals(13*13*17*2*2, fr.getDenominator());
         assertEquals(-17 - 2*13*2, fr.getNumerator());
 
-        assertThrows(IllegalArgumentException.class, () -> fr.add(null));
+        assertThrows(NullPointerException.class, () -> fr.add(null));
 
         // if this fraction is added naively, it will overflow.
         // check that it doesn't.
@@ -836,7 +836,7 @@ public void testSubtract() {
         assertSame(f2, f);
 
         final Fraction fr = f;
-        assertThrows(IllegalArgumentException.class, () -> fr.subtract(null));
+        assertThrows(NullPointerException.class, () -> fr.subtract(null));
 
         // if this fraction is subtracted naively, it will overflow.
         // check that it doesn't.
@@ -934,7 +934,7 @@ public void testMultiply() {
         assertEquals(1, f.getDenominator());
 
         final Fraction fr = f;
-        assertThrows(IllegalArgumentException.class, () -> fr.multiplyBy(null));
+        assertThrows(NullPointerException.class, () -> fr.multiplyBy(null));
 
         final Fraction fr1 = Fraction.getFraction(1, Integer.MAX_VALUE);
         assertThrows(ArithmeticException.class, () -> fr1.multiplyBy(fr1));
@@ -979,7 +979,7 @@ public void testDivide() {
         assertEquals(Integer.MIN_VALUE, fr.getNumerator());
         assertEquals(1, fr.getDenominator());
 
-        assertThrows(IllegalArgumentException.class, () -> fr.divideBy(null));
+        assertThrows(NullPointerException.class, () -> fr.divideBy(null));
 
         final Fraction smallest = Fraction.getFraction(1, Integer.MAX_VALUE);
         assertThrows(ArithmeticException.class, () -> smallest.divideBy(smallest.invert())); // Should overflow
diff --git a/src/test/java/org/apache/commons/lang3/math/IEEE754rUtilsTest.java b/src/test/java/org/apache/commons/lang3/math/IEEE754rUtilsTest.java
index 2caf60be268..39fe5cd6fa3 100644
--- a/src/test/java/org/apache/commons/lang3/math/IEEE754rUtilsTest.java
+++ b/src/test/java/org/apache/commons/lang3/math/IEEE754rUtilsTest.java
@@ -56,7 +56,7 @@ public void testLang381() {
     @Test
     public void testEnforceExceptions() {
         assertThrows(
-                IllegalArgumentException.class,
+                NullPointerException.class,
                 () -> IEEE754rUtils.min( (float[]) null),
                 "IllegalArgumentException expected for null input");
 
@@ -66,7 +66,7 @@ public void testEnforceExceptions() {
                 "IllegalArgumentException expected for empty input");
 
         assertThrows(
-                IllegalArgumentException.class,
+                NullPointerException.class,
                 () -> IEEE754rUtils.max( (float[]) null),
                 "IllegalArgumentException expected for null input");
 
@@ -76,7 +76,7 @@ public void testEnforceExceptions() {
                 "IllegalArgumentException expected for empty input");
 
         assertThrows(
-                IllegalArgumentException.class,
+                NullPointerException.class,
                 () -> IEEE754rUtils.min( (double[]) null),
                 "IllegalArgumentException expected for null input");
 
@@ -86,7 +86,7 @@ public void testEnforceExceptions() {
                 "IllegalArgumentException expected for empty input");
 
         assertThrows(
-                IllegalArgumentException.class,
+                NullPointerException.class,
                 () -> IEEE754rUtils.max( (double[]) null),
                 "IllegalArgumentException expected for null input");
 
diff --git a/src/test/java/org/apache/commons/lang3/math/NumberUtilsTest.java b/src/test/java/org/apache/commons/lang3/math/NumberUtilsTest.java
index 5e5c554e890..3e32c90515f 100644
--- a/src/test/java/org/apache/commons/lang3/math/NumberUtilsTest.java
+++ b/src/test/java/org/apache/commons/lang3/math/NumberUtilsTest.java
@@ -686,7 +686,7 @@ protected void testCreateBigDecimalFailure(final String str) {
     // ----------------------------------------------------------------------
     @Test
     public void testMinLong_nullArray() {
-        assertThrows(IllegalArgumentException.class, () -> NumberUtils.min((long[]) null));
+        assertThrows(NullPointerException.class, () -> NumberUtils.min((long[]) null));
     }
 
     @Test
@@ -705,7 +705,7 @@ public void testMinLong() {
 
     @Test
     public void testMinInt_nullArray() {
-        assertThrows(IllegalArgumentException.class, () -> NumberUtils.min((int[]) null));
+        assertThrows(NullPointerException.class, () -> NumberUtils.min((int[]) null));
     }
 
     @Test
@@ -724,7 +724,7 @@ public void testMinInt() {
 
     @Test
     public void testMinShort_nullArray() {
-        assertThrows(IllegalArgumentException.class, () -> NumberUtils.min((short[]) null));
+        assertThrows(NullPointerException.class, () -> NumberUtils.min((short[]) null));
     }
 
     @Test
@@ -743,7 +743,7 @@ public void testMinShort() {
 
     @Test
     public void testMinByte_nullArray() {
-        assertThrows(IllegalArgumentException.class, () -> NumberUtils.min((byte[]) null));
+        assertThrows(NullPointerException.class, () -> NumberUtils.min((byte[]) null));
     }
 
     @Test
@@ -762,7 +762,7 @@ public void testMinByte() {
 
     @Test
     public void testMinDouble_nullArray() {
-        assertThrows(IllegalArgumentException.class, () -> NumberUtils.min((double[]) null));
+        assertThrows(NullPointerException.class, () -> NumberUtils.min((double[]) null));
     }
 
     @Test
@@ -781,7 +781,7 @@ public void testMinDouble() {
 
     @Test
     public void testMinFloat_nullArray() {
-        assertThrows(IllegalArgumentException.class, () -> NumberUtils.min((float[]) null));
+        assertThrows(NullPointerException.class, () -> NumberUtils.min((float[]) null));
     }
 
     @Test
@@ -800,7 +800,7 @@ public void testMinFloat() {
 
     @Test
     public void testMaxLong_nullArray() {
-        assertThrows(IllegalArgumentException.class, () -> NumberUtils.max((long[]) null));
+        assertThrows(NullPointerException.class, () -> NumberUtils.max((long[]) null));
     }
 
     @Test
@@ -819,7 +819,7 @@ public void testMaxLong() {
 
     @Test
     public void testMaxInt_nullArray() {
-        assertThrows(IllegalArgumentException.class, () -> NumberUtils.max((int[]) null));
+        assertThrows(NullPointerException.class, () -> NumberUtils.max((int[]) null));
     }
 
     @Test
@@ -838,7 +838,7 @@ public void testMaxInt() {
 
     @Test
     public void testMaxShort_nullArray() {
-        assertThrows(IllegalArgumentException.class, () -> NumberUtils.max((short[]) null));
+        assertThrows(NullPointerException.class, () -> NumberUtils.max((short[]) null));
     }
 
     @Test
@@ -857,7 +857,7 @@ public void testMaxShort() {
 
     @Test
     public void testMaxByte_nullArray() {
-        assertThrows(IllegalArgumentException.class, () -> NumberUtils.max((byte[]) null));
+        assertThrows(NullPointerException.class, () -> NumberUtils.max((byte[]) null));
     }
 
     @Test
@@ -876,7 +876,7 @@ public void testMaxByte() {
 
     @Test
     public void testMaxDouble_nullArray() {
-        assertThrows(IllegalArgumentException.class, () -> NumberUtils.max((double[]) null));
+        assertThrows(NullPointerException.class, () -> NumberUtils.max((double[]) null));
     }
 
     @Test
@@ -888,7 +888,7 @@ public void testMaxDouble_emptyArray() {
     public void testMaxDouble() {
         final double[] d = null;
         assertThrows(
-                IllegalArgumentException.class, () -> NumberUtils.max(d), "No exception was thrown for null input.");
+            NullPointerException.class, () -> NumberUtils.max(d), "No exception was thrown for null input.");
 
         assertThrows(
                 IllegalArgumentException.class,
@@ -904,7 +904,7 @@ public void testMaxDouble() {
 
     @Test
     public void testMaxFloat_nullArray() {
-        assertThrows(IllegalArgumentException.class, () -> NumberUtils.max((float[]) null));
+        assertThrows(NullPointerException.class, () -> NumberUtils.max((float[]) null));
     }
 
     @Test
diff --git a/src/test/java/org/apache/commons/lang3/reflect/FieldUtilsTest.java b/src/test/java/org/apache/commons/lang3/reflect/FieldUtilsTest.java
index 9db1f807056..20ae2acadb8 100644
--- a/src/test/java/org/apache/commons/lang3/reflect/FieldUtilsTest.java
+++ b/src/test/java/org/apache/commons/lang3/reflect/FieldUtilsTest.java
@@ -106,7 +106,7 @@ public void testGetField() {
 
     @Test
     public void testGetFieldIllegalArgumentException1() {
-        assertThrows(IllegalArgumentException.class, () -> FieldUtils.getField(null, "none"));
+        assertThrows(NullPointerException.class, () -> FieldUtils.getField(null, "none"));
     }
 
     @Test
@@ -145,7 +145,7 @@ public void testGetFieldForceAccess() {
 
     @Test
     public void testGetFieldForceAccessIllegalArgumentException1() {
-        assertThrows(IllegalArgumentException.class, () -> FieldUtils.getField(null, "none", true));
+        assertThrows(NullPointerException.class, () -> FieldUtils.getField(null, "none", true));
     }
 
     @Test
@@ -214,17 +214,17 @@ public void testGetFieldsWithAnnotation() throws NoSuchFieldException {
 
     @Test
     public void testGetFieldsWithAnnotationIllegalArgumentException1() {
-        assertThrows(IllegalArgumentException.class, () -> FieldUtils.getFieldsWithAnnotation(FieldUtilsTest.class, null));
+        assertThrows(NullPointerException.class, () -> FieldUtils.getFieldsWithAnnotation(FieldUtilsTest.class, null));
     }
 
     @Test
     public void testGetFieldsWithAnnotationIllegalArgumentException2() {
-        assertThrows(IllegalArgumentException.class, () -> FieldUtils.getFieldsWithAnnotation(null, Annotated.class));
+        assertThrows(NullPointerException.class, () -> FieldUtils.getFieldsWithAnnotation(null, Annotated.class));
     }
 
     @Test
     public void testGetFieldsWithAnnotationIllegalArgumentException3() {
-        assertThrows(IllegalArgumentException.class, () -> FieldUtils.getFieldsWithAnnotation(null, null));
+        assertThrows(NullPointerException.class, () -> FieldUtils.getFieldsWithAnnotation(null, null));
     }
 
     @Test
@@ -242,17 +242,17 @@ public void testGetFieldsListWithAnnotation() throws NoSuchFieldException {
 
     @Test
     public void testGetFieldsListWithAnnotationIllegalArgumentException1() {
-        assertThrows(IllegalArgumentException.class, () -> FieldUtils.getFieldsListWithAnnotation(FieldUtilsTest.class, null));
+        assertThrows(NullPointerException.class, () -> FieldUtils.getFieldsListWithAnnotation(FieldUtilsTest.class, null));
     }
 
     @Test
     public void testGetFieldsListWithAnnotationIllegalArgumentException2() {
-        assertThrows(IllegalArgumentException.class, () -> FieldUtils.getFieldsListWithAnnotation(null, Annotated.class));
+        assertThrows(NullPointerException.class, () -> FieldUtils.getFieldsListWithAnnotation(null, Annotated.class));
     }
 
     @Test
     public void testGetFieldsListWithAnnotationIllegalArgumentException3() {
-        assertThrows(IllegalArgumentException.class, () -> FieldUtils.getFieldsListWithAnnotation(null, null));
+        assertThrows(NullPointerException.class, () -> FieldUtils.getFieldsListWithAnnotation(null, null));
     }
 
     @Test
@@ -276,7 +276,7 @@ public void testGetDeclaredField() {
 
     @Test
     public void testGetDeclaredFieldAccessIllegalArgumentException1() {
-        assertThrows(IllegalArgumentException.class, () -> FieldUtils.getDeclaredField(null, "none"));
+        assertThrows(NullPointerException.class, () -> FieldUtils.getDeclaredField(null, "none"));
     }
 
     @Test
@@ -315,7 +315,7 @@ public void testGetDeclaredFieldForceAccess() {
 
     @Test
     public void testGetDeclaredFieldForceAccessIllegalArgumentException1() {
-        assertThrows(IllegalArgumentException.class, () -> FieldUtils.getDeclaredField(null, "none", true));
+        assertThrows(NullPointerException.class, () -> FieldUtils.getDeclaredField(null, "none", true));
     }
 
     @Test
@@ -340,7 +340,7 @@ public void testReadStaticField() throws Exception {
 
     @Test
     public void testReadStaticFieldIllegalArgumentException1() {
-        assertThrows(IllegalArgumentException.class, () -> FieldUtils.readStaticField(null));
+        assertThrows(NullPointerException.class, () -> FieldUtils.readStaticField(null));
     }
 
     @Test
@@ -359,7 +359,7 @@ public void testReadStaticFieldForceAccess() throws Exception {
 
     @Test
     public void testReadStaticFieldForceAccessIllegalArgumentException1() {
-        assertThrows(IllegalArgumentException.class, () -> FieldUtils.readStaticField(null, true));
+        assertThrows(NullPointerException.class, () -> FieldUtils.readStaticField(null, true));
     }
 
     @Test
@@ -377,7 +377,7 @@ public void testReadNamedStaticField() throws Exception {
         assertEquals(Foo.VALUE, FieldUtils.readStaticField(PublicChild.class, "VALUE"));
 
         assertThrows(
-                IllegalArgumentException.class,
+                NullPointerException.class,
                 () -> FieldUtils.readStaticField(null, "none"),
                 "null class should cause an IllegalArgumentException");
 
@@ -397,7 +397,7 @@ public void testReadNamedStaticField() throws Exception {
                 "blank field name should cause an IllegalArgumentException");
 
         assertThrows(
-                IllegalArgumentException.class,
+                NullPointerException.class,
                 () -> FieldUtils.readStaticField(Foo.class, "does_not_exist"),
                 "a field that doesn't exist should cause an IllegalArgumentException");
 
@@ -415,7 +415,7 @@ public void testReadNamedStaticFieldForceAccess() throws Exception {
         assertEquals("child", FieldUtils.readStaticField(PublicChild.class, "VALUE", true));
 
         assertThrows(
-                IllegalArgumentException.class,
+                NullPointerException.class,
                 () -> FieldUtils.readStaticField(null, "none", true),
                 "null class should cause an IllegalArgumentException");
 
@@ -435,7 +435,7 @@ public void testReadNamedStaticFieldForceAccess() throws Exception {
                 "blank field name should cause an IllegalArgumentException");
 
         assertThrows(
-                IllegalArgumentException.class,
+                NullPointerException.class,
                 () -> FieldUtils.readStaticField(Foo.class, "does_not_exist", true),
                 "a field that doesn't exist should cause an IllegalArgumentException");
 
@@ -449,12 +449,12 @@ public void testReadNamedStaticFieldForceAccess() throws Exception {
     public void testReadDeclaredNamedStaticField() throws Exception {
         assertEquals(Foo.VALUE, FieldUtils.readDeclaredStaticField(Foo.class, "VALUE"));
         assertThrows(
-                IllegalArgumentException.class, () -> FieldUtils.readDeclaredStaticField(PublicChild.class, "VALUE"));
+                NullPointerException.class, () -> FieldUtils.readDeclaredStaticField(PublicChild.class, "VALUE"));
         assertThrows(
-                IllegalArgumentException.class,
+                NullPointerException.class,
                 () -> FieldUtils.readDeclaredStaticField(PubliclyShadowedChild.class, "VALUE"));
         assertThrows(
-                IllegalArgumentException.class,
+                NullPointerException.class,
                 () -> FieldUtils.readDeclaredStaticField(PrivatelyShadowedChild.class, "VALUE"));
     }
 
@@ -463,10 +463,10 @@ public void testReadDeclaredNamedStaticFieldForceAccess() throws Exception {
         assertEquals(Foo.VALUE, FieldUtils.readDeclaredStaticField(Foo.class, "VALUE", true));
         assertEquals("child", FieldUtils.readDeclaredStaticField(PublicChild.class, "VALUE", true));
         assertThrows(
-                IllegalArgumentException.class,
+                NullPointerException.class,
                 () -> FieldUtils.readDeclaredStaticField(PubliclyShadowedChild.class, "VALUE", true));
         assertThrows(
-                IllegalArgumentException.class,
+                NullPointerException.class,
                 () -> FieldUtils.readDeclaredStaticField(PrivatelyShadowedChild.class, "VALUE", true));
     }
 
@@ -490,7 +490,7 @@ public void testReadField() throws Exception {
         assertEquals(D0, FieldUtils.readField(parentD, privatelyShadowedChild));
 
         assertThrows(
-                IllegalArgumentException.class,
+                NullPointerException.class,
                 () -> FieldUtils.readField(null, publicChild),
                 "a null field should cause an IllegalArgumentException");
     }
@@ -519,7 +519,7 @@ public void testReadFieldForceAccess() throws Exception {
         assertEquals(D0, FieldUtils.readField(parentD, privatelyShadowedChild, true));
 
         assertThrows(
-                IllegalArgumentException.class,
+                NullPointerException.class,
                 () -> FieldUtils.readField(null, publicChild, true),
                 "a null field should cause an IllegalArgumentException");
     }
@@ -546,7 +546,7 @@ public void testReadNamedField() throws Exception {
                 "a blank field name should cause an IllegalArgumentException");
 
         assertThrows(
-                IllegalArgumentException.class,
+                NullPointerException.class,
                 () -> FieldUtils.readField((Object) null, "none"),
                 "a null target should cause an IllegalArgumentException");
 
@@ -593,7 +593,7 @@ public void testReadNamedFieldForceAccess() throws Exception {
                 "a blank field name should cause an IllegalArgumentException");
 
         assertThrows(
-                IllegalArgumentException.class,
+                NullPointerException.class,
                 () -> FieldUtils.readField((Object) null, "none", true),
                 "a null target should cause an IllegalArgumentException");
     }
@@ -616,7 +616,7 @@ public void testReadDeclaredNamedField() throws Exception {
                 "a blank field name should cause an IllegalArgumentException");
 
         assertThrows(
-                IllegalArgumentException.class,
+                NullPointerException.class,
                 () -> FieldUtils.readDeclaredField(null, "none"),
                 "a null target should cause an IllegalArgumentException");
 
@@ -652,7 +652,7 @@ public void testReadDeclaredNamedFieldForceAccess() throws Exception {
                 "a blank field name should cause an IllegalArgumentException");
 
         assertThrows(
-                IllegalArgumentException.class,
+                NullPointerException.class,
                 () -> FieldUtils.readDeclaredField(null, "none", true),
                 "a null target should cause an IllegalArgumentException");
 
@@ -731,25 +731,25 @@ public void testWriteNamedStaticField() throws Exception {
         FieldUtils.writeStaticField(StaticContainerChild.class, "mutablePublic", "new");
         assertEquals("new", StaticContainer.mutablePublic);
         assertThrows(
-                IllegalArgumentException.class,
+                NullPointerException.class,
                 () -> FieldUtils.writeStaticField(StaticContainerChild.class, "mutableProtected", "new"));
         assertThrows(
-                IllegalArgumentException.class,
+                NullPointerException.class,
                 () -> FieldUtils.writeStaticField(StaticContainerChild.class, "mutablePackage", "new"));
         assertThrows(
-                IllegalArgumentException.class,
+                NullPointerException.class,
                 () -> FieldUtils.writeStaticField(StaticContainerChild.class, "mutablePrivate", "new"));
         assertThrows(
                 IllegalAccessException.class,
                 () -> FieldUtils.writeStaticField(StaticContainerChild.class, "IMMUTABLE_PUBLIC", "new"));
         assertThrows(
-                IllegalArgumentException.class,
+                NullPointerException.class,
                 () -> FieldUtils.writeStaticField(StaticContainerChild.class, "IMMUTABLE_PROTECTED", "new"));
         assertThrows(
-                IllegalArgumentException.class,
+                NullPointerException.class,
                 () -> FieldUtils.writeStaticField(StaticContainerChild.class, "IMMUTABLE_PACKAGE", "new"));
         assertThrows(
-                IllegalArgumentException.class,
+                NullPointerException.class,
                 () -> FieldUtils.writeStaticField(StaticContainerChild.class, "IMMUTABLE_PRIVATE", "new"));
     }
 
@@ -782,25 +782,25 @@ public void testWriteDeclaredNamedStaticField() throws Exception {
         FieldUtils.writeStaticField(StaticContainer.class, "mutablePublic", "new");
         assertEquals("new", StaticContainer.mutablePublic);
         assertThrows(
-                IllegalArgumentException.class,
+                NullPointerException.class,
                 () -> FieldUtils.writeDeclaredStaticField(StaticContainer.class, "mutableProtected", "new"));
         assertThrows(
-                IllegalArgumentException.class,
+                NullPointerException.class,
                 () -> FieldUtils.writeDeclaredStaticField(StaticContainer.class, "mutablePackage", "new"));
         assertThrows(
-                IllegalArgumentException.class,
+                NullPointerException.class,
                 () -> FieldUtils.writeDeclaredStaticField(StaticContainer.class, "mutablePrivate", "new"));
         assertThrows(
                 IllegalAccessException.class,
                 () -> FieldUtils.writeDeclaredStaticField(StaticContainer.class, "IMMUTABLE_PUBLIC", "new"));
         assertThrows(
-                IllegalArgumentException.class,
+                NullPointerException.class,
                 () -> FieldUtils.writeDeclaredStaticField(StaticContainer.class, "IMMUTABLE_PROTECTED", "new"));
         assertThrows(
-                IllegalArgumentException.class,
+                NullPointerException.class,
                 () -> FieldUtils.writeDeclaredStaticField(StaticContainer.class, "IMMUTABLE_PACKAGE", "new"));
         assertThrows(
-                IllegalArgumentException.class,
+                NullPointerException.class,
                 () -> FieldUtils.writeDeclaredStaticField(StaticContainer.class, "IMMUTABLE_PRIVATE", "new"));
     }
 
diff --git a/src/test/java/org/apache/commons/lang3/reflect/MethodUtilsTest.java b/src/test/java/org/apache/commons/lang3/reflect/MethodUtilsTest.java
index ab40b22df90..9966efe21b4 100644
--- a/src/test/java/org/apache/commons/lang3/reflect/MethodUtilsTest.java
+++ b/src/test/java/org/apache/commons/lang3/reflect/MethodUtilsTest.java
@@ -868,12 +868,12 @@ public void testGetMethodsWithAnnotationIllegalArgumentException1() {
 
     @Test
     public void testGetMethodsWithAnnotationIllegalArgumentException2() {
-        assertThrows(IllegalArgumentException.class, () -> MethodUtils.getMethodsWithAnnotation(null, Annotated.class));
+        assertThrows(NullPointerException.class, () -> MethodUtils.getMethodsWithAnnotation(null, Annotated.class));
     }
 
     @Test
     public void testGetMethodsWithAnnotationIllegalArgumentException3() {
-        assertThrows(IllegalArgumentException.class, () -> MethodUtils.getMethodsWithAnnotation(null, null));
+        assertThrows(NullPointerException.class, () -> MethodUtils.getMethodsWithAnnotation(null, null));
     }
 
     @Test
@@ -896,12 +896,12 @@ public void testGetMethodsListWithAnnotationIllegalArgumentException1() {
 
     @Test
     public void testGetMethodsListWithAnnotationIllegalArgumentException2() {
-        assertThrows(IllegalArgumentException.class, () -> MethodUtils.getMethodsListWithAnnotation(null, Annotated.class));
+        assertThrows(NullPointerException.class, () -> MethodUtils.getMethodsListWithAnnotation(null, Annotated.class));
     }
 
     @Test
     public void testGetMethodsListWithAnnotationIllegalArgumentException3() {
-        assertThrows(IllegalArgumentException.class, () -> MethodUtils.getMethodsListWithAnnotation(null, null));
+        assertThrows(NullPointerException.class, () -> MethodUtils.getMethodsListWithAnnotation(null, null));
     }
 
     @Test
@@ -912,12 +912,12 @@ public void testGetAnnotationIllegalArgumentException1() {
 
     @Test
     public void testGetAnnotationIllegalArgumentException2() {
-        assertThrows(IllegalArgumentException.class, () -> MethodUtils.getAnnotation(null, Annotated.class, true, true));
+        assertThrows(NullPointerException.class, () -> MethodUtils.getAnnotation(null, Annotated.class, true, true));
     }
 
     @Test
     public void testGetAnnotationIllegalArgumentException3() {
-        assertThrows(IllegalArgumentException.class, () -> MethodUtils.getAnnotation(null, null, true, true));
+        assertThrows(NullPointerException.class, () -> MethodUtils.getAnnotation(null, null, true, true));
     }
 
     private void expectMatchingAccessibleMethodParameterTypes(final Class cls,
diff --git a/src/test/java/org/apache/commons/lang3/time/DateUtilsFragmentTest.java b/src/test/java/org/apache/commons/lang3/time/DateUtilsFragmentTest.java
index 5f65d0e0b19..be6f23ba164 100644
--- a/src/test/java/org/apache/commons/lang3/time/DateUtilsFragmentTest.java
+++ b/src/test/java/org/apache/commons/lang3/time/DateUtilsFragmentTest.java
@@ -49,23 +49,23 @@ public void setUp() {
     @Test
     public void testNullDate() {
         assertThrows(
-                IllegalArgumentException.class,
+                NullPointerException.class,
                 () -> DateUtils.getFragmentInMilliseconds((Date) null, Calendar.MILLISECOND));
 
         assertThrows(
-                IllegalArgumentException.class,
+                NullPointerException.class,
                 () -> DateUtils.getFragmentInSeconds((Date) null, Calendar.MILLISECOND));
 
         assertThrows(
-                IllegalArgumentException.class,
+                NullPointerException.class,
                 () -> DateUtils.getFragmentInMinutes((Date) null, Calendar.MILLISECOND));
 
         assertThrows(
-                IllegalArgumentException.class,
+                NullPointerException.class,
                 () -> DateUtils.getFragmentInHours((Date) null, Calendar.MILLISECOND));
 
         assertThrows(
-                IllegalArgumentException.class,
+                NullPointerException.class,
                 () -> DateUtils.getFragmentInDays((Date) null, Calendar.MILLISECOND));
     }
 
diff --git a/src/test/java/org/apache/commons/lang3/time/DateUtilsTest.java b/src/test/java/org/apache/commons/lang3/time/DateUtilsTest.java
index 64cfde87d8c..14dbf89c2d1 100644
--- a/src/test/java/org/apache/commons/lang3/time/DateUtilsTest.java
+++ b/src/test/java/org/apache/commons/lang3/time/DateUtilsTest.java
@@ -830,7 +830,7 @@ public void testRound() throws Exception {
                 DateUtils.round((Object) dateAmPm4, Calendar.AM_PM),
                 "round ampm-4 failed");
 
-        assertThrows(IllegalArgumentException.class, () -> DateUtils.round((Date) null, Calendar.SECOND));
+        assertThrows(NullPointerException.class, () -> DateUtils.round((Date) null, Calendar.SECOND));
         assertThrows(IllegalArgumentException.class, () -> DateUtils.round((Calendar) null, Calendar.SECOND));
         assertThrows(IllegalArgumentException.class, () -> DateUtils.round((Object) null, Calendar.SECOND));
         assertThrows(ClassCastException.class, () -> DateUtils.round("", Calendar.SECOND));
@@ -1111,7 +1111,7 @@ public void testTruncate() throws Exception {
                 DateUtils.truncate((Object) calAmPm4, Calendar.AM_PM),
                 "truncate ampm-4 failed");
 
-        assertThrows(IllegalArgumentException.class, () -> DateUtils.truncate((Date) null, Calendar.SECOND));
+        assertThrows(NullPointerException.class, () -> DateUtils.truncate((Date) null, Calendar.SECOND));
         assertThrows(IllegalArgumentException.class, () -> DateUtils.truncate((Calendar) null, Calendar.SECOND));
         assertThrows(IllegalArgumentException.class, () -> DateUtils.truncate((Object) null, Calendar.SECOND));
         assertThrows(ClassCastException.class, () -> DateUtils.truncate("", Calendar.SECOND));
@@ -1389,7 +1389,7 @@ public void testCeil() throws Exception {
                 DateUtils.ceiling((Object) calAmPm4, Calendar.AM_PM),
                 "ceiling ampm-4 failed");
 
-        assertThrows(IllegalArgumentException.class, () -> DateUtils.ceiling((Date) null, Calendar.SECOND));
+        assertThrows(NullPointerException.class, () -> DateUtils.ceiling((Date) null, Calendar.SECOND));
         assertThrows(IllegalArgumentException.class, () -> DateUtils.ceiling((Calendar) null, Calendar.SECOND));
         assertThrows(IllegalArgumentException.class, () -> DateUtils.ceiling((Object) null, Calendar.SECOND));
         assertThrows(ClassCastException.class, () -> DateUtils.ceiling("", Calendar.SECOND));
@@ -1475,7 +1475,7 @@ public void testCeil() throws Exception {
     public void testIteratorEx() {
         assertThrows(IllegalArgumentException.class, () -> DateUtils.iterator(Calendar.getInstance(), -9999));
         assertThrows
-                (IllegalArgumentException.class, () -> DateUtils.iterator((Date) null, DateUtils.RANGE_WEEK_CENTER));
+                (NullPointerException.class, () -> DateUtils.iterator((Date) null, DateUtils.RANGE_WEEK_CENTER));
         assertThrows
                 (IllegalArgumentException.class, () -> DateUtils.iterator((Calendar) null, DateUtils.RANGE_WEEK_CENTER));
         assertThrows

From fde46a232d82f2b746f62bc7546e2e3371f20dca Mon Sep 17 00:00:00 2001
From: Dominik Schramm <1610640051@fh-burgenland.at>
Date: Sat, 7 Mar 2020 16:58:19 +0100
Subject: [PATCH 0044/3230]  Added 1 and 0 in toBooleanObject(final String str)
  (#502)

* Added 1 and 0 in toBooleanObject(String)

* Added 1 and 0 in toBooleanObject(String)

 - Documentation
 - Tests
---
 .../org/apache/commons/lang3/BooleanUtils.java   | 16 ++++++++++------
 .../apache/commons/lang3/BooleanUtilsTest.java   |  4 ++++
 2 files changed, 14 insertions(+), 6 deletions(-)

diff --git a/src/main/java/org/apache/commons/lang3/BooleanUtils.java b/src/main/java/org/apache/commons/lang3/BooleanUtils.java
index 9dbcc65634b..7cf3794610a 100644
--- a/src/main/java/org/apache/commons/lang3/BooleanUtils.java
+++ b/src/main/java/org/apache/commons/lang3/BooleanUtils.java
@@ -532,10 +532,10 @@ public static Integer toIntegerObject(final Boolean bool, final Integer trueValu
     /**
      * 

Converts a String to a Boolean.

* - *

{@code 'true'}, {@code 'on'}, {@code 'y'}, {@code 't'} or {@code 'yes'} - * (case insensitive) will return {@code true}. - * {@code 'false'}, {@code 'off'}, {@code 'n'}, {@code 'f'} or {@code 'no'} - * (case insensitive) will return {@code false}. + *

{@code 'true'}, {@code 'on'}, {@code 'y'}, {@code 't'}, {@code 'yes'} + * or {@code '1'} (case insensitive) will return {@code true}. + * {@code 'false'}, {@code 'off'}, {@code 'n'}, {@code 'f'}, {@code 'no'} + * or {@code '0'} (case insensitive) will return {@code false}. * Otherwise, {@code null} is returned.

* *

NOTE: This method may return {@code null} and may throw a {@code NullPointerException} @@ -556,6 +556,8 @@ public static Integer toIntegerObject(final Boolean bool, final Integer trueValu * BooleanUtils.toBooleanObject("oFf") = Boolean.FALSE * BooleanUtils.toBooleanObject("yes") = Boolean.TRUE * BooleanUtils.toBooleanObject("Y") = Boolean.TRUE // i.e. Y[ES] + * BooleanUtils.toBooleanObject("1") = Boolean.TRUE + * BooleanUtils.toBooleanObject("0") = Boolean.FALSE * BooleanUtils.toBooleanObject("blue") = null * BooleanUtils.toBooleanObject("true ") = null // trailing space (too long) * BooleanUtils.toBooleanObject("ono") = null // does not match on or no @@ -581,11 +583,13 @@ public static Boolean toBooleanObject(final String str) { case 1: { final char ch0 = str.charAt(0); if (ch0 == 'y' || ch0 == 'Y' || - ch0 == 't' || ch0 == 'T') { + ch0 == 't' || ch0 == 'T' || + ch0 == '1') { return Boolean.TRUE; } if (ch0 == 'n' || ch0 == 'N' || - ch0 == 'f' || ch0 == 'F') { + ch0 == 'f' || ch0 == 'F' || + ch0 == '0') { return Boolean.FALSE; } break; diff --git a/src/test/java/org/apache/commons/lang3/BooleanUtilsTest.java b/src/test/java/org/apache/commons/lang3/BooleanUtilsTest.java index c25c22ef2a8..a70272fbc96 100644 --- a/src/test/java/org/apache/commons/lang3/BooleanUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/BooleanUtilsTest.java @@ -280,10 +280,12 @@ public void test_toBooleanObject_String() { assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject("Y")); assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject("t")); // true assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject("T")); + assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject("1")); assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject("f")); // false assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject("F")); assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject("n")); // No assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject("N")); + assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject("0")); assertNull(BooleanUtils.toBooleanObject("z")); assertNull(BooleanUtils.toBooleanObject("ab")); @@ -353,7 +355,9 @@ public void test_toBoolean_String() { assertTrue(BooleanUtils.toBoolean("YeS")); assertTrue(BooleanUtils.toBoolean("YEs")); assertTrue(BooleanUtils.toBoolean("YES")); + assertTrue(BooleanUtils.toBoolean("1")); assertFalse(BooleanUtils.toBoolean("yes?")); + assertFalse(BooleanUtils.toBoolean("0")); assertFalse(BooleanUtils.toBoolean("tru")); assertFalse(BooleanUtils.toBoolean("no")); From 893cc1512bcee1929b713e1be9c4acceba54cc14 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Tue, 10 Mar 2020 16:49:06 -0400 Subject: [PATCH 0045/3230] [LANG-1526] Add 1 and 0 in toBooleanObject(final String str) #502. --- src/changes/changes.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index a97452f5829..b636c88272f 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -107,6 +107,7 @@ The type attribute can be add,update,fix,remove. MethodUtils.getAnnotation() with searchSupers = true does not work if super is generic #494. Avoid unnecessary allocation in StringUtils.wrapIfMissing. #496. Internally use Validate.notNull(foo, ...) instead of Validate.isTrue(foo != null, ...). + Add 1 and 0 in toBooleanObject(final String str) #502. From 02732d6132da6e720502f357e91e3937df76d8fa Mon Sep 17 00:00:00 2001 From: Prodigysov Date: Sun, 15 Mar 2020 15:34:25 -0500 Subject: [PATCH 0046/3230] LANG-1527: Remove an redundant argument check in NumberUtils. (#504) --- .../java/org/apache/commons/lang3/math/NumberUtils.java | 7 ------- 1 file changed, 7 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/math/NumberUtils.java b/src/main/java/org/apache/commons/lang3/math/NumberUtils.java index ab7badc19c0..38240c2d161 100644 --- a/src/main/java/org/apache/commons/lang3/math/NumberUtils.java +++ b/src/main/java/org/apache/commons/lang3/math/NumberUtils.java @@ -987,13 +987,6 @@ public static BigDecimal createBigDecimal(final String str) { if (StringUtils.isBlank(str)) { throw new NumberFormatException("A blank string is not a valid number"); } - if (str.trim().startsWith("--")) { - // this is protection for poorness in java.lang.BigDecimal. - // it accepts this as a legal value, but it does not appear - // to be in specification of class. OS X Java parses it to - // a wrong value. - throw new NumberFormatException(str + " is not a valid number."); - } return new BigDecimal(str); } From 6240c11f225e68bab717ee0c188e10ac479ba035 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sun, 15 Mar 2020 16:37:58 -0400 Subject: [PATCH 0047/3230] [LANG-1527] NumberUtils.createBigDecimal has a redundant argument check. --- src/changes/changes.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index b636c88272f..778dfe80be8 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -108,6 +108,7 @@ The type attribute can be add,update,fix,remove. Avoid unnecessary allocation in StringUtils.wrapIfMissing. #496. Internally use Validate.notNull(foo, ...) instead of Validate.isTrue(foo != null, ...). Add 1 and 0 in toBooleanObject(final String str) #502. + Remove an redundant argument check in NumberUtils #504. From 1c42dfb05791a1172e03d355d296327c013177f9 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Thu, 19 Mar 2020 10:00:46 -0400 Subject: [PATCH 0048/3230] Clean ups. --- .../commons/lang3/builder/EqualsExclude.java | 2 +- .../lang3/builder/HashCodeExclude.java | 2 +- .../lang3/builder/ToStringExclude.java | 2 +- .../lang3/builder/ToStringSummary.java | 2 +- .../commons/lang3/reflect/TypeUtils.java | 241 +++++++++--------- .../translate/NumericEntityUnescaper.java | 4 +- 6 files changed, 132 insertions(+), 121 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/builder/EqualsExclude.java b/src/main/java/org/apache/commons/lang3/builder/EqualsExclude.java index f6b4d3ec559..b4ede8f1ecf 100755 --- a/src/main/java/org/apache/commons/lang3/builder/EqualsExclude.java +++ b/src/main/java/org/apache/commons/lang3/builder/EqualsExclude.java @@ -32,5 +32,5 @@ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface EqualsExclude { - + // empty } diff --git a/src/main/java/org/apache/commons/lang3/builder/HashCodeExclude.java b/src/main/java/org/apache/commons/lang3/builder/HashCodeExclude.java index e25a168d83f..d1c3661da26 100755 --- a/src/main/java/org/apache/commons/lang3/builder/HashCodeExclude.java +++ b/src/main/java/org/apache/commons/lang3/builder/HashCodeExclude.java @@ -32,5 +32,5 @@ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface HashCodeExclude { - + // empty } diff --git a/src/main/java/org/apache/commons/lang3/builder/ToStringExclude.java b/src/main/java/org/apache/commons/lang3/builder/ToStringExclude.java index e36acce6470..41dcf67396d 100755 --- a/src/main/java/org/apache/commons/lang3/builder/ToStringExclude.java +++ b/src/main/java/org/apache/commons/lang3/builder/ToStringExclude.java @@ -31,5 +31,5 @@ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface ToStringExclude { - + // empty } diff --git a/src/main/java/org/apache/commons/lang3/builder/ToStringSummary.java b/src/main/java/org/apache/commons/lang3/builder/ToStringSummary.java index ba255d4e951..c6dad14f425 100644 --- a/src/main/java/org/apache/commons/lang3/builder/ToStringSummary.java +++ b/src/main/java/org/apache/commons/lang3/builder/ToStringSummary.java @@ -36,5 +36,5 @@ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface ToStringSummary { - + // empty } diff --git a/src/main/java/org/apache/commons/lang3/reflect/TypeUtils.java b/src/main/java/org/apache/commons/lang3/reflect/TypeUtils.java index eced4e08294..aea37a7f882 100644 --- a/src/main/java/org/apache/commons/lang3/reflect/TypeUtils.java +++ b/src/main/java/org/apache/commons/lang3/reflect/TypeUtils.java @@ -150,12 +150,12 @@ private static final class ParameterizedTypeImpl implements ParameterizedType { /** * Constructor - * @param raw type + * @param rawClass type * @param useOwner owner type to use, if any * @param typeArguments formal type arguments */ - private ParameterizedTypeImpl(final Class raw, final Type useOwner, final Type[] typeArguments) { - this.raw = raw; + private ParameterizedTypeImpl(final Class rawClass, final Type useOwner, final Type[] typeArguments) { + this.raw = rawClass; this.useOwner = useOwner; this.typeArguments = Arrays.copyOf(typeArguments, typeArguments.length, Type[].class); } @@ -482,17 +482,18 @@ private static boolean isAssignable(final Type type, final ParameterizedType toP /** * Look up {@code var} in {@code typeVarAssigns} transitively, * i.e. keep looking until the value found is not a type variable. - * @param var the type variable to look up + * @param typeVariable the type variable to look up * @param typeVarAssigns the map used for the look up * @return Type or {@code null} if some variable was not in the map * @since 3.2 */ - private static Type unrollVariableAssignments(TypeVariable var, final Map, Type> typeVarAssigns) { + private static Type unrollVariableAssignments(TypeVariable typeVariable, + final Map, Type> typeVarAssigns) { Type result; do { - result = typeVarAssigns.get(var); - if (result instanceof TypeVariable && !result.equals(var)) { - var = (TypeVariable) result; + result = typeVarAssigns.get(typeVariable); + if (result instanceof TypeVariable && !result.equals(typeVariable)) { + typeVariable = (TypeVariable) result; continue; } break; @@ -1344,8 +1345,8 @@ public static boolean isArrayType(final Type type) { */ public static Type getArrayComponentType(final Type type) { if (type instanceof Class) { - final Class clazz = (Class) type; - return clazz.isArray() ? clazz.getComponentType() : null; + final Class cls = (Class) type; + return cls.isArray() ? cls.getComponentType() : null; } if (type instanceof GenericArrayType) { return ((GenericArrayType) type).getGenericComponentType(); @@ -1451,76 +1452,78 @@ public static boolean containsTypeVariables(final Type type) { /** * Create a parameterized type instance. * - * @param raw the raw class to create a parameterized type instance for + * @param rawClass the raw class to create a parameterized type instance for * @param typeArguments the types used for parameterization * @return {@link ParameterizedType} * @since 3.2 */ - public static final ParameterizedType parameterize(final Class raw, final Type... typeArguments) { - return parameterizeWithOwner(null, raw, typeArguments); + public static final ParameterizedType parameterize(final Class rawClass, final Type... typeArguments) { + return parameterizeWithOwner(null, rawClass, typeArguments); } /** * Create a parameterized type instance. * - * @param raw the raw class to create a parameterized type instance for + * @param rawClass the raw class to create a parameterized type instance for * @param typeArgMappings the mapping used for parameterization * @return {@link ParameterizedType} * @since 3.2 */ - public static final ParameterizedType parameterize(final Class raw, + public static final ParameterizedType parameterize(final Class rawClass, final Map, Type> typeArgMappings) { - Validate.notNull(raw, "raw class is null"); + Validate.notNull(rawClass, "raw class is null"); Validate.notNull(typeArgMappings, "typeArgMappings is null"); - return parameterizeWithOwner(null, raw, extractTypeArgumentsFrom(typeArgMappings, raw.getTypeParameters())); + return parameterizeWithOwner(null, rawClass, + extractTypeArgumentsFrom(typeArgMappings, rawClass.getTypeParameters())); } /** * Create a parameterized type instance. * * @param owner the owning type - * @param raw the raw class to create a parameterized type instance for + * @param rawClass the raw class to create a parameterized type instance for * @param typeArguments the types used for parameterization * * @return {@link ParameterizedType} * @since 3.2 */ - public static final ParameterizedType parameterizeWithOwner(final Type owner, final Class raw, + public static final ParameterizedType parameterizeWithOwner(final Type owner, final Class rawClass, final Type... typeArguments) { - Validate.notNull(raw, "raw class is null"); + Validate.notNull(rawClass, "raw class is null"); final Type useOwner; - if (raw.getEnclosingClass() == null) { - Validate.isTrue(owner == null, "no owner allowed for top-level %s", raw); + if (rawClass.getEnclosingClass() == null) { + Validate.isTrue(owner == null, "no owner allowed for top-level %s", rawClass); useOwner = null; } else if (owner == null) { - useOwner = raw.getEnclosingClass(); + useOwner = rawClass.getEnclosingClass(); } else { - Validate.isTrue(isAssignable(owner, raw.getEnclosingClass()), - "%s is invalid owner type for parameterized %s", owner, raw); + Validate.isTrue(isAssignable(owner, rawClass.getEnclosingClass()), + "%s is invalid owner type for parameterized %s", owner, rawClass); useOwner = owner; } Validate.noNullElements(typeArguments, "null type argument at index %s"); - Validate.isTrue(raw.getTypeParameters().length == typeArguments.length, - "invalid number of type parameters specified: expected %d, got %d", raw.getTypeParameters().length, + Validate.isTrue(rawClass.getTypeParameters().length == typeArguments.length, + "invalid number of type parameters specified: expected %d, got %d", rawClass.getTypeParameters().length, typeArguments.length); - return new ParameterizedTypeImpl(raw, useOwner, typeArguments); + return new ParameterizedTypeImpl(rawClass, useOwner, typeArguments); } /** * Create a parameterized type instance. * * @param owner the owning type - * @param raw the raw class to create a parameterized type instance for + * @param rawClass the raw class to create a parameterized type instance for * @param typeArgMappings the mapping used for parameterization * @return {@link ParameterizedType} * @since 3.2 */ - public static final ParameterizedType parameterizeWithOwner(final Type owner, final Class raw, + public static final ParameterizedType parameterizeWithOwner(final Type owner, final Class rawClass, final Map, Type> typeArgMappings) { - Validate.notNull(raw, "raw class is null"); + Validate.notNull(rawClass, "raw class is null"); Validate.notNull(typeArgMappings, "typeArgMappings is null"); - return parameterizeWithOwner(owner, raw, extractTypeArgumentsFrom(typeArgMappings, raw.getTypeParameters())); + return parameterizeWithOwner(owner, rawClass, + extractTypeArgumentsFrom(typeArgMappings, rawClass.getTypeParameters())); } /** @@ -1563,39 +1566,40 @@ public static GenericArrayType genericArrayType(final Type componentType) { /** * Check equality of types. * - * @param t1 the first type - * @param t2 the second type + * @param type1 the first type + * @param type2 the second type * @return boolean * @since 3.2 */ - public static boolean equals(final Type t1, final Type t2) { - if (Objects.equals(t1, t2)) { + public static boolean equals(final Type type1, final Type type2) { + if (Objects.equals(type1, type2)) { return true; } - if (t1 instanceof ParameterizedType) { - return equals((ParameterizedType) t1, t2); + if (type1 instanceof ParameterizedType) { + return equals((ParameterizedType) type1, type2); } - if (t1 instanceof GenericArrayType) { - return equals((GenericArrayType) t1, t2); + if (type1 instanceof GenericArrayType) { + return equals((GenericArrayType) type1, type2); } - if (t1 instanceof WildcardType) { - return equals((WildcardType) t1, t2); + if (type1 instanceof WildcardType) { + return equals((WildcardType) type1, type2); } return false; } /** * Learn whether {@code t} equals {@code p}. - * @param p LHS - * @param t RHS + * @param parameterizedType LHS + * @param type RHS * @return boolean * @since 3.2 */ - private static boolean equals(final ParameterizedType p, final Type t) { - if (t instanceof ParameterizedType) { - final ParameterizedType other = (ParameterizedType) t; - if (equals(p.getRawType(), other.getRawType()) && equals(p.getOwnerType(), other.getOwnerType())) { - return equals(p.getActualTypeArguments(), other.getActualTypeArguments()); + private static boolean equals(final ParameterizedType parameterizedType, final Type type) { + if (type instanceof ParameterizedType) { + final ParameterizedType other = (ParameterizedType) type; + if (equals(parameterizedType.getRawType(), other.getRawType()) + && equals(parameterizedType.getOwnerType(), other.getOwnerType())) { + return equals(parameterizedType.getActualTypeArguments(), other.getActualTypeArguments()); } } return false; @@ -1603,43 +1607,43 @@ private static boolean equals(final ParameterizedType p, final Type t) { /** * Learn whether {@code t} equals {@code a}. - * @param a LHS - * @param t RHS + * @param genericArrayType LHS + * @param type RHS * @return boolean * @since 3.2 */ - private static boolean equals(final GenericArrayType a, final Type t) { - return t instanceof GenericArrayType - && equals(a.getGenericComponentType(), ((GenericArrayType) t).getGenericComponentType()); + private static boolean equals(final GenericArrayType genericArrayType, final Type type) { + return type instanceof GenericArrayType + && equals(genericArrayType.getGenericComponentType(), ((GenericArrayType) type).getGenericComponentType()); } /** * Learn whether {@code t} equals {@code w}. - * @param w LHS - * @param t RHS + * @param wildcardType LHS + * @param type RHS * @return boolean * @since 3.2 */ - private static boolean equals(final WildcardType w, final Type t) { - if (t instanceof WildcardType) { - final WildcardType other = (WildcardType) t; - return equals(getImplicitLowerBounds(w), getImplicitLowerBounds(other)) - && equals(getImplicitUpperBounds(w), getImplicitUpperBounds(other)); + private static boolean equals(final WildcardType wildcardType, final Type type) { + if (type instanceof WildcardType) { + final WildcardType other = (WildcardType) type; + return equals(getImplicitLowerBounds(wildcardType), getImplicitLowerBounds(other)) + && equals(getImplicitUpperBounds(wildcardType), getImplicitUpperBounds(other)); } return false; } /** * Learn whether {@code t1} equals {@code t2}. - * @param t1 LHS - * @param t2 RHS + * @param type1 LHS + * @param type2 RHS * @return boolean * @since 3.2 */ - private static boolean equals(final Type[] t1, final Type[] t2) { - if (t1.length == t2.length) { - for (int i = 0; i < t1.length; i++) { - if (!equals(t1[i], t2[i])) { + private static boolean equals(final Type[] type1, final Type[] type2) { + if (type1.length == type2.length) { + for (int i = 0; i < type1.length; i++) { + if (!equals(type1[i], type2[i])) { return false; } } @@ -1730,25 +1734,25 @@ public static Typed wrap(final Class type) { /** * Format a {@link Class} as a {@link String}. - * @param c {@code Class} to format + * @param cls {@code Class} to format * @return String * @since 3.2 */ - private static String classToString(final Class c) { - if (c.isArray()) { - return toString(c.getComponentType()) + "[]"; + private static String classToString(final Class cls) { + if (cls.isArray()) { + return toString(cls.getComponentType()) + "[]"; } final StringBuilder buf = new StringBuilder(); - if (c.getEnclosingClass() != null) { - buf.append(classToString(c.getEnclosingClass())).append('.').append(c.getSimpleName()); + if (cls.getEnclosingClass() != null) { + buf.append(classToString(cls.getEnclosingClass())).append('.').append(cls.getSimpleName()); } else { - buf.append(c.getName()); + buf.append(cls.getName()); } - if (c.getTypeParameters().length > 0) { + if (cls.getTypeParameters().length > 0) { buf.append('<'); - appendAllTo(buf, ", ", c.getTypeParameters()); + appendAllTo(buf, ", ", cls.getTypeParameters()); buf.append('>'); } return buf.toString(); @@ -1756,72 +1760,75 @@ private static String classToString(final Class c) { /** * Format a {@link TypeVariable} as a {@link String}. - * @param v {@code TypeVariable} to format + * @param typeVariable {@code TypeVariable} to format * @return String * @since 3.2 */ - private static String typeVariableToString(final TypeVariable v) { - final StringBuilder buf = new StringBuilder(v.getName()); - final Type[] bounds = v.getBounds(); + private static String typeVariableToString(final TypeVariable typeVariable) { + final StringBuilder buf = new StringBuilder(typeVariable.getName()); + final Type[] bounds = typeVariable.getBounds(); if (bounds.length > 0 && !(bounds.length == 1 && Object.class.equals(bounds[0]))) { buf.append(" extends "); - appendAllTo(buf, " & ", v.getBounds()); + appendAllTo(buf, " & ", typeVariable.getBounds()); } return buf.toString(); } /** * Format a {@link ParameterizedType} as a {@link String}. - * @param p {@code ParameterizedType} to format + * @param parameterizedType {@code ParameterizedType} to format * @return String * @since 3.2 */ - private static String parameterizedTypeToString(final ParameterizedType p) { - final StringBuilder buf = new StringBuilder(); + private static String parameterizedTypeToString(final ParameterizedType parameterizedType) { + final StringBuilder builder = new StringBuilder(); - final Type useOwner = p.getOwnerType(); - final Class raw = (Class) p.getRawType(); + final Type useOwner = parameterizedType.getOwnerType(); + final Class raw = (Class) parameterizedType.getRawType(); if (useOwner == null) { - buf.append(raw.getName()); + builder.append(raw.getName()); } else { if (useOwner instanceof Class) { - buf.append(((Class) useOwner).getName()); + builder.append(((Class) useOwner).getName()); } else { - buf.append(useOwner.toString()); + builder.append(useOwner.toString()); } - buf.append('.').append(raw.getSimpleName()); + builder.append('.').append(raw.getSimpleName()); } - final int[] recursiveTypeIndexes = findRecursiveTypes(p); + final int[] recursiveTypeIndexes = findRecursiveTypes(parameterizedType); if (recursiveTypeIndexes.length > 0) { - appendRecursiveTypes(buf, recursiveTypeIndexes, p.getActualTypeArguments()); + appendRecursiveTypes(builder, recursiveTypeIndexes, parameterizedType.getActualTypeArguments()); } else { - appendAllTo(buf.append('<'), ", ", p.getActualTypeArguments()).append('>'); + appendAllTo(builder.append('<'), ", ", parameterizedType.getActualTypeArguments()).append('>'); } - return buf.toString(); + return builder.toString(); } - private static void appendRecursiveTypes(final StringBuilder buf, final int[] recursiveTypeIndexes, final Type[] argumentTypes) { + private static void appendRecursiveTypes(final StringBuilder builder, final int[] recursiveTypeIndexes, + final Type[] argumentTypes) { for (int i = 0; i < recursiveTypeIndexes.length; i++) { - appendAllTo(buf.append('<'), ", ", argumentTypes[i].toString()).append('>'); + appendAllTo(builder.append('<'), ", ", argumentTypes[i].toString()).append('>'); } final Type[] argumentsFiltered = ArrayUtils.removeAll(argumentTypes, recursiveTypeIndexes); if (argumentsFiltered.length > 0) { - appendAllTo(buf.append('<'), ", ", argumentsFiltered).append('>'); + appendAllTo(builder.append('<'), ", ", argumentsFiltered).append('>'); } } - private static int[] findRecursiveTypes(final ParameterizedType p) { - final Type[] filteredArgumentTypes = Arrays.copyOf(p.getActualTypeArguments(), p.getActualTypeArguments().length); + private static int[] findRecursiveTypes(final ParameterizedType parameterizedType) { + final Type[] filteredArgumentTypes = Arrays.copyOf(parameterizedType.getActualTypeArguments(), + parameterizedType.getActualTypeArguments().length); int[] indexesToRemove = {}; for (int i = 0; i < filteredArgumentTypes.length; i++) { if (filteredArgumentTypes[i] instanceof TypeVariable) { - if (containsVariableTypeSameParametrizedTypeBound(((TypeVariable) filteredArgumentTypes[i]), p)) { + if (containsVariableTypeSameParametrizedTypeBound(((TypeVariable) filteredArgumentTypes[i]), + parameterizedType)) { indexesToRemove = ArrayUtils.add(indexesToRemove, i); } } @@ -1829,20 +1836,21 @@ private static int[] findRecursiveTypes(final ParameterizedType p) { return indexesToRemove; } - private static boolean containsVariableTypeSameParametrizedTypeBound(final TypeVariable typeVariable, final ParameterizedType p) { - return ArrayUtils.contains(typeVariable.getBounds(), p); + private static boolean containsVariableTypeSameParametrizedTypeBound(final TypeVariable typeVariable, + final ParameterizedType parameterizedType) { + return ArrayUtils.contains(typeVariable.getBounds(), parameterizedType); } /** * Format a {@link WildcardType} as a {@link String}. - * @param w {@code WildcardType} to format + * @param wildcardType {@code WildcardType} to format * @return String * @since 3.2 */ - private static String wildcardTypeToString(final WildcardType w) { + private static String wildcardTypeToString(final WildcardType wildcardType) { final StringBuilder buf = new StringBuilder().append('?'); - final Type[] lowerBounds = w.getLowerBounds(); - final Type[] upperBounds = w.getUpperBounds(); + final Type[] lowerBounds = wildcardType.getLowerBounds(); + final Type[] upperBounds = wildcardType.getUpperBounds(); if (lowerBounds.length > 1 || lowerBounds.length == 1 && lowerBounds[0] != null) { appendAllTo(buf.append(" super "), " & ", lowerBounds); } else if (upperBounds.length > 1 || upperBounds.length == 1 && !Object.class.equals(upperBounds[0])) { @@ -1853,31 +1861,32 @@ private static String wildcardTypeToString(final WildcardType w) { /** * Format a {@link GenericArrayType} as a {@link String}. - * @param g {@code GenericArrayType} to format + * @param genericArrayType {@code GenericArrayType} to format * @return String * @since 3.2 */ - private static String genericArrayTypeToString(final GenericArrayType g) { - return String.format("%s[]", toString(g.getGenericComponentType())); + private static String genericArrayTypeToString(final GenericArrayType genericArrayType) { + return String.format("%s[]", toString(genericArrayType.getGenericComponentType())); } /** - * Append {@code types} to {@code buf} with separator {@code sep}. - * @param buf destination + * Append {@code types} to {@code builder} with separator {@code sep}. + * @param builder destination * @param sep separator * @param types to append - * @return {@code buf} + * @return {@code builder} * @since 3.2 */ - private static StringBuilder appendAllTo(final StringBuilder buf, final String sep, final T... types) { + private static StringBuilder appendAllTo(final StringBuilder builder, final String sep, + @SuppressWarnings("unchecked") final T... types) { Validate.notEmpty(Validate.noNullElements(types)); if (types.length > 0) { - buf.append(toString(types[0])); + builder.append(toString(types[0])); for (int i = 1; i < types.length; i++) { - buf.append(sep).append(toString(types[i])); + builder.append(sep).append(toString(types[i])); } } - return buf; + return builder; } private static String toString(final T object) { diff --git a/src/main/java/org/apache/commons/lang3/text/translate/NumericEntityUnescaper.java b/src/main/java/org/apache/commons/lang3/text/translate/NumericEntityUnescaper.java index aad10c0223f..2b7ee8ec983 100644 --- a/src/main/java/org/apache/commons/lang3/text/translate/NumericEntityUnescaper.java +++ b/src/main/java/org/apache/commons/lang3/text/translate/NumericEntityUnescaper.java @@ -35,7 +35,9 @@ @Deprecated public class NumericEntityUnescaper extends CharSequenceTranslator { - public enum OPTION { semiColonRequired, semiColonOptional, errorIfNoSemiColon } + public enum OPTION { + semiColonRequired, semiColonOptional, errorIfNoSemiColon + } // TODO?: Create an OptionsSet class to hide some of the conditional logic below private final EnumSet diff --git a/src/main/java/org/apache/commons/lang3/ArrayUtils.java b/src/main/java/org/apache/commons/lang3/ArrayUtils.java index 1485e0c5585..7f369fa3c91 100644 --- a/src/main/java/org/apache/commons/lang3/ArrayUtils.java +++ b/src/main/java/org/apache/commons/lang3/ArrayUtils.java @@ -5302,6 +5302,7 @@ public static T[] removeAll(final T[] array, final int... indices) { * * @return A new array containing the existing elements except the occurrences of the specified element. * @since 3.5 + * @deprecated Use {@link #removeAllOccurrences(boolean[], boolean)} */ public static boolean[] removeAllOccurences(final boolean[] array, final boolean element) { return (boolean[]) removeAll((Object) array, indexesOf(array, element)); @@ -5321,6 +5322,7 @@ public static boolean[] removeAllOccurences(final boolean[] array, final boolean * * @return A new array containing the existing elements except the occurrences of the specified element. * @since 3.5 + * @deprecated Use {@link #removeAllOccurrences(byte[], byte)} */ public static byte[] removeAllOccurences(final byte[] array, final byte element) { return (byte[]) removeAll((Object) array, indexesOf(array, element)); @@ -5340,6 +5342,7 @@ public static byte[] removeAllOccurences(final byte[] array, final byte element) * * @return A new array containing the existing elements except the occurrences of the specified element. * @since 3.5 + * @deprecated Use {@link #removeAllOccurrences(char[], char)} */ public static char[] removeAllOccurences(final char[] array, final char element) { return (char[]) removeAll((Object) array, indexesOf(array, element)); @@ -5359,6 +5362,7 @@ public static char[] removeAllOccurences(final char[] array, final char element) * * @return A new array containing the existing elements except the occurrences of the specified element. * @since 3.5 + * @deprecated Use {@link #removeAllOccurrences(double[], double)} */ public static double[] removeAllOccurences(final double[] array, final double element) { return (double[]) removeAll((Object) array, indexesOf(array, element)); @@ -5378,6 +5382,7 @@ public static double[] removeAllOccurences(final double[] array, final double el * * @return A new array containing the existing elements except the occurrences of the specified element. * @since 3.5 + * @deprecated Use {@link #removeAllOccurrences(float[], float)} */ public static float[] removeAllOccurences(final float[] array, final float element) { return (float[]) removeAll((Object) array, indexesOf(array, element)); @@ -5397,6 +5402,7 @@ public static float[] removeAllOccurences(final float[] array, final float eleme * * @return A new array containing the existing elements except the occurrences of the specified element. * @since 3.5 + * @deprecated Use {@link #removeAllOccurrences(int[], int)} */ public static int[] removeAllOccurences(final int[] array, final int element) { return (int[]) removeAll((Object) array, indexesOf(array, element)); @@ -5416,6 +5422,7 @@ public static int[] removeAllOccurences(final int[] array, final int element) { * * @return A new array containing the existing elements except the occurrences of the specified element. * @since 3.5 + * @deprecated Use {@link #removeAllOccurrences(long[], long)} */ public static long[] removeAllOccurences(final long[] array, final long element) { return (long[]) removeAll((Object) array, indexesOf(array, element)); @@ -5435,6 +5442,7 @@ public static long[] removeAllOccurences(final long[] array, final long element) * * @return A new array containing the existing elements except the occurrences of the specified element. * @since 3.5 + * @deprecated Use {@link #removeAllOccurrences(short[], short)} */ public static short[] removeAllOccurences(final short[] array, final short element) { return (short[]) removeAll((Object) array, indexesOf(array, element)); @@ -5455,11 +5463,184 @@ public static short[] removeAllOccurences(final short[] array, final short eleme * * @return A new array containing the existing elements except the occurrences of the specified element. * @since 3.5 + * @deprecated Use {@link #removeAllOccurrences(Object[], Object)} */ public static T[] removeAllOccurences(final T[] array, final T element) { return (T[]) removeAll((Object) array, indexesOf(array, element)); } + /** + * Removes the occurrences of the specified element from the specified boolean array. + * + *

+ * All subsequent elements are shifted to the left (subtracts one from their indices). + * If the array doesn't contains such an element, no elements are removed from the array. + * {@code null} will be returned if the input array is {@code null}. + *

+ * + * @param element the element to remove + * @param array the input array + * + * @return A new array containing the existing elements except the occurrences of the specified element. + * @since 3.10 + */ + public static boolean[] removeAllOccurrences(final boolean[] array, final boolean element) { + return (boolean[]) removeAll((Object) array, indexesOf(array, element)); + } + + /** + * Removes the occurrences of the specified element from the specified byte array. + * + *

+ * All subsequent elements are shifted to the left (subtracts one from their indices). + * If the array doesn't contains such an element, no elements are removed from the array. + * {@code null} will be returned if the input array is {@code null}. + *

+ * + * @param element the element to remove + * @param array the input array + * + * @return A new array containing the existing elements except the occurrences of the specified element. + * @since 3.10 + */ + public static byte[] removeAllOccurrences(final byte[] array, final byte element) { + return (byte[]) removeAll((Object) array, indexesOf(array, element)); + } + + /** + * Removes the occurrences of the specified element from the specified char array. + * + *

+ * All subsequent elements are shifted to the left (subtracts one from their indices). + * If the array doesn't contains such an element, no elements are removed from the array. + * {@code null} will be returned if the input array is {@code null}. + *

+ * + * @param element the element to remove + * @param array the input array + * + * @return A new array containing the existing elements except the occurrences of the specified element. + * @since 3.10 + */ + public static char[] removeAllOccurrences(final char[] array, final char element) { + return (char[]) removeAll((Object) array, indexesOf(array, element)); + } + + /** + * Removes the occurrences of the specified element from the specified double array. + * + *

+ * All subsequent elements are shifted to the left (subtracts one from their indices). + * If the array doesn't contains such an element, no elements are removed from the array. + * {@code null} will be returned if the input array is {@code null}. + *

+ * + * @param element the element to remove + * @param array the input array + * + * @return A new array containing the existing elements except the occurrences of the specified element. + * @since 3.10 + */ + public static double[] removeAllOccurrences(final double[] array, final double element) { + return (double[]) removeAll((Object) array, indexesOf(array, element)); + } + + /** + * Removes the occurrences of the specified element from the specified float array. + * + *

+ * All subsequent elements are shifted to the left (subtracts one from their indices). + * If the array doesn't contains such an element, no elements are removed from the array. + * {@code null} will be returned if the input array is {@code null}. + *

+ * + * @param element the element to remove + * @param array the input array + * + * @return A new array containing the existing elements except the occurrences of the specified element. + * @since 3.10 + */ + public static float[] removeAllOccurrences(final float[] array, final float element) { + return (float[]) removeAll((Object) array, indexesOf(array, element)); + } + + /** + * Removes the occurrences of the specified element from the specified int array. + * + *

+ * All subsequent elements are shifted to the left (subtracts one from their indices). + * If the array doesn't contains such an element, no elements are removed from the array. + * {@code null} will be returned if the input array is {@code null}. + *

+ * + * @param element the element to remove + * @param array the input array + * + * @return A new array containing the existing elements except the occurrences of the specified element. + * @since 3.10 + */ + public static int[] removeAllOccurrences(final int[] array, final int element) { + return (int[]) removeAll((Object) array, indexesOf(array, element)); + } + + /** + * Removes the occurrences of the specified element from the specified long array. + * + *

+ * All subsequent elements are shifted to the left (subtracts one from their indices). + * If the array doesn't contains such an element, no elements are removed from the array. + * {@code null} will be returned if the input array is {@code null}. + *

+ * + * @param element the element to remove + * @param array the input array + * + * @return A new array containing the existing elements except the occurrences of the specified element. + * @since 3.10 + */ + public static long[] removeAllOccurrences(final long[] array, final long element) { + return (long[]) removeAll((Object) array, indexesOf(array, element)); + } + + /** + * Removes the occurrences of the specified element from the specified short array. + * + *

+ * All subsequent elements are shifted to the left (subtracts one from their indices). + * If the array doesn't contains such an element, no elements are removed from the array. + * {@code null} will be returned if the input array is {@code null}. + *

+ * + * @param element the element to remove + * @param array the input array + * + * @return A new array containing the existing elements except the occurrences of the specified element. + * @since 3.10 + */ + public static short[] removeAllOccurrences(final short[] array, final short element) { + return (short[]) removeAll((Object) array, indexesOf(array, element)); + } + + /** + * Removes the occurrences of the specified element from the specified array. + * + *

+ * All subsequent elements are shifted to the left (subtracts one from their indices). + * If the array doesn't contains such an element, no elements are removed from the array. + * {@code null} will be returned if the input array is {@code null}. + *

+ * + * @param the type of object in the array + * @param element the element to remove + * @param array the input array + * + * @return A new array containing the existing elements except the occurrences of the specified element. + * @since 3.10 + */ + public static T[] removeAllOccurrences(final T[] array, final T element) { + return (T[]) removeAll((Object) array, indexesOf(array, element)); + } + /** *

Removes the first occurrence of the specified element from the * specified array. All subsequent elements are shifted to the left diff --git a/src/test/java/org/apache/commons/lang3/ArrayUtilsRemoveTest.java b/src/test/java/org/apache/commons/lang3/ArrayUtilsRemoveTest.java index 22b258cee47..4877b106125 100644 --- a/src/test/java/org/apache/commons/lang3/ArrayUtilsRemoveTest.java +++ b/src/test/java/org/apache/commons/lang3/ArrayUtilsRemoveTest.java @@ -30,264 +30,507 @@ public class ArrayUtilsRemoveTest { @Test - public void testRemoveObjectArray() { - Object[] array; - array = ArrayUtils.remove(new Object[] {"a"}, 0); - assertArrayEquals(ArrayUtils.EMPTY_OBJECT_ARRAY, array); - assertEquals(Object.class, array.getClass().getComponentType()); - array = ArrayUtils.remove(new Object[] {"a", "b"}, 0); - assertArrayEquals(new Object[]{"b"}, array); - assertEquals(Object.class, array.getClass().getComponentType()); - array = ArrayUtils.remove(new Object[] {"a", "b"}, 1); - assertArrayEquals(new Object[]{"a"}, array); - assertEquals(Object.class, array.getClass().getComponentType()); - array = ArrayUtils.remove(new Object[] {"a", "b", "c"}, 1); - assertArrayEquals(new Object[]{"a", "c"}, array); - assertEquals(Object.class, array.getClass().getComponentType()); - assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove(new Object[] {"a", "b"}, -1)); - assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove(new Object[] {"a", "b"}, 2)); - assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove((Object[]) null, 0)); + public void testRemoveAllBooleanOccurences() { + boolean[] a = null; + assertNull(ArrayUtils.removeAllOccurences(a, true)); + + a = new boolean[0]; + assertArrayEquals(ArrayUtils.EMPTY_BOOLEAN_ARRAY, ArrayUtils.removeAllOccurences(a, true)); + + a = new boolean[] { true }; + assertArrayEquals(ArrayUtils.EMPTY_BOOLEAN_ARRAY, ArrayUtils.removeAllOccurences(a, true)); + + a = new boolean[] { true, true }; + assertArrayEquals(ArrayUtils.EMPTY_BOOLEAN_ARRAY, ArrayUtils.removeAllOccurences(a, true)); + + a = new boolean[] { false, true, true, false, true }; + assertArrayEquals(new boolean[]{false, false}, ArrayUtils.removeAllOccurences(a, true)); + + a = new boolean[] { false, true, true, false, true }; + assertArrayEquals(new boolean[]{true, true, true}, ArrayUtils.removeAllOccurences(a, false)); } @Test - public void testRemoveNumberArray() { - final Number[] inarray = {Integer.valueOf(1), Long.valueOf(2), Byte.valueOf((byte) 3)}; - assertEquals(3, inarray.length); - Number[] outarray; - outarray = ArrayUtils.remove(inarray, 1); - assertEquals(2, outarray.length); - assertEquals(Number.class, outarray.getClass().getComponentType()); - outarray = ArrayUtils.remove(outarray, 1); - assertEquals(1, outarray.length); - assertEquals(Number.class, outarray.getClass().getComponentType()); - outarray = ArrayUtils.remove(outarray, 0); - assertEquals(0, outarray.length); - assertEquals(Number.class, outarray.getClass().getComponentType()); + public void testRemoveAllBooleanOccurrences() { + boolean[] a = null; + assertNull(ArrayUtils.removeAllOccurrences(a, true)); + + a = new boolean[0]; + assertArrayEquals(ArrayUtils.EMPTY_BOOLEAN_ARRAY, ArrayUtils.removeAllOccurrences(a, true)); + + a = new boolean[] { true }; + assertArrayEquals(ArrayUtils.EMPTY_BOOLEAN_ARRAY, ArrayUtils.removeAllOccurrences(a, true)); + + a = new boolean[] { true, true }; + assertArrayEquals(ArrayUtils.EMPTY_BOOLEAN_ARRAY, ArrayUtils.removeAllOccurrences(a, true)); + + a = new boolean[] { false, true, true, false, true }; + assertArrayEquals(new boolean[]{false, false}, ArrayUtils.removeAllOccurrences(a, true)); + + a = new boolean[] { false, true, true, false, true }; + assertArrayEquals(new boolean[]{true, true, true}, ArrayUtils.removeAllOccurrences(a, false)); } @Test - public void testRemoveBooleanArray() { - boolean[] array; - array = ArrayUtils.remove(new boolean[] {true}, 0); - assertArrayEquals(ArrayUtils.EMPTY_BOOLEAN_ARRAY, array); - assertEquals(Boolean.TYPE, array.getClass().getComponentType()); - array = ArrayUtils.remove(new boolean[] {true, false}, 0); - assertArrayEquals(new boolean[]{false}, array); - assertEquals(Boolean.TYPE, array.getClass().getComponentType()); - array = ArrayUtils.remove(new boolean[] {true, false}, 1); - assertArrayEquals(new boolean[]{true}, array); - assertEquals(Boolean.TYPE, array.getClass().getComponentType()); - array = ArrayUtils.remove(new boolean[] {true, false, true}, 1); - assertArrayEquals(new boolean[]{true, true}, array); - assertEquals(Boolean.TYPE, array.getClass().getComponentType()); - assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove(new boolean[] {true, false}, -1)); - assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove(new boolean[] {true, false}, 2)); - assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove((boolean[]) null, 0)); + public void testRemoveAllByteOccurences() { + byte[] a = null; + assertNull(ArrayUtils.removeAllOccurences(a, (byte) 2)); + + a = new byte[0]; + assertArrayEquals(ArrayUtils.EMPTY_BYTE_ARRAY, ArrayUtils.removeAllOccurences(a, (byte) 2)); + + a = new byte[] { 2 }; + assertArrayEquals(ArrayUtils.EMPTY_BYTE_ARRAY, ArrayUtils.removeAllOccurences(a, (byte) 2)); + + a = new byte[] { 2, 2 }; + assertArrayEquals(ArrayUtils.EMPTY_BYTE_ARRAY, ArrayUtils.removeAllOccurences(a, (byte) 2)); + + a = new byte[] { 1, 2, 2, 3, 2 }; + assertArrayEquals(new byte[]{1, 3}, ArrayUtils.removeAllOccurences(a, (byte) 2)); + + a = new byte[] { 1, 2, 2, 3, 2 }; + assertArrayEquals(new byte[]{1, 2, 2, 3, 2}, ArrayUtils.removeAllOccurences(a, (byte) 4)); } @Test - public void testRemoveByteArray() { - byte[] array; - array = ArrayUtils.remove(new byte[] {1}, 0); - assertArrayEquals(ArrayUtils.EMPTY_BYTE_ARRAY, array); - assertEquals(Byte.TYPE, array.getClass().getComponentType()); - array = ArrayUtils.remove(new byte[] {1, 2}, 0); - assertArrayEquals(new byte[]{2}, array); - assertEquals(Byte.TYPE, array.getClass().getComponentType()); - array = ArrayUtils.remove(new byte[] {1, 2}, 1); - assertArrayEquals(new byte[]{1}, array); - assertEquals(Byte.TYPE, array.getClass().getComponentType()); - array = ArrayUtils.remove(new byte[] {1, 2, 1}, 1); - assertArrayEquals(new byte[]{1, 1}, array); - assertEquals(Byte.TYPE, array.getClass().getComponentType()); - assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove(new byte[] {1, 2}, -1)); - assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove(new byte[] {1, 2}, 2)); - assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove((byte[]) null, 0)); + public void testRemoveAllByteOccurrences() { + byte[] a = null; + assertNull(ArrayUtils.removeAllOccurrences(a, (byte) 2)); + + a = new byte[0]; + assertArrayEquals(ArrayUtils.EMPTY_BYTE_ARRAY, ArrayUtils.removeAllOccurrences(a, (byte) 2)); + + a = new byte[] { 2 }; + assertArrayEquals(ArrayUtils.EMPTY_BYTE_ARRAY, ArrayUtils.removeAllOccurrences(a, (byte) 2)); + + a = new byte[] { 2, 2 }; + assertArrayEquals(ArrayUtils.EMPTY_BYTE_ARRAY, ArrayUtils.removeAllOccurrences(a, (byte) 2)); + + a = new byte[] { 1, 2, 2, 3, 2 }; + assertArrayEquals(new byte[]{1, 3}, ArrayUtils.removeAllOccurrences(a, (byte) 2)); + + a = new byte[] { 1, 2, 2, 3, 2 }; + assertArrayEquals(new byte[]{1, 2, 2, 3, 2}, ArrayUtils.removeAllOccurrences(a, (byte) 4)); } @Test - public void testRemoveCharArray() { - char[] array; - array = ArrayUtils.remove(new char[] {'a'}, 0); - assertArrayEquals(ArrayUtils.EMPTY_CHAR_ARRAY, array); - assertEquals(Character.TYPE, array.getClass().getComponentType()); - array = ArrayUtils.remove(new char[] {'a', 'b'}, 0); - assertArrayEquals(new char[]{'b'}, array); - assertEquals(Character.TYPE, array.getClass().getComponentType()); - array = ArrayUtils.remove(new char[] {'a', 'b'}, 1); - assertArrayEquals(new char[]{'a'}, array); - assertEquals(Character.TYPE, array.getClass().getComponentType()); - array = ArrayUtils.remove(new char[] {'a', 'b', 'c'}, 1); - assertArrayEquals(new char[]{'a', 'c'}, array); - assertEquals(Character.TYPE, array.getClass().getComponentType()); - assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove(new char[] {'a', 'b'}, -1)); - assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove(new char[] {'a', 'b'}, 2)); - assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove((char[]) null, 0)); + public void testRemoveAllCharOccurences() { + char[] a = null; + assertNull(ArrayUtils.removeAllOccurences(a, '2')); + + a = new char[0]; + assertArrayEquals(ArrayUtils.EMPTY_CHAR_ARRAY, ArrayUtils.removeAllOccurences(a, '2')); + + a = new char[] { '2' }; + assertArrayEquals(ArrayUtils.EMPTY_CHAR_ARRAY, ArrayUtils.removeAllOccurences(a, '2')); + + a = new char[] { '2', '2' }; + assertArrayEquals(ArrayUtils.EMPTY_CHAR_ARRAY, ArrayUtils.removeAllOccurences(a, '2')); + + a = new char[] { '1', '2', '2', '3', '2' }; + assertArrayEquals(new char[]{'1', '3'}, ArrayUtils.removeAllOccurences(a, '2')); + + a = new char[] { '1', '2', '2', '3', '2' }; + assertArrayEquals(new char[]{'1', '2', '2', '3', '2'}, ArrayUtils.removeAllOccurences(a, '4')); } @Test - public void testRemoveDoubleArray() { - double[] array; - array = ArrayUtils.remove(new double[] {1}, 0); - assertArrayEquals(ArrayUtils.EMPTY_DOUBLE_ARRAY, array); - assertEquals(Double.TYPE, array.getClass().getComponentType()); - array = ArrayUtils.remove(new double[] {1, 2}, 0); - assertArrayEquals(new double[]{2}, array); - assertEquals(Double.TYPE, array.getClass().getComponentType()); - array = ArrayUtils.remove(new double[] {1, 2}, 1); - assertArrayEquals(new double[]{1}, array); - assertEquals(Double.TYPE, array.getClass().getComponentType()); - array = ArrayUtils.remove(new double[] {1, 2, 1}, 1); - assertArrayEquals(new double[]{1, 1}, array); - assertEquals(Double.TYPE, array.getClass().getComponentType()); - assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove(new double[] {1, 2}, -1)); - assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove(new double[] {1, 2}, 2)); - assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove((double[]) null, 0)); + public void testRemoveAllCharOccurrences() { + char[] a = null; + assertNull(ArrayUtils.removeAllOccurrences(a, '2')); + + a = new char[0]; + assertArrayEquals(ArrayUtils.EMPTY_CHAR_ARRAY, ArrayUtils.removeAllOccurrences(a, '2')); + + a = new char[] { '2' }; + assertArrayEquals(ArrayUtils.EMPTY_CHAR_ARRAY, ArrayUtils.removeAllOccurrences(a, '2')); + + a = new char[] { '2', '2' }; + assertArrayEquals(ArrayUtils.EMPTY_CHAR_ARRAY, ArrayUtils.removeAllOccurrences(a, '2')); + + a = new char[] { '1', '2', '2', '3', '2' }; + assertArrayEquals(new char[]{'1', '3'}, ArrayUtils.removeAllOccurrences(a, '2')); + + a = new char[] { '1', '2', '2', '3', '2' }; + assertArrayEquals(new char[]{'1', '2', '2', '3', '2'}, ArrayUtils.removeAllOccurrences(a, '4')); } @Test - public void testRemoveFloatArray() { - float[] array; - array = ArrayUtils.remove(new float[] {1}, 0); - assertArrayEquals(ArrayUtils.EMPTY_FLOAT_ARRAY, array); - assertEquals(Float.TYPE, array.getClass().getComponentType()); - array = ArrayUtils.remove(new float[] {1, 2}, 0); - assertArrayEquals(new float[]{2}, array); - assertEquals(Float.TYPE, array.getClass().getComponentType()); - array = ArrayUtils.remove(new float[] {1, 2}, 1); - assertArrayEquals(new float[]{1}, array); - assertEquals(Float.TYPE, array.getClass().getComponentType()); - array = ArrayUtils.remove(new float[] {1, 2, 1}, 1); - assertArrayEquals(new float[]{1, 1}, array); - assertEquals(Float.TYPE, array.getClass().getComponentType()); - assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove(new float[] {1, 2}, -1)); - assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove(new float[] {1, 2}, 2)); - assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove((float[]) null, 0)); + public void testRemoveAllDoubleOccurences() { + double[] a = null; + assertNull(ArrayUtils.removeAllOccurences(a, 2)); + + a = new double[0]; + assertArrayEquals(ArrayUtils.EMPTY_DOUBLE_ARRAY, ArrayUtils.removeAllOccurences(a, 2)); + + a = new double[] { 2 }; + assertArrayEquals(ArrayUtils.EMPTY_DOUBLE_ARRAY, ArrayUtils.removeAllOccurences(a, 2)); + + a = new double[] { 2, 2 }; + assertArrayEquals(ArrayUtils.EMPTY_DOUBLE_ARRAY, ArrayUtils.removeAllOccurences(a, 2)); + + a = new double[] { 1, 2, 2, 3, 2 }; + assertArrayEquals(new double[]{1, 3}, ArrayUtils.removeAllOccurences(a, 2)); + + a = new double[] { 1, 2, 2, 3, 2 }; + assertArrayEquals(new double[]{1, 2, 2, 3, 2}, ArrayUtils.removeAllOccurences(a, 4)); } @Test - public void testRemoveIntArray() { - int[] array; - array = ArrayUtils.remove(new int[] {1}, 0); - assertArrayEquals(ArrayUtils.EMPTY_INT_ARRAY, array); - assertEquals(Integer.TYPE, array.getClass().getComponentType()); - array = ArrayUtils.remove(new int[] {1, 2}, 0); - assertArrayEquals(new int[]{2}, array); - assertEquals(Integer.TYPE, array.getClass().getComponentType()); - array = ArrayUtils.remove(new int[] {1, 2}, 1); - assertArrayEquals(new int[]{1}, array); - assertEquals(Integer.TYPE, array.getClass().getComponentType()); - array = ArrayUtils.remove(new int[] {1, 2, 1}, 1); - assertArrayEquals(new int[]{1, 1}, array); - assertEquals(Integer.TYPE, array.getClass().getComponentType()); - assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove(new int[] {1, 2}, -1)); - assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove(new int[] {1, 2}, 2)); - assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove((int[]) null, 0)); + public void testRemoveAllDoubleOccurrences() { + double[] a = null; + assertNull(ArrayUtils.removeAllOccurrences(a, 2)); + + a = new double[0]; + assertArrayEquals(ArrayUtils.EMPTY_DOUBLE_ARRAY, ArrayUtils.removeAllOccurrences(a, 2)); + + a = new double[] { 2 }; + assertArrayEquals(ArrayUtils.EMPTY_DOUBLE_ARRAY, ArrayUtils.removeAllOccurrences(a, 2)); + + a = new double[] { 2, 2 }; + assertArrayEquals(ArrayUtils.EMPTY_DOUBLE_ARRAY, ArrayUtils.removeAllOccurrences(a, 2)); + + a = new double[] { 1, 2, 2, 3, 2 }; + assertArrayEquals(new double[]{1, 3}, ArrayUtils.removeAllOccurrences(a, 2)); + + a = new double[] { 1, 2, 2, 3, 2 }; + assertArrayEquals(new double[]{1, 2, 2, 3, 2}, ArrayUtils.removeAllOccurrences(a, 4)); } @Test - public void testRemoveLongArray() { - long[] array; - array = ArrayUtils.remove(new long[] {1}, 0); - assertArrayEquals(ArrayUtils.EMPTY_LONG_ARRAY, array); - assertEquals(Long.TYPE, array.getClass().getComponentType()); - array = ArrayUtils.remove(new long[] {1, 2}, 0); - assertArrayEquals(new long[]{2}, array); - assertEquals(Long.TYPE, array.getClass().getComponentType()); - array = ArrayUtils.remove(new long[] {1, 2}, 1); - assertArrayEquals(new long[]{1}, array); - assertEquals(Long.TYPE, array.getClass().getComponentType()); - array = ArrayUtils.remove(new long[] {1, 2, 1}, 1); - assertArrayEquals(new long[]{1, 1}, array); - assertEquals(Long.TYPE, array.getClass().getComponentType()); - assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove(new long[] {1, 2}, -1)); - assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove(new long[] {1, 2}, 2)); - assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove((long[]) null, 0)); + public void testRemoveAllFloatOccurences() { + float[] a = null; + assertNull(ArrayUtils.removeAllOccurences(a, 2)); + + a = new float[0]; + assertArrayEquals(ArrayUtils.EMPTY_FLOAT_ARRAY, ArrayUtils.removeAllOccurences(a, 2)); + + a = new float[] { 2 }; + assertArrayEquals(ArrayUtils.EMPTY_FLOAT_ARRAY, ArrayUtils.removeAllOccurences(a, 2)); + + a = new float[] { 2, 2 }; + assertArrayEquals(ArrayUtils.EMPTY_FLOAT_ARRAY, ArrayUtils.removeAllOccurences(a, 2)); + + a = new float[] { 1, 2, 2, 3, 2 }; + assertArrayEquals(new float[]{1, 3}, ArrayUtils.removeAllOccurences(a, 2)); + + a = new float[] { 1, 2, 2, 3, 2 }; + assertArrayEquals(new float[]{1, 2, 2, 3, 2}, ArrayUtils.removeAllOccurences(a, 4)); } @Test - public void testRemoveShortArray() { - short[] array; - array = ArrayUtils.remove(new short[] {1}, 0); - assertArrayEquals(ArrayUtils.EMPTY_SHORT_ARRAY, array); - assertEquals(Short.TYPE, array.getClass().getComponentType()); - array = ArrayUtils.remove(new short[] {1, 2}, 0); - assertArrayEquals(new short[]{2}, array); - assertEquals(Short.TYPE, array.getClass().getComponentType()); - array = ArrayUtils.remove(new short[] {1, 2}, 1); - assertArrayEquals(new short[]{1}, array); - assertEquals(Short.TYPE, array.getClass().getComponentType()); - array = ArrayUtils.remove(new short[] {1, 2, 1}, 1); - assertArrayEquals(new short[]{1, 1}, array); - assertEquals(Short.TYPE, array.getClass().getComponentType()); - assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove(new short[] {1, 2}, -1)); - assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove(new short[] {1, 2}, 2)); - assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove((short[]) null, 0)); + public void testRemoveAllFloatOccurrences() { + float[] a = null; + assertNull(ArrayUtils.removeAllOccurrences(a, 2)); + + a = new float[0]; + assertArrayEquals(ArrayUtils.EMPTY_FLOAT_ARRAY, ArrayUtils.removeAllOccurrences(a, 2)); + + a = new float[] { 2 }; + assertArrayEquals(ArrayUtils.EMPTY_FLOAT_ARRAY, ArrayUtils.removeAllOccurrences(a, 2)); + + a = new float[] { 2, 2 }; + assertArrayEquals(ArrayUtils.EMPTY_FLOAT_ARRAY, ArrayUtils.removeAllOccurrences(a, 2)); + + a = new float[] { 1, 2, 2, 3, 2 }; + assertArrayEquals(new float[]{1, 3}, ArrayUtils.removeAllOccurrences(a, 2)); + + a = new float[] { 1, 2, 2, 3, 2 }; + assertArrayEquals(new float[]{1, 2, 2, 3, 2}, ArrayUtils.removeAllOccurrences(a, 4)); } @Test - public void testRemoveElementObjectArray() { - Object[] array; - array = ArrayUtils.removeElement(null, "a"); - assertNull(array); - array = ArrayUtils.removeElement(ArrayUtils.EMPTY_OBJECT_ARRAY, "a"); - assertArrayEquals(ArrayUtils.EMPTY_OBJECT_ARRAY, array); - assertEquals(Object.class, array.getClass().getComponentType()); - array = ArrayUtils.removeElement(new Object[] {"a"}, "a"); - assertArrayEquals(ArrayUtils.EMPTY_OBJECT_ARRAY, array); - assertEquals(Object.class, array.getClass().getComponentType()); - array = ArrayUtils.removeElement(new Object[] {"a", "b"}, "a"); - assertArrayEquals(new Object[]{"b"}, array); - assertEquals(Object.class, array.getClass().getComponentType()); - array = ArrayUtils.removeElement(new Object[] {"a", "b", "a"}, "a"); - assertArrayEquals(new Object[]{"b", "a"}, array); - assertEquals(Object.class, array.getClass().getComponentType()); + public void testRemoveAllIntOccurences() { + int[] a = null; + assertNull(ArrayUtils.removeAllOccurences(a, 2)); + + a = new int[0]; + assertArrayEquals(ArrayUtils.EMPTY_INT_ARRAY, ArrayUtils.removeAllOccurences(a, 2)); + + a = new int[] { 2 }; + assertArrayEquals(ArrayUtils.EMPTY_INT_ARRAY, ArrayUtils.removeAllOccurences(a, 2)); + + a = new int[] { 2, 2 }; + assertArrayEquals(ArrayUtils.EMPTY_INT_ARRAY, ArrayUtils.removeAllOccurences(a, 2)); + + a = new int[] { 1, 2, 2, 3, 2 }; + assertArrayEquals(new int[]{1, 3}, ArrayUtils.removeAllOccurences(a, 2)); + + a = new int[] { 1, 2, 2, 3, 2 }; + assertArrayEquals(new int[]{1, 2, 2, 3, 2}, ArrayUtils.removeAllOccurences(a, 4)); } @Test - public void testRemoveElementBooleanArray() { + public void testRemoveAllIntOccurrences() { + int[] a = null; + assertNull(ArrayUtils.removeAllOccurrences(a, 2)); + + a = new int[0]; + assertArrayEquals(ArrayUtils.EMPTY_INT_ARRAY, ArrayUtils.removeAllOccurrences(a, 2)); + + a = new int[] { 2 }; + assertArrayEquals(ArrayUtils.EMPTY_INT_ARRAY, ArrayUtils.removeAllOccurrences(a, 2)); + + a = new int[] { 2, 2 }; + assertArrayEquals(ArrayUtils.EMPTY_INT_ARRAY, ArrayUtils.removeAllOccurrences(a, 2)); + + a = new int[] { 1, 2, 2, 3, 2 }; + assertArrayEquals(new int[]{1, 3}, ArrayUtils.removeAllOccurrences(a, 2)); + + a = new int[] { 1, 2, 2, 3, 2 }; + assertArrayEquals(new int[]{1, 2, 2, 3, 2}, ArrayUtils.removeAllOccurrences(a, 4)); + } + + @Test + public void testRemoveAllLongOccurences() { + long[] a = null; + assertNull(ArrayUtils.removeAllOccurences(a, 2)); + + a = new long[0]; + assertArrayEquals(ArrayUtils.EMPTY_LONG_ARRAY, ArrayUtils.removeAllOccurences(a, 2)); + + a = new long[] { 2 }; + assertArrayEquals(ArrayUtils.EMPTY_LONG_ARRAY, ArrayUtils.removeAllOccurences(a, 2)); + + a = new long[] { 2, 2 }; + assertArrayEquals(ArrayUtils.EMPTY_LONG_ARRAY, ArrayUtils.removeAllOccurences(a, 2)); + + a = new long[] { 1, 2, 2, 3, 2 }; + assertArrayEquals(new long[]{1, 3}, ArrayUtils.removeAllOccurences(a, 2)); + + a = new long[] { 1, 2, 2, 3, 2 }; + assertArrayEquals(new long[]{1, 2, 2, 3, 2}, ArrayUtils.removeAllOccurences(a, 4)); + } + + @Test + public void testRemoveAllLongOccurrences() { + long[] a = null; + assertNull(ArrayUtils.removeAllOccurrences(a, 2)); + + a = new long[0]; + assertArrayEquals(ArrayUtils.EMPTY_LONG_ARRAY, ArrayUtils.removeAllOccurrences(a, 2)); + + a = new long[] { 2 }; + assertArrayEquals(ArrayUtils.EMPTY_LONG_ARRAY, ArrayUtils.removeAllOccurrences(a, 2)); + + a = new long[] { 2, 2 }; + assertArrayEquals(ArrayUtils.EMPTY_LONG_ARRAY, ArrayUtils.removeAllOccurrences(a, 2)); + + a = new long[] { 1, 2, 2, 3, 2 }; + assertArrayEquals(new long[]{1, 3}, ArrayUtils.removeAllOccurrences(a, 2)); + + a = new long[] { 1, 2, 2, 3, 2 }; + assertArrayEquals(new long[]{1, 2, 2, 3, 2}, ArrayUtils.removeAllOccurrences(a, 4)); + } + + @Test + public void testRemoveAllObjectOccurences() { + String[] a = null; + assertNull(ArrayUtils.removeAllOccurences(a, "2")); + + a = new String[0]; + assertArrayEquals(ArrayUtils.EMPTY_STRING_ARRAY, ArrayUtils.removeAllOccurences(a, "2")); + + a = new String[] { "2" }; + assertArrayEquals(ArrayUtils.EMPTY_STRING_ARRAY, ArrayUtils.removeAllOccurences(a, "2")); + + a = new String[] { "2", "2" }; + assertArrayEquals(ArrayUtils.EMPTY_STRING_ARRAY, ArrayUtils.removeAllOccurences(a, "2")); + + a = new String[] { "1", "2", "2", "3", "2" }; + assertArrayEquals(new String[]{"1", "3"}, ArrayUtils.removeAllOccurences(a, "2")); + + a = new String[] { "1", "2", "2", "3", "2" }; + assertArrayEquals(new String[]{"1", "2", "2", "3", "2"}, ArrayUtils.removeAllOccurences(a, "4")); + } + + @Test + public void testRemoveAllObjectOccurrences() { + String[] a = null; + assertNull(ArrayUtils.removeAllOccurrences(a, "2")); + + a = new String[0]; + assertArrayEquals(ArrayUtils.EMPTY_STRING_ARRAY, ArrayUtils.removeAllOccurrences(a, "2")); + + a = new String[] { "2" }; + assertArrayEquals(ArrayUtils.EMPTY_STRING_ARRAY, ArrayUtils.removeAllOccurrences(a, "2")); + + a = new String[] { "2", "2" }; + assertArrayEquals(ArrayUtils.EMPTY_STRING_ARRAY, ArrayUtils.removeAllOccurrences(a, "2")); + + a = new String[] { "1", "2", "2", "3", "2" }; + assertArrayEquals(new String[]{"1", "3"}, ArrayUtils.removeAllOccurrences(a, "2")); + + a = new String[] { "1", "2", "2", "3", "2" }; + assertArrayEquals(new String[]{"1", "2", "2", "3", "2"}, ArrayUtils.removeAllOccurrences(a, "4")); + } + + @Test + public void testRemoveAllShortOccurences() { + short[] a = null; + assertNull(ArrayUtils.removeAllOccurences(a, (short) 2)); + + a = new short[0]; + assertArrayEquals(ArrayUtils.EMPTY_SHORT_ARRAY, ArrayUtils.removeAllOccurences(a, (short) 2)); + + a = new short[] { 2 }; + assertArrayEquals(ArrayUtils.EMPTY_SHORT_ARRAY, ArrayUtils.removeAllOccurences(a, (short) 2)); + + a = new short[] { 2, 2 }; + assertArrayEquals(ArrayUtils.EMPTY_SHORT_ARRAY, ArrayUtils.removeAllOccurences(a, (short) 2)); + + a = new short[] { 1, 2, 2, 3, 2 }; + assertArrayEquals(new short[]{1, 3}, ArrayUtils.removeAllOccurences(a, (short) 2)); + + a = new short[] { 1, 2, 2, 3, 2 }; + assertArrayEquals(new short[]{1, 2, 2, 3, 2}, ArrayUtils.removeAllOccurences(a, (short) 4)); + } + + @Test + public void testRemoveAllShortOccurrences() { + short[] a = null; + assertNull(ArrayUtils.removeAllOccurrences(a, (short) 2)); + + a = new short[0]; + assertArrayEquals(ArrayUtils.EMPTY_SHORT_ARRAY, ArrayUtils.removeAllOccurrences(a, (short) 2)); + + a = new short[] { 2 }; + assertArrayEquals(ArrayUtils.EMPTY_SHORT_ARRAY, ArrayUtils.removeAllOccurrences(a, (short) 2)); + + a = new short[] { 2, 2 }; + assertArrayEquals(ArrayUtils.EMPTY_SHORT_ARRAY, ArrayUtils.removeAllOccurrences(a, (short) 2)); + + a = new short[] { 1, 2, 2, 3, 2 }; + assertArrayEquals(new short[]{1, 3}, ArrayUtils.removeAllOccurrences(a, (short) 2)); + + a = new short[] { 1, 2, 2, 3, 2 }; + assertArrayEquals(new short[]{1, 2, 2, 3, 2}, ArrayUtils.removeAllOccurrences(a, (short) 4)); + } + + @Test + public void testRemoveBooleanArray() { boolean[] array; - array = ArrayUtils.removeElement(null, true); - assertNull(array); - array = ArrayUtils.removeElement(ArrayUtils.EMPTY_BOOLEAN_ARRAY, true); - assertArrayEquals(ArrayUtils.EMPTY_BOOLEAN_ARRAY, array); - assertEquals(Boolean.TYPE, array.getClass().getComponentType()); - array = ArrayUtils.removeElement(new boolean[] {true}, true); + array = ArrayUtils.remove(new boolean[] {true}, 0); assertArrayEquals(ArrayUtils.EMPTY_BOOLEAN_ARRAY, array); assertEquals(Boolean.TYPE, array.getClass().getComponentType()); - array = ArrayUtils.removeElement(new boolean[] {true, false}, true); + array = ArrayUtils.remove(new boolean[] {true, false}, 0); assertArrayEquals(new boolean[]{false}, array); assertEquals(Boolean.TYPE, array.getClass().getComponentType()); - array = ArrayUtils.removeElement(new boolean[] {true, false, true}, true); - assertArrayEquals(new boolean[]{false, true}, array); + array = ArrayUtils.remove(new boolean[] {true, false}, 1); + assertArrayEquals(new boolean[]{true}, array); + assertEquals(Boolean.TYPE, array.getClass().getComponentType()); + array = ArrayUtils.remove(new boolean[] {true, false, true}, 1); + assertArrayEquals(new boolean[]{true, true}, array); assertEquals(Boolean.TYPE, array.getClass().getComponentType()); + assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove(new boolean[] {true, false}, -1)); + assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove(new boolean[] {true, false}, 2)); + assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove((boolean[]) null, 0)); } @Test - public void testRemoveElementByteArray() { + public void testRemoveByteArray() { byte[] array; - array = ArrayUtils.removeElement((byte[]) null, (byte) 1); - assertNull(array); - array = ArrayUtils.removeElement(ArrayUtils.EMPTY_BYTE_ARRAY, (byte) 1); - assertArrayEquals(ArrayUtils.EMPTY_BYTE_ARRAY, array); - assertEquals(Byte.TYPE, array.getClass().getComponentType()); - array = ArrayUtils.removeElement(new byte[] {1}, (byte) 1); + array = ArrayUtils.remove(new byte[] {1}, 0); assertArrayEquals(ArrayUtils.EMPTY_BYTE_ARRAY, array); assertEquals(Byte.TYPE, array.getClass().getComponentType()); - array = ArrayUtils.removeElement(new byte[] {1, 2}, (byte) 1); + array = ArrayUtils.remove(new byte[] {1, 2}, 0); assertArrayEquals(new byte[]{2}, array); assertEquals(Byte.TYPE, array.getClass().getComponentType()); - array = ArrayUtils.removeElement(new byte[] {1, 2, 1}, (byte) 1); - assertArrayEquals(new byte[]{2, 1}, array); + array = ArrayUtils.remove(new byte[] {1, 2}, 1); + assertArrayEquals(new byte[]{1}, array); assertEquals(Byte.TYPE, array.getClass().getComponentType()); + array = ArrayUtils.remove(new byte[] {1, 2, 1}, 1); + assertArrayEquals(new byte[]{1, 1}, array); + assertEquals(Byte.TYPE, array.getClass().getComponentType()); + assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove(new byte[] {1, 2}, -1)); + assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove(new byte[] {1, 2}, 2)); + assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove((byte[]) null, 0)); } @Test - public void testRemoveElementCharArray() { + public void testRemoveCharArray() { char[] array; - array = ArrayUtils.removeElement((char[]) null, 'a'); - assertNull(array); - array = ArrayUtils.removeElement(ArrayUtils.EMPTY_CHAR_ARRAY, 'a'); + array = ArrayUtils.remove(new char[] {'a'}, 0); + assertArrayEquals(ArrayUtils.EMPTY_CHAR_ARRAY, array); + assertEquals(Character.TYPE, array.getClass().getComponentType()); + array = ArrayUtils.remove(new char[] {'a', 'b'}, 0); + assertArrayEquals(new char[]{'b'}, array); + assertEquals(Character.TYPE, array.getClass().getComponentType()); + array = ArrayUtils.remove(new char[] {'a', 'b'}, 1); + assertArrayEquals(new char[]{'a'}, array); + assertEquals(Character.TYPE, array.getClass().getComponentType()); + array = ArrayUtils.remove(new char[] {'a', 'b', 'c'}, 1); + assertArrayEquals(new char[]{'a', 'c'}, array); + assertEquals(Character.TYPE, array.getClass().getComponentType()); + assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove(new char[] {'a', 'b'}, -1)); + assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove(new char[] {'a', 'b'}, 2)); + assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove((char[]) null, 0)); + } + + @Test + public void testRemoveDoubleArray() { + double[] array; + array = ArrayUtils.remove(new double[] {1}, 0); + assertArrayEquals(ArrayUtils.EMPTY_DOUBLE_ARRAY, array); + assertEquals(Double.TYPE, array.getClass().getComponentType()); + array = ArrayUtils.remove(new double[] {1, 2}, 0); + assertArrayEquals(new double[]{2}, array); + assertEquals(Double.TYPE, array.getClass().getComponentType()); + array = ArrayUtils.remove(new double[] {1, 2}, 1); + assertArrayEquals(new double[]{1}, array); + assertEquals(Double.TYPE, array.getClass().getComponentType()); + array = ArrayUtils.remove(new double[] {1, 2, 1}, 1); + assertArrayEquals(new double[]{1, 1}, array); + assertEquals(Double.TYPE, array.getClass().getComponentType()); + assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove(new double[] {1, 2}, -1)); + assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove(new double[] {1, 2}, 2)); + assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove((double[]) null, 0)); + } + + @Test + public void testRemoveElementBooleanArray() { + boolean[] array; + array = ArrayUtils.removeElement(null, true); + assertNull(array); + array = ArrayUtils.removeElement(ArrayUtils.EMPTY_BOOLEAN_ARRAY, true); + assertArrayEquals(ArrayUtils.EMPTY_BOOLEAN_ARRAY, array); + assertEquals(Boolean.TYPE, array.getClass().getComponentType()); + array = ArrayUtils.removeElement(new boolean[] {true}, true); + assertArrayEquals(ArrayUtils.EMPTY_BOOLEAN_ARRAY, array); + assertEquals(Boolean.TYPE, array.getClass().getComponentType()); + array = ArrayUtils.removeElement(new boolean[] {true, false}, true); + assertArrayEquals(new boolean[]{false}, array); + assertEquals(Boolean.TYPE, array.getClass().getComponentType()); + array = ArrayUtils.removeElement(new boolean[] {true, false, true}, true); + assertArrayEquals(new boolean[]{false, true}, array); + assertEquals(Boolean.TYPE, array.getClass().getComponentType()); + } + + @Test + public void testRemoveElementByteArray() { + byte[] array; + array = ArrayUtils.removeElement((byte[]) null, (byte) 1); + assertNull(array); + array = ArrayUtils.removeElement(ArrayUtils.EMPTY_BYTE_ARRAY, (byte) 1); + assertArrayEquals(ArrayUtils.EMPTY_BYTE_ARRAY, array); + assertEquals(Byte.TYPE, array.getClass().getComponentType()); + array = ArrayUtils.removeElement(new byte[] {1}, (byte) 1); + assertArrayEquals(ArrayUtils.EMPTY_BYTE_ARRAY, array); + assertEquals(Byte.TYPE, array.getClass().getComponentType()); + array = ArrayUtils.removeElement(new byte[] {1, 2}, (byte) 1); + assertArrayEquals(new byte[]{2}, array); + assertEquals(Byte.TYPE, array.getClass().getComponentType()); + array = ArrayUtils.removeElement(new byte[] {1, 2, 1}, (byte) 1); + assertArrayEquals(new byte[]{2, 1}, array); + assertEquals(Byte.TYPE, array.getClass().getComponentType()); + } + + @Test + public void testRemoveElementCharArray() { + char[] array; + array = ArrayUtils.removeElement((char[]) null, 'a'); + assertNull(array); + array = ArrayUtils.removeElement(ArrayUtils.EMPTY_CHAR_ARRAY, 'a'); assertArrayEquals(ArrayUtils.EMPTY_CHAR_ARRAY, array); assertEquals(Character.TYPE, array.getClass().getComponentType()); array = ArrayUtils.removeElement(new char[] {'a'}, 'a'); @@ -360,6 +603,7 @@ public void testRemoveElementIntArray() { assertEquals(Integer.TYPE, array.getClass().getComponentType()); } + @Test @SuppressWarnings("cast") public void testRemoveElementLongArray() { @@ -380,6 +624,25 @@ public void testRemoveElementLongArray() { assertEquals(Long.TYPE, array.getClass().getComponentType()); } + @Test + public void testRemoveElementObjectArray() { + Object[] array; + array = ArrayUtils.removeElement(null, "a"); + assertNull(array); + array = ArrayUtils.removeElement(ArrayUtils.EMPTY_OBJECT_ARRAY, "a"); + assertArrayEquals(ArrayUtils.EMPTY_OBJECT_ARRAY, array); + assertEquals(Object.class, array.getClass().getComponentType()); + array = ArrayUtils.removeElement(new Object[] {"a"}, "a"); + assertArrayEquals(ArrayUtils.EMPTY_OBJECT_ARRAY, array); + assertEquals(Object.class, array.getClass().getComponentType()); + array = ArrayUtils.removeElement(new Object[] {"a", "b"}, "a"); + assertArrayEquals(new Object[]{"b"}, array); + assertEquals(Object.class, array.getClass().getComponentType()); + array = ArrayUtils.removeElement(new Object[] {"a", "b", "a"}, "a"); + assertArrayEquals(new Object[]{"b", "a"}, array); + assertEquals(Object.class, array.getClass().getComponentType()); + } + @Test public void testRemoveElementShortArray() { short[] array; @@ -399,193 +662,119 @@ public void testRemoveElementShortArray() { assertEquals(Short.TYPE, array.getClass().getComponentType()); } - - @Test - public void testRemoveAllBooleanOccurences() { - boolean[] a = null; - assertNull(ArrayUtils.removeAllOccurences(a, true)); - - a = new boolean[0]; - assertArrayEquals(ArrayUtils.EMPTY_BOOLEAN_ARRAY, ArrayUtils.removeAllOccurences(a, true)); - - a = new boolean[] { true }; - assertArrayEquals(ArrayUtils.EMPTY_BOOLEAN_ARRAY, ArrayUtils.removeAllOccurences(a, true)); - - a = new boolean[] { true, true }; - assertArrayEquals(ArrayUtils.EMPTY_BOOLEAN_ARRAY, ArrayUtils.removeAllOccurences(a, true)); - - a = new boolean[] { false, true, true, false, true }; - assertArrayEquals(new boolean[]{false, false}, ArrayUtils.removeAllOccurences(a, true)); - - a = new boolean[] { false, true, true, false, true }; - assertArrayEquals(new boolean[]{true, true, true}, ArrayUtils.removeAllOccurences(a, false)); - } - - @Test - public void testRemoveAllCharOccurences() { - char[] a = null; - assertNull(ArrayUtils.removeAllOccurences(a, '2')); - - a = new char[0]; - assertArrayEquals(ArrayUtils.EMPTY_CHAR_ARRAY, ArrayUtils.removeAllOccurences(a, '2')); - - a = new char[] { '2' }; - assertArrayEquals(ArrayUtils.EMPTY_CHAR_ARRAY, ArrayUtils.removeAllOccurences(a, '2')); - - a = new char[] { '2', '2' }; - assertArrayEquals(ArrayUtils.EMPTY_CHAR_ARRAY, ArrayUtils.removeAllOccurences(a, '2')); - - a = new char[] { '1', '2', '2', '3', '2' }; - assertArrayEquals(new char[]{'1', '3'}, ArrayUtils.removeAllOccurences(a, '2')); - - a = new char[] { '1', '2', '2', '3', '2' }; - assertArrayEquals(new char[]{'1', '2', '2', '3', '2'}, ArrayUtils.removeAllOccurences(a, '4')); - } - - @Test - public void testRemoveAllByteOccurences() { - byte[] a = null; - assertNull(ArrayUtils.removeAllOccurences(a, (byte) 2)); - - a = new byte[0]; - assertArrayEquals(ArrayUtils.EMPTY_BYTE_ARRAY, ArrayUtils.removeAllOccurences(a, (byte) 2)); - - a = new byte[] { 2 }; - assertArrayEquals(ArrayUtils.EMPTY_BYTE_ARRAY, ArrayUtils.removeAllOccurences(a, (byte) 2)); - - a = new byte[] { 2, 2 }; - assertArrayEquals(ArrayUtils.EMPTY_BYTE_ARRAY, ArrayUtils.removeAllOccurences(a, (byte) 2)); - - a = new byte[] { 1, 2, 2, 3, 2 }; - assertArrayEquals(new byte[]{1, 3}, ArrayUtils.removeAllOccurences(a, (byte) 2)); - - a = new byte[] { 1, 2, 2, 3, 2 }; - assertArrayEquals(new byte[]{1, 2, 2, 3, 2}, ArrayUtils.removeAllOccurences(a, (byte) 4)); - } - @Test - public void testRemoveAllShortOccurences() { - short[] a = null; - assertNull(ArrayUtils.removeAllOccurences(a, (short) 2)); - - a = new short[0]; - assertArrayEquals(ArrayUtils.EMPTY_SHORT_ARRAY, ArrayUtils.removeAllOccurences(a, (short) 2)); - - a = new short[] { 2 }; - assertArrayEquals(ArrayUtils.EMPTY_SHORT_ARRAY, ArrayUtils.removeAllOccurences(a, (short) 2)); - - a = new short[] { 2, 2 }; - assertArrayEquals(ArrayUtils.EMPTY_SHORT_ARRAY, ArrayUtils.removeAllOccurences(a, (short) 2)); - - a = new short[] { 1, 2, 2, 3, 2 }; - assertArrayEquals(new short[]{1, 3}, ArrayUtils.removeAllOccurences(a, (short) 2)); - - a = new short[] { 1, 2, 2, 3, 2 }; - assertArrayEquals(new short[]{1, 2, 2, 3, 2}, ArrayUtils.removeAllOccurences(a, (short) 4)); + public void testRemoveFloatArray() { + float[] array; + array = ArrayUtils.remove(new float[] {1}, 0); + assertArrayEquals(ArrayUtils.EMPTY_FLOAT_ARRAY, array); + assertEquals(Float.TYPE, array.getClass().getComponentType()); + array = ArrayUtils.remove(new float[] {1, 2}, 0); + assertArrayEquals(new float[]{2}, array); + assertEquals(Float.TYPE, array.getClass().getComponentType()); + array = ArrayUtils.remove(new float[] {1, 2}, 1); + assertArrayEquals(new float[]{1}, array); + assertEquals(Float.TYPE, array.getClass().getComponentType()); + array = ArrayUtils.remove(new float[] {1, 2, 1}, 1); + assertArrayEquals(new float[]{1, 1}, array); + assertEquals(Float.TYPE, array.getClass().getComponentType()); + assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove(new float[] {1, 2}, -1)); + assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove(new float[] {1, 2}, 2)); + assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove((float[]) null, 0)); } @Test - public void testRemoveAllIntOccurences() { - int[] a = null; - assertNull(ArrayUtils.removeAllOccurences(a, 2)); - - a = new int[0]; - assertArrayEquals(ArrayUtils.EMPTY_INT_ARRAY, ArrayUtils.removeAllOccurences(a, 2)); - - a = new int[] { 2 }; - assertArrayEquals(ArrayUtils.EMPTY_INT_ARRAY, ArrayUtils.removeAllOccurences(a, 2)); - - a = new int[] { 2, 2 }; - assertArrayEquals(ArrayUtils.EMPTY_INT_ARRAY, ArrayUtils.removeAllOccurences(a, 2)); - - a = new int[] { 1, 2, 2, 3, 2 }; - assertArrayEquals(new int[]{1, 3}, ArrayUtils.removeAllOccurences(a, 2)); - - a = new int[] { 1, 2, 2, 3, 2 }; - assertArrayEquals(new int[]{1, 2, 2, 3, 2}, ArrayUtils.removeAllOccurences(a, 4)); + public void testRemoveIntArray() { + int[] array; + array = ArrayUtils.remove(new int[] {1}, 0); + assertArrayEquals(ArrayUtils.EMPTY_INT_ARRAY, array); + assertEquals(Integer.TYPE, array.getClass().getComponentType()); + array = ArrayUtils.remove(new int[] {1, 2}, 0); + assertArrayEquals(new int[]{2}, array); + assertEquals(Integer.TYPE, array.getClass().getComponentType()); + array = ArrayUtils.remove(new int[] {1, 2}, 1); + assertArrayEquals(new int[]{1}, array); + assertEquals(Integer.TYPE, array.getClass().getComponentType()); + array = ArrayUtils.remove(new int[] {1, 2, 1}, 1); + assertArrayEquals(new int[]{1, 1}, array); + assertEquals(Integer.TYPE, array.getClass().getComponentType()); + assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove(new int[] {1, 2}, -1)); + assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove(new int[] {1, 2}, 2)); + assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove((int[]) null, 0)); } @Test - public void testRemoveAllLongOccurences() { - long[] a = null; - assertNull(ArrayUtils.removeAllOccurences(a, 2)); - - a = new long[0]; - assertArrayEquals(ArrayUtils.EMPTY_LONG_ARRAY, ArrayUtils.removeAllOccurences(a, 2)); - - a = new long[] { 2 }; - assertArrayEquals(ArrayUtils.EMPTY_LONG_ARRAY, ArrayUtils.removeAllOccurences(a, 2)); - - a = new long[] { 2, 2 }; - assertArrayEquals(ArrayUtils.EMPTY_LONG_ARRAY, ArrayUtils.removeAllOccurences(a, 2)); - - a = new long[] { 1, 2, 2, 3, 2 }; - assertArrayEquals(new long[]{1, 3}, ArrayUtils.removeAllOccurences(a, 2)); - - a = new long[] { 1, 2, 2, 3, 2 }; - assertArrayEquals(new long[]{1, 2, 2, 3, 2}, ArrayUtils.removeAllOccurences(a, 4)); + public void testRemoveLongArray() { + long[] array; + array = ArrayUtils.remove(new long[] {1}, 0); + assertArrayEquals(ArrayUtils.EMPTY_LONG_ARRAY, array); + assertEquals(Long.TYPE, array.getClass().getComponentType()); + array = ArrayUtils.remove(new long[] {1, 2}, 0); + assertArrayEquals(new long[]{2}, array); + assertEquals(Long.TYPE, array.getClass().getComponentType()); + array = ArrayUtils.remove(new long[] {1, 2}, 1); + assertArrayEquals(new long[]{1}, array); + assertEquals(Long.TYPE, array.getClass().getComponentType()); + array = ArrayUtils.remove(new long[] {1, 2, 1}, 1); + assertArrayEquals(new long[]{1, 1}, array); + assertEquals(Long.TYPE, array.getClass().getComponentType()); + assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove(new long[] {1, 2}, -1)); + assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove(new long[] {1, 2}, 2)); + assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove((long[]) null, 0)); } @Test - public void testRemoveAllFloatOccurences() { - float[] a = null; - assertNull(ArrayUtils.removeAllOccurences(a, 2)); - - a = new float[0]; - assertArrayEquals(ArrayUtils.EMPTY_FLOAT_ARRAY, ArrayUtils.removeAllOccurences(a, 2)); - - a = new float[] { 2 }; - assertArrayEquals(ArrayUtils.EMPTY_FLOAT_ARRAY, ArrayUtils.removeAllOccurences(a, 2)); - - a = new float[] { 2, 2 }; - assertArrayEquals(ArrayUtils.EMPTY_FLOAT_ARRAY, ArrayUtils.removeAllOccurences(a, 2)); - - a = new float[] { 1, 2, 2, 3, 2 }; - assertArrayEquals(new float[]{1, 3}, ArrayUtils.removeAllOccurences(a, 2)); - - a = new float[] { 1, 2, 2, 3, 2 }; - assertArrayEquals(new float[]{1, 2, 2, 3, 2}, ArrayUtils.removeAllOccurences(a, 4)); + public void testRemoveNumberArray() { + final Number[] inarray = {Integer.valueOf(1), Long.valueOf(2), Byte.valueOf((byte) 3)}; + assertEquals(3, inarray.length); + Number[] outarray; + outarray = ArrayUtils.remove(inarray, 1); + assertEquals(2, outarray.length); + assertEquals(Number.class, outarray.getClass().getComponentType()); + outarray = ArrayUtils.remove(outarray, 1); + assertEquals(1, outarray.length); + assertEquals(Number.class, outarray.getClass().getComponentType()); + outarray = ArrayUtils.remove(outarray, 0); + assertEquals(0, outarray.length); + assertEquals(Number.class, outarray.getClass().getComponentType()); } @Test - public void testRemoveAllDoubleOccurences() { - double[] a = null; - assertNull(ArrayUtils.removeAllOccurences(a, 2)); - - a = new double[0]; - assertArrayEquals(ArrayUtils.EMPTY_DOUBLE_ARRAY, ArrayUtils.removeAllOccurences(a, 2)); - - a = new double[] { 2 }; - assertArrayEquals(ArrayUtils.EMPTY_DOUBLE_ARRAY, ArrayUtils.removeAllOccurences(a, 2)); - - a = new double[] { 2, 2 }; - assertArrayEquals(ArrayUtils.EMPTY_DOUBLE_ARRAY, ArrayUtils.removeAllOccurences(a, 2)); - - a = new double[] { 1, 2, 2, 3, 2 }; - assertArrayEquals(new double[]{1, 3}, ArrayUtils.removeAllOccurences(a, 2)); - - a = new double[] { 1, 2, 2, 3, 2 }; - assertArrayEquals(new double[]{1, 2, 2, 3, 2}, ArrayUtils.removeAllOccurences(a, 4)); + public void testRemoveObjectArray() { + Object[] array; + array = ArrayUtils.remove(new Object[] {"a"}, 0); + assertArrayEquals(ArrayUtils.EMPTY_OBJECT_ARRAY, array); + assertEquals(Object.class, array.getClass().getComponentType()); + array = ArrayUtils.remove(new Object[] {"a", "b"}, 0); + assertArrayEquals(new Object[]{"b"}, array); + assertEquals(Object.class, array.getClass().getComponentType()); + array = ArrayUtils.remove(new Object[] {"a", "b"}, 1); + assertArrayEquals(new Object[]{"a"}, array); + assertEquals(Object.class, array.getClass().getComponentType()); + array = ArrayUtils.remove(new Object[] {"a", "b", "c"}, 1); + assertArrayEquals(new Object[]{"a", "c"}, array); + assertEquals(Object.class, array.getClass().getComponentType()); + assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove(new Object[] {"a", "b"}, -1)); + assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove(new Object[] {"a", "b"}, 2)); + assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove((Object[]) null, 0)); } @Test - public void testRemoveAllObjectOccurences() { - String[] a = null; - assertNull(ArrayUtils.removeAllOccurences(a, "2")); - - a = new String[0]; - assertArrayEquals(ArrayUtils.EMPTY_STRING_ARRAY, ArrayUtils.removeAllOccurences(a, "2")); - - a = new String[] { "2" }; - assertArrayEquals(ArrayUtils.EMPTY_STRING_ARRAY, ArrayUtils.removeAllOccurences(a, "2")); - - a = new String[] { "2", "2" }; - assertArrayEquals(ArrayUtils.EMPTY_STRING_ARRAY, ArrayUtils.removeAllOccurences(a, "2")); - - a = new String[] { "1", "2", "2", "3", "2" }; - assertArrayEquals(new String[]{"1", "3"}, ArrayUtils.removeAllOccurences(a, "2")); - - a = new String[] { "1", "2", "2", "3", "2" }; - assertArrayEquals(new String[]{"1", "2", "2", "3", "2"}, ArrayUtils.removeAllOccurences(a, "4")); + public void testRemoveShortArray() { + short[] array; + array = ArrayUtils.remove(new short[] {1}, 0); + assertArrayEquals(ArrayUtils.EMPTY_SHORT_ARRAY, array); + assertEquals(Short.TYPE, array.getClass().getComponentType()); + array = ArrayUtils.remove(new short[] {1, 2}, 0); + assertArrayEquals(new short[]{2}, array); + assertEquals(Short.TYPE, array.getClass().getComponentType()); + array = ArrayUtils.remove(new short[] {1, 2}, 1); + assertArrayEquals(new short[]{1}, array); + assertEquals(Short.TYPE, array.getClass().getComponentType()); + array = ArrayUtils.remove(new short[] {1, 2, 1}, 1); + assertArrayEquals(new short[]{1, 1}, array); + assertEquals(Short.TYPE, array.getClass().getComponentType()); + assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove(new short[] {1, 2}, -1)); + assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove(new short[] {1, 2}, 2)); + assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove((short[]) null, 0)); } } diff --git a/src/test/java/org/apache/commons/lang3/ArrayUtilsTest.java b/src/test/java/org/apache/commons/lang3/ArrayUtilsTest.java index 16faecd8c91..3831f090a62 100644 --- a/src/test/java/org/apache/commons/lang3/ArrayUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/ArrayUtilsTest.java @@ -5070,7 +5070,7 @@ public void testShuffleBoolean() { ArrayUtils.shuffle(array1, new Random(SEED)); assertFalse(Arrays.equals(array1, array2)); - assertEquals(5, ArrayUtils.removeAllOccurences(array1, true).length); + assertEquals(5, ArrayUtils.removeAllOccurrences(array1, true).length); } @Test From e3a7399a7d82a5b3a33cc7653107821ce1709f67 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Mon, 23 Mar 2020 09:10:49 -0400 Subject: [PATCH 0052/3230] Prepare for 3.10 RC1. --- CONTRIBUTING.md | 2 +- NOTICE.txt | 2 +- README.md | 12 +- RELEASE-NOTES.txt | 105 +++++++++++ src/changes/changes.xml | 2 +- .../release-notes/RELEASE-NOTES-3.10.txt | 119 ++++++++++++ src/site/xdoc/download_lang.xml | 171 +++++++++--------- src/site/xdoc/issue-tracking.xml | 4 +- src/site/xdoc/mail-lists.xml | 38 ++-- src/site/xdoc/release-history.xml | 3 + 10 files changed, 343 insertions(+), 115 deletions(-) create mode 100644 src/site/resources/release-notes/RELEASE-NOTES-3.10.txt diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index cf6b5657134..18d9c28e7f8 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -25,7 +25,7 @@ | commons-build-plugin/trunk/src/main/resources/commons-xdoc-templates | +======================================================================+ | | - | 1) Re-generate using: mvn commons:contributing-md | + | 1) Re-generate using: mvn commons-build:contributing-md | | | | 2) Set the following properties in the component's pom: | | - commons.jira.id (required, alphabetic, upper case) | diff --git a/NOTICE.txt b/NOTICE.txt index f223e8f63ac..72eb0990a0f 100644 --- a/NOTICE.txt +++ b/NOTICE.txt @@ -2,4 +2,4 @@ Apache Commons Lang Copyright 2001-2020 The Apache Software Foundation This product includes software developed at -The Apache Software Foundation (http://www.apache.org/). +The Apache Software Foundation (https://www.apache.org/). diff --git a/README.md b/README.md index ae9cdc2041c..a2e48251eef 100644 --- a/README.md +++ b/README.md @@ -25,7 +25,7 @@ | commons-build-plugin/trunk/src/main/resources/commons-xdoc-templates | +======================================================================+ | | - | 1) Re-generate using: mvn commons:readme-md | + | 1) Re-generate using: mvn commons-build:readme-md | | | | 2) Set the following properties in the component's pom: | | - commons.componentid (required, alphabetic, lower case) | @@ -46,7 +46,7 @@ Apache Commons Lang [![Build Status](https://travis-ci.org/apache/commons-lang.svg)](https://travis-ci.org/apache/commons-lang) [![Coverage Status](https://coveralls.io/repos/apache/commons-lang/badge.svg)](https://coveralls.io/r/apache/commons-lang) [![Maven Central](https://maven-badges.herokuapp.com/maven-central/org.apache.commons/commons-lang3/badge.svg)](https://maven-badges.herokuapp.com/maven-central/org.apache.commons/commons-lang3/) -[![Javadocs](https://javadoc.io/badge/org.apache.commons/commons-lang3/3.9.svg)](https://javadoc.io/doc/org.apache.commons/commons-lang3/3.9) +[![Javadocs](https://javadoc.io/badge/org.apache.commons/commons-lang3/3.10.svg)](https://javadoc.io/doc/org.apache.commons/commons-lang3/3.10) Apache Commons Lang, a package of Java utility classes for the classes that are in java.lang's hierarchy, or are considered to be so @@ -55,13 +55,13 @@ Apache Commons Lang, a package of Java utility classes for the Documentation ------------- -More information can be found on the [Apache Commons Lang homepage](https://commons.apache.org/proper/commons-lang/). -The [Javadoc](https://commons.apache.org/proper/commons-lang/javadocs/api-release/) can be browsed. +More information can be found on the [Apache Commons Lang homepage](https://commons.apache.org/proper/commons-lang). +The [Javadoc](https://commons.apache.org/proper/commons-lang/apidocs) can be browsed. Questions related to the usage of Apache Commons Lang should be posted to the [user mailing list][ml]. Where can I get the latest release? ----------------------------------- -You can download source and binaries from our [download page](https://commons.apache.org/proper/commons-lang3/download_lang3.cgi). +You can download source and binaries from our [download page](https://commons.apache.org/proper/commons-lang/download_lang.cgi). Alternatively you can pull it from the central Maven repositories: @@ -69,7 +69,7 @@ Alternatively you can pull it from the central Maven repositories: org.apache.commons commons-lang3 - 3.9 + 3.10 ``` diff --git a/RELEASE-NOTES.txt b/RELEASE-NOTES.txt index f9ee7aa22f3..88bc7eb9010 100644 --- a/RELEASE-NOTES.txt +++ b/RELEASE-NOTES.txt @@ -1,3 +1,108 @@ + Apache Commons Lang + Version 3.10 + Release Notes + + +INTRODUCTION: + +This document contains the release notes for the 3.10 version of Apache Commons Lang. +Commons Lang is a set of utility functions and reusable components that should be of use in any +Java environment. + +Lang 3.9 and onwards now targets Java 8, making use of features that arrived with Java 8. + +For the advice on upgrading from 2.x to 3.x, see the following page: + + https://commons.apache.org/lang/article3_0.html + +Apache Commons Lang, a package of Java utility classes for the +classes that are in java.lang's hierarchy, or are considered to be so +standard as to justify existence in java.lang. + +New features and bug fixes. Requires Java 8, supports Java 9, 10, 11. + +Changes in this version include: + +New features: +o LANG-1457: Add ExceptionUtils.throwableOfType(Throwable, Class) and friends. +o LANG-1458: Add EMPTY_ARRAY constants to classes in org.apache.commons.lang3.tuple. +o LANG-1461: Add null-safe StringUtils APIs to wrap String#getBytes([Charset|String]). +o LANG-1467: Add zero arg constructor for org.apache.commons.lang3.NotImplementedException. +o LANG-1470: Add ArrayUtils.addFirst() methods. +o LANG-1479: Add Range.fit(T) to fit a value into a range. +o LANG-1477: Added Functions.as*, and tests thereof, as suggested by Peter Verhas +o LANG-1485: Add getters for lhs and rhs objects in DiffResult #451. Thanks to nicolasbd. +o LANG-1486: Generify builder classes Diffable, DiffBuilder, and DiffResult #452. Thanks to Gary Gregory. +o LANG-1487: Add ClassLoaderUtils with toString() implementations #453. Thanks to Gary Gregory. +o LANG-1489: Add null-safe APIs as StringUtils.toRootLowerCase(String) and StringUtils.toRootUpperCase(String) #456. Thanks to Gary Gregory. +o LANG-1494: Add org.apache.commons.lang3.time.Calendars. Thanks to Gary Gregory. +o LANG-1495: Add EnumUtils getEnum() methods with default values #475. Thanks to Cheong Voon Leong. +o LANG-1177: Added indexesOf methods and simplified removeAllOccurences #471. Thanks to Liel Fridman. +o LANG-1498: Add support of lambda value evaluation for defaulting methods #416. Thanks to Lysergid, Gary Gregory. +o LANG-1503: Add factory methods to Pair classes with Map.Entry input. #454. Thanks to XenoAmess, Gary Gregory. +o LANG-1505: Add StopWatch convenience APIs to format times and create a simple instance. Thanks to Gary Gregory. +o LANG-1506: Allow a StopWatch to carry an optional message. Thanks to Gary Gregory. +o LANG-1507: Add ComparableUtils #398. Thanks to Sam Kruglov, Mark Dacek, Marc Magon, Pascal Schumacher, Rob Tompkins, Bruno P. Kinoshita, Amey Jadiye, Gary Gregory. +o LANG-1508: Add org.apache.commons.lang3.SystemUtils.getUserName(). Thanks to Gary Gregory. +o LANG-1509: Add ObjectToStringComparator. #483. Thanks to Gary Gregory. +o LANG-1510: Add org.apache.commons.lang3.arch.Processor.Arch.getLabel(). Thanks to Gary Gregory. +o LANG-1512: Add IS_JAVA_14 and IS_JAVA_15 to org.apache.commons.lang3.SystemUtils. Thanks to Gary Gregory. +o LANG-1513: ObjectUtils: Get first non-null supplier value. Thanks to Bernhard Bonigl, Gary Gregory. +o Added the Streams class, and Functions.stream() as an accessor thereof. + +Fixed Bugs: +o LANG-1514: Make test more stable by wrapping assertions in hashset. Thanks to contextshuffling. +o LANG-1450: Generate Javadoc jar on build. +o LANG-1460: Trivial: year of release for 3.9 says 2018, should be 2019 Thanks to Larry West. +o LANG-1476: Use synchronize on a set created with Collections.synchronizedSet before iterating Thanks to emopers. +o LANG-1475: StringUtils.unwrap incorrect throw StringIndexOutOfBoundsException. Thanks to stzx. +o LANG-1406: StringIndexOutOfBoundsException in StringUtils.replaceIgnoreCase #423. Thanks to geratorres. +o LANG-1453: StringUtils.removeIgnoreCase("?a", "a") throws IndexOutOfBoundsException #423. Thanks to geratorres. +o LANG-1426: Corrected usage examples in Javadocs #458. Thanks to Brower, Mikko Maunu, Suraj Gautam. +o LANG-1463: StringUtils abbreviate returns String of length greater than maxWidth #477. Thanks to bbeckercscc, Gary Gregory. +o LANG-1500: Test may fail due to a different order of fields returned by reflection api #480. Thanks to contextshuffling. +o LANG-1501: Sort fields in ReflectionToStringBuilder for deterministic order #481. Thanks to contextshuffling. +o LANG-1433: MethodUtils will throw a NPE if invokeMethod() is called for a var-args method #407. Thanks to Christian Franzen. +o LANG-1518: MethodUtils.getAnnotation() with searchSupers = true does not work if super is generic #494. Thanks to Michele Preti, Bruno P. Kinoshita, Gary Gregory. + +Changes: +o LANG-1437: Remove redundant if statements in join methods #411. Thanks to Andrei Troie. +o commons.japicmp.version 0.13.1 -> 0.14.1. +o junit-jupiter 5.5.0 -> 5.5.1. +o junit-jupiter 5.5.1 -> 5.5.2. +o Improve Javadoc based on the discussion of the GitHub PR #459. Thanks to Jonathan Leitschuh, Bruno P. Kinoshita, Rob Tompkins, Gary Gregory. +o maven-checkstyle-plugin 3.0.0 -> 3.1.0. +o LANG-696: Update documentation related to the issue LANG-696 #449. Thanks to Peter Verhas. +o AnnotationUtils little cleanup #467. Thanks to Peter Verhas. +o Update test dependency: org.easymock:easymock 4.0.2 -> 4.1. Thanks to Gary Gregory. +o Update test dependency: org.hamcrest:hamcrest 2.1 -> 2.2. Thanks to Gary Gregory. +o Update test dependency: org.junit-pioneer:junit-pioneer 0.3.0 -> 0.4.2. Thanks to Gary Gregory. +o Update build dependency: com.puppycrawl.tools:checkstyle 8.18 -> 8.27. Thanks to Gary Gregory. +o Update POM parent: org.apache.commons:commons-parent 48 -> 50. Thanks to Gary Gregory. +o BooleanUtils Javadoc #469. Thanks to Peter Verhas. +o Functions Javadoc #466. Thanks to Peter Verhas. +o org.easymock:easymock 4.1 -> 4.2. Thanks to Gary Gregory. +o org.junit-pioneer:junit-pioneer 0.4.2 -> 0.5.4. Thanks to Gary Gregory. +o org.junit.jupiter:junit-jupiter 5.5.2 -> 5.6.0. Thanks to Gary Gregory. +o Use Javadoc {@code} instead of pre tags. #490. Thanks to Peter Verhas. +o ExceptionUtilsTest to 100% #486. Thanks to Peter Verhas. +o Reuse own code in Functions.java #493. Thanks to Peter Verhas. +o LANG-1523: Avoid unnecessary allocation in StringUtils.wrapIfMissing. #496. Thanks to Edgar Asatryan, Bruno P. Kinoshita, Gary Gregory. +o LANG-1525: Internally use Validate.notNull(foo, ...) instead of Validate.isTrue(foo != null, ...). Thanks to Edgar Asatryan, Bruno P. Kinoshita, Gary Gregory. +o LANG-1526: Add 1 and 0 in toBooleanObject(final String str) #502. Thanks to Dominik Schramm. +o LANG-1527: Remove an redundant argument check in NumberUtils #504. Thanks to Pengyu Nie. +o LANG-1529: Deprecate org.apache.commons.lang3.ArrayUtils.removeAllOccurences(*) for org.apache.commons.lang3.ArrayUtils.removeAllOccurrences(*). Thanks to Gary Gregory, BillCindy, Bruno P. Kinoshita. + + +Historical list of changes: https://commons.apache.org/proper/commons-lang/changes-report.html + +For complete information on Apache Commons Lang, including instructions on how to submit bug reports, +patches, or suggestions for improvement, see the Apache Apache Commons Lang website: + +https://commons.apache.org/proper/commons-lang/ + +============================================================================= + Apache Commons Lang Version 3.9 Release Notes diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 026336fbb73..86afaaabcff 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -45,7 +45,7 @@ The type attribute can be add,update,fix,remove. - + Make test more stable by wrapping assertions in hashset. Generate Javadoc jar on build. Add ExceptionUtils.throwableOfType(Throwable, Class) and friends. diff --git a/src/site/resources/release-notes/RELEASE-NOTES-3.10.txt b/src/site/resources/release-notes/RELEASE-NOTES-3.10.txt new file mode 100644 index 00000000000..04e4e067ceb --- /dev/null +++ b/src/site/resources/release-notes/RELEASE-NOTES-3.10.txt @@ -0,0 +1,119 @@ + +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. + + + Apache Commons Lang + Version 3.10-SNAPSHOT + Release Notes + + +INTRODUCTION: + +This document contains the release notes for the 3.10-SNAPSHOT version of Apache Commons Lang. +Commons Lang is a set of utility functions and reusable components that should be of use in any +Java environment. + +Lang 3.9 and onwards now targets Java 8, making use of features that arrived with Java 8. + +For the advice on upgrading from 2.x to 3.x, see the following page: + + https://commons.apache.org/lang/article3_0.html + +Apache Commons Lang, a package of Java utility classes for the +classes that are in java.lang's hierarchy, or are considered to be so +standard as to justify existence in java.lang. + +New features and bug fixes. Requires Java 8, supports Java 9, 10, 11. + +Changes in this version include: + +New features: +o LANG-1457: Add ExceptionUtils.throwableOfType(Throwable, Class) and friends. +o LANG-1458: Add EMPTY_ARRAY constants to classes in org.apache.commons.lang3.tuple. +o LANG-1461: Add null-safe StringUtils APIs to wrap String#getBytes([Charset|String]). +o LANG-1467: Add zero arg constructor for org.apache.commons.lang3.NotImplementedException. +o LANG-1470: Add ArrayUtils.addFirst() methods. +o LANG-1479: Add Range.fit(T) to fit a value into a range. +o LANG-1477: Added Functions.as*, and tests thereof, as suggested by Peter Verhas +o LANG-1485: Add getters for lhs and rhs objects in DiffResult #451. Thanks to nicolasbd. +o LANG-1486: Generify builder classes Diffable, DiffBuilder, and DiffResult #452. Thanks to Gary Gregory. +o LANG-1487: Add ClassLoaderUtils with toString() implementations #453. Thanks to Gary Gregory. +o LANG-1489: Add null-safe APIs as StringUtils.toRootLowerCase(String) and StringUtils.toRootUpperCase(String) #456. Thanks to Gary Gregory. +o LANG-1494: Add org.apache.commons.lang3.time.Calendars. Thanks to Gary Gregory. +o LANG-1495: Add EnumUtils getEnum() methods with default values #475. Thanks to Cheong Voon Leong. +o LANG-1177: Added indexesOf methods and simplified removeAllOccurences #471. Thanks to Liel Fridman. +o LANG-1498: Add support of lambda value evaluation for defaulting methods #416. Thanks to Lysergid, Gary Gregory. +o LANG-1503: Add factory methods to Pair classes with Map.Entry input. #454. Thanks to XenoAmess, Gary Gregory. +o LANG-1505: Add StopWatch convenience APIs to format times and create a simple instance. Thanks to Gary Gregory. +o LANG-1506: Allow a StopWatch to carry an optional message. Thanks to Gary Gregory. +o LANG-1507: Add ComparableUtils #398. Thanks to Sam Kruglov, Mark Dacek, Marc Magon, Pascal Schumacher, Rob Tompkins, Bruno P. Kinoshita, Amey Jadiye, Gary Gregory. +o LANG-1508: Add org.apache.commons.lang3.SystemUtils.getUserName(). Thanks to Gary Gregory. +o LANG-1509: Add ObjectToStringComparator. #483. Thanks to Gary Gregory. +o LANG-1510: Add org.apache.commons.lang3.arch.Processor.Arch.getLabel(). Thanks to Gary Gregory. +o LANG-1512: Add IS_JAVA_14 and IS_JAVA_15 to org.apache.commons.lang3.SystemUtils. Thanks to Gary Gregory. +o LANG-1513: ObjectUtils: Get first non-null supplier value. Thanks to Bernhard Bonigl, Gary Gregory. +o Added the Streams class, and Functions.stream() as an accessor thereof. + +Fixed Bugs: +o LANG-1514: Make test more stable by wrapping assertions in hashset. Thanks to contextshuffling. +o LANG-1450: Generate Javadoc jar on build. +o LANG-1460: Trivial: year of release for 3.9 says 2018, should be 2019 Thanks to Larry West. +o LANG-1476: Use synchronize on a set created with Collections.synchronizedSet before iterating Thanks to emopers. +o LANG-1475: StringUtils.unwrap incorrect throw StringIndexOutOfBoundsException. Thanks to stzx. +o LANG-1406: StringIndexOutOfBoundsException in StringUtils.replaceIgnoreCase #423. Thanks to geratorres. +o LANG-1453: StringUtils.removeIgnoreCase("?a", "a") throws IndexOutOfBoundsException #423. Thanks to geratorres. +o LANG-1426: Corrected usage examples in Javadocs #458. Thanks to Brower, Mikko Maunu, Suraj Gautam. +o LANG-1463: StringUtils abbreviate returns String of length greater than maxWidth #477. Thanks to bbeckercscc, Gary Gregory. +o LANG-1500: Test may fail due to a different order of fields returned by reflection api #480. Thanks to contextshuffling. +o LANG-1501: Sort fields in ReflectionToStringBuilder for deterministic order #481. Thanks to contextshuffling. +o LANG-1433: MethodUtils will throw a NPE if invokeMethod() is called for a var-args method #407. Thanks to Christian Franzen. +o LANG-1518: MethodUtils.getAnnotation() with searchSupers = true does not work if super is generic #494. Thanks to Michele Preti, Bruno P. Kinoshita, Gary Gregory. + +Changes: +o LANG-1437: Remove redundant if statements in join methods #411. Thanks to Andrei Troie. +o commons.japicmp.version 0.13.1 -> 0.14.1. +o junit-jupiter 5.5.0 -> 5.5.1. +o junit-jupiter 5.5.1 -> 5.5.2. +o Improve Javadoc based on the discussion of the GitHub PR #459. Thanks to Jonathan Leitschuh, Bruno P. Kinoshita, Rob Tompkins, Gary Gregory. +o maven-checkstyle-plugin 3.0.0 -> 3.1.0. +o LANG-696: Update documentation related to the issue LANG-696 #449. Thanks to Peter Verhas. +o AnnotationUtils little cleanup #467. Thanks to Peter Verhas. +o Update test dependency: org.easymock:easymock 4.0.2 -> 4.1. Thanks to Gary Gregory. +o Update test dependency: org.hamcrest:hamcrest 2.1 -> 2.2. Thanks to Gary Gregory. +o Update test dependency: org.junit-pioneer:junit-pioneer 0.3.0 -> 0.4.2. Thanks to Gary Gregory. +o Update build dependency: com.puppycrawl.tools:checkstyle 8.18 -> 8.27. Thanks to Gary Gregory. +o Update POM parent: org.apache.commons:commons-parent 48 -> 50. Thanks to Gary Gregory. +o BooleanUtils Javadoc #469. Thanks to Peter Verhas. +o Functions Javadoc #466. Thanks to Peter Verhas. +o org.easymock:easymock 4.1 -> 4.2. Thanks to Gary Gregory. +o org.junit-pioneer:junit-pioneer 0.4.2 -> 0.5.4. Thanks to Gary Gregory. +o org.junit.jupiter:junit-jupiter 5.5.2 -> 5.6.0. Thanks to Gary Gregory. +o Use Javadoc {@code} instead of pre tags. #490. Thanks to Peter Verhas. +o ExceptionUtilsTest to 100% #486. Thanks to Peter Verhas. +o Reuse own code in Functions.java #493. Thanks to Peter Verhas. +o LANG-1523: Avoid unnecessary allocation in StringUtils.wrapIfMissing. #496. Thanks to Edgar Asatryan, Bruno P. Kinoshita, Gary Gregory. +o LANG-1525: Internally use Validate.notNull(foo, ...) instead of Validate.isTrue(foo != null, ...). Thanks to Edgar Asatryan, Bruno P. Kinoshita, Gary Gregory. +o LANG-1526: Add 1 and 0 in toBooleanObject(final String str) #502. Thanks to Dominik Schramm. +o LANG-1527: Remove an redundant argument check in NumberUtils #504. Thanks to Pengyu Nie. +o LANG-1529: Deprecate org.apache.commons.lang3.ArrayUtils.removeAllOccurences(*) for org.apache.commons.lang3.ArrayUtils.removeAllOccurrences(*). Thanks to Gary Gregory, BillCindy, Bruno P. Kinoshita. + + +Historical list of changes: https://commons.apache.org/proper/commons-lang/changes-report.html + +For complete information on Apache Commons Lang, including instructions on how to submit bug reports, +patches, or suggestions for improvement, see the Apache Apache Commons Lang website: + +https://commons.apache.org/proper/commons-lang/ \ No newline at end of file diff --git a/src/site/xdoc/download_lang.xml b/src/site/xdoc/download_lang.xml index f2b323812ca..b8491da3411 100644 --- a/src/site/xdoc/download_lang.xml +++ b/src/site/xdoc/download_lang.xml @@ -26,22 +26,24 @@ limitations under the License. | commons-build-plugin/trunk/src/main/resources/commons-xdoc-templates | +======================================================================+ | | - | 1) Re-generate using: mvn commons:download-page | + | 1) Re-generate using: mvn commons-build:download-page | | | | 2) Set the following properties in the component's pom: | - | - commons.componentid (required, alphabetic, lower case) | + | - commons.componentid (required, alphabetic, lower case) | | - commons.release.version (required) | | - commons.release.name (required) | | - commons.binary.suffix (optional) | | (defaults to "-bin", set to "" for pre-maven2 releases) | | - commons.release.desc (optional) | | - commons.release.subdir (optional) | + | - commons.release.hash (optional, lowercase, default sha512) | | | - | - commons.release.2/3.version (conditional) | - | - commons.release.2/3.name (conditional) | - | - commons.release.2/3.binary.suffix (optional) | - | - commons.release.2/3.desc (optional) | - | - commons.release.2/3.subdir (optional) | + | - commons.release.[234].version (conditional) | + | - commons.release.[234].name (conditional) | + | - commons.release.[234].binary.suffix (optional) | + | - commons.release.[234].desc (optional) | + | - commons.release.[234].subdir (optional) | + | - commons.release.[234].hash (optional, lowercase, [sha512])| | | | 3) Example Properties | | (commons.release.name inherited by parent: | @@ -61,83 +63,82 @@ limitations under the License.

- -

- We recommend you use a mirror to download our release - builds, but you must verify the integrity of - the downloaded files using signatures downloaded from our main - distribution directories. Recent releases (48 hours) may not yet - be available from all the mirrors. -

- -

- You are currently using [preferred]. If you - encounter a problem with this mirror, please select another - mirror. If all mirrors are failing, there are backup - mirrors (at the end of the mirrors list) that should be - available. -

- [if-any logo][end] -

+ +

+ We recommend you use a mirror to download our release + builds, but you must verify the integrity of + the downloaded files using signatures downloaded from our main + distribution directories. Recent releases (48 hours) may not yet + be available from all the mirrors. +

-
-

- Other mirrors: - - -

-
+

+ You are currently using [preferred]. If you + encounter a problem with this mirror, please select another + mirror. If all mirrors are failing, there are backup + mirrors (at the end of the mirrors list) that should be + available. +

+ [if-any logo][end] +

+

- It is essential that you - verify the integrity - of downloaded files, preferably using the PGP signature (*.asc files); - failing that using the SHA512 hash (*.sha512 checksum files) or - SHA1 hash (*.sha1 checksum files). -

-

- The KEYS - file contains the public PGP keys used by Apache Commons developers - to sign releases. + Other mirrors: + +

- +
+ +

+ It is essential that you + verify the integrity + of downloaded files, preferably using the PGP signature (*.asc files); + failing that using the SHA512 hash (*.sha512 checksum files). +

+

+ The KEYS + file contains the public PGP keys used by Apache Commons developers + to sign releases. +

+
-
+
- - - + + + - - - + + +
commons-lang3-3.9-bin.tar.gzsha512pgpcommons-lang3-3.10-bin.tar.gzsha512pgp
commons-lang3-3.9-bin.zipsha512pgpcommons-lang3-3.10-bin.zipsha512pgp
- - - + + + - - - + + +
commons-lang3-3.9-src.tar.gzsha512pgpcommons-lang3-3.10-src.tar.gzsha512pgp
commons-lang3-3.9-src.zipsha512pgpcommons-lang3-3.10-src.zipsha512pgp
@@ -146,40 +147,40 @@ limitations under the License. - - - + + + - - - + + +
commons-lang-2.6-bin.tar.gzsha512pgpcommons-lang-2.6-bin.tar.gzsha512pgp
commons-lang-2.6-bin.zipsha512pgpcommons-lang-2.6-bin.zipsha512pgp
- - - + + + - - - + + +
commons-lang-2.6-src.tar.gzsha512pgpcommons-lang-2.6-src.tar.gzsha512pgp
commons-lang-2.6-src.zipsha512pgpcommons-lang-2.6-src.zipsha512pgp
-

- Older releases can be obtained from the archives. -

- +

+ Older releases can be obtained from the archives. +

+
diff --git a/src/site/xdoc/issue-tracking.xml b/src/site/xdoc/issue-tracking.xml index 582079df6c8..18662cc829d 100644 --- a/src/site/xdoc/issue-tracking.xml +++ b/src/site/xdoc/issue-tracking.xml @@ -26,7 +26,7 @@ limitations under the License. | commons-build-plugin/trunk/src/main/resources/commons-xdoc-templates | +======================================================================+ | | - | 1) Re-generate using: mvn commons:jira-page | + | 1) Re-generate using: mvn commons-build:jira-page | | | | 2) Set the following properties in the component's pom: | | - commons.jira.id (required, alphabetic, upper case) | @@ -86,7 +86,7 @@ limitations under the License.

For more information on subversion and creating patches see the - Apache Contributors Guide. + Apache Contributors Guide.

diff --git a/src/site/xdoc/mail-lists.xml b/src/site/xdoc/mail-lists.xml index f6cb1845597..e6ca0e087eb 100644 --- a/src/site/xdoc/mail-lists.xml +++ b/src/site/xdoc/mail-lists.xml @@ -26,7 +26,7 @@ limitations under the License. | commons-build-plugin/trunk/src/main/resources/commons-xdoc-templates | +======================================================================+ | | - | 1) Re-generate using: mvn commons:mail-page | + | 1) Re-generate using: mvn commons-build:mail-page | | | | 2) Set the following properties in the component's pom: | | - commons.componentid (required, alphabetic, lower case) | @@ -54,7 +54,7 @@ limitations under the License. the convention in Commons is to prefix the subject line of messages with the component's name, for example:

    -
  • [lang3] Problem with the ...
  • +
  • [lang] Problem with the ...

@@ -79,7 +79,7 @@ limitations under the License.

Please prefix the subject line of any messages for Apache Commons Lang - with [lang3] - thanks! + with [lang] - thanks!

@@ -104,11 +104,11 @@ limitations under the License. Subscribe Unsubscribe - Post + Post mail-archives.apache.org - markmail.org
- www.mail-archive.com
- news.gmane.org + markmail.org
+ www.mail-archive.com
+ news.gmane.org @@ -122,11 +122,11 @@ limitations under the License. Subscribe Unsubscribe - Post + Post mail-archives.apache.org - markmail.org
- www.mail-archive.com
- news.gmane.org + markmail.org
+ www.mail-archive.com
+ news.gmane.org @@ -142,8 +142,8 @@ limitations under the License. Unsubscribe read only mail-archives.apache.org - markmail.org
- www.mail-archive.com + markmail.org
+ www.mail-archive.com @@ -159,8 +159,8 @@ limitations under the License. Unsubscribe read only mail-archives.apache.org - markmail.org
- www.mail-archive.com + markmail.org
+ www.mail-archive.com @@ -192,10 +192,10 @@ limitations under the License. Unsubscribe read only mail-archives.apache.org - markmail.org
- old.nabble.com
- www.mail-archive.com
- news.gmane.org + markmail.org
+ old.nabble.com
+ www.mail-archive.com
+ news.gmane.org diff --git a/src/site/xdoc/release-history.xml b/src/site/xdoc/release-history.xml index e72dd4b4c9d..0fd2de16041 100644 --- a/src/site/xdoc/release-history.xml +++ b/src/site/xdoc/release-history.xml @@ -31,6 +31,9 @@ limitations under the License. VersionRelease dateRequired Java VersionJavadocRelease notes + + 3.102020-03-228api-3.10release notes for 3.10 + 3.92019-04-098api-3.9release notes for 3.9 From e0b474c0d015f89a52c4cf8866fa157dd89e7d1c Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Mon, 23 Mar 2020 09:14:11 -0400 Subject: [PATCH 0053/3230] Update POM version numbers for Apache Commons Lang release 3.10 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 6a569928be3..99a6a791e77 100644 --- a/pom.xml +++ b/pom.xml @@ -26,7 +26,7 @@ 4.0.0 commons-lang3 - 3.10-SNAPSHOT + 3.10 Apache Commons Lang 2001 From 7a9c09161de76a436942473134d0c28323d58e24 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sat, 28 Mar 2020 10:02:28 -0400 Subject: [PATCH 0054/3230] Bump to next development version --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 99a6a791e77..68932c0916a 100644 --- a/pom.xml +++ b/pom.xml @@ -26,7 +26,7 @@ 4.0.0 commons-lang3 - 3.10 + 3.10.1-SNAPSHOT Apache Commons Lang 2001 From 8c1153d371d4498677605b847f8bfb0e0e743fd5 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sat, 28 Mar 2020 10:17:10 -0400 Subject: [PATCH 0055/3230] Add download page link. --- RELEASE-NOTES.txt | 2 ++ src/changes/release-notes.vm | 7 ++++++- src/site/resources/release-notes/RELEASE-NOTES-3.10.txt | 8 +++++--- 3 files changed, 13 insertions(+), 4 deletions(-) diff --git a/RELEASE-NOTES.txt b/RELEASE-NOTES.txt index 88bc7eb9010..13792540986 100644 --- a/RELEASE-NOTES.txt +++ b/RELEASE-NOTES.txt @@ -101,6 +101,8 @@ patches, or suggestions for improvement, see the Apache Apache Commons Lang webs https://commons.apache.org/proper/commons-lang/ +Download page: https://commons.apache.org/proper/commons-lang/download_lang.cgi + ============================================================================= Apache Commons Lang diff --git a/src/changes/release-notes.vm b/src/changes/release-notes.vm index 7b41e94899d..42349082977 100644 --- a/src/changes/release-notes.vm +++ b/src/changes/release-notes.vm @@ -136,4 +136,9 @@ Historical list of changes: ${project.url}changes-report.html For complete information on ${project.name}, including instructions on how to submit bug reports, patches, or suggestions for improvement, see the Apache ${project.name} website: -${project.url} \ No newline at end of file +${project.url} + +Download page: ${project.url}download_csv.cgi + +Have fun! +-Apache Commons Team diff --git a/src/site/resources/release-notes/RELEASE-NOTES-3.10.txt b/src/site/resources/release-notes/RELEASE-NOTES-3.10.txt index 04e4e067ceb..ba8b6bf5ef4 100644 --- a/src/site/resources/release-notes/RELEASE-NOTES-3.10.txt +++ b/src/site/resources/release-notes/RELEASE-NOTES-3.10.txt @@ -16,13 +16,13 @@ limitations under the License. Apache Commons Lang - Version 3.10-SNAPSHOT + Version 3.10 Release Notes INTRODUCTION: -This document contains the release notes for the 3.10-SNAPSHOT version of Apache Commons Lang. +This document contains the release notes for the 3.10 version of Apache Commons Lang. Commons Lang is a set of utility functions and reusable components that should be of use in any Java environment. @@ -116,4 +116,6 @@ Historical list of changes: https://commons.apache.org/proper/commons-lang/chang For complete information on Apache Commons Lang, including instructions on how to submit bug reports, patches, or suggestions for improvement, see the Apache Apache Commons Lang website: -https://commons.apache.org/proper/commons-lang/ \ No newline at end of file +https://commons.apache.org/proper/commons-lang/ + +Download page: https://commons.apache.org/proper/commons-lang/download_lang.cgi From 36c4cc67a17b51256096f0a33427071b3cc1194e Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sun, 29 Mar 2020 17:30:29 -0400 Subject: [PATCH 0056/3230] Lambdas. --- .../org/apache/commons/lang3/ArrayUtils.java | 2 +- .../org/apache/commons/lang3/Streams.java | 4 ++-- .../apache/commons/lang3/FunctionsTest.java | 14 +++++------- .../org/apache/commons/lang3/StreamsTest.java | 22 +++++++++---------- .../commons/lang3/math/IEEE754rUtilsTest.java | 6 ++--- .../commons/lang3/math/NumberUtilsTest.java | 22 +++++++++---------- 6 files changed, 34 insertions(+), 36 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/ArrayUtils.java b/src/main/java/org/apache/commons/lang3/ArrayUtils.java index 7f369fa3c91..010d8c11162 100644 --- a/src/main/java/org/apache/commons/lang3/ArrayUtils.java +++ b/src/main/java/org/apache/commons/lang3/ArrayUtils.java @@ -3663,7 +3663,7 @@ public static boolean isSorted(final short[] array) { * @since 3.4 */ public static > boolean isSorted(final T[] array) { - return isSorted(array, (o1, o2) -> o1.compareTo(o2)); + return isSorted(array, Comparable::compareTo); } /** diff --git a/src/main/java/org/apache/commons/lang3/Streams.java b/src/main/java/org/apache/commons/lang3/Streams.java index b5e7d43128b..337a0fd79c9 100644 --- a/src/main/java/org/apache/commons/lang3/Streams.java +++ b/src/main/java/org/apache/commons/lang3/Streams.java @@ -445,7 +445,7 @@ public ArrayCollector(final Class elementType) { @Override public Supplier> supplier() { - return () -> new ArrayList<>(); + return ArrayList::new; } @Override @@ -465,7 +465,7 @@ public BinaryOperator> combiner() { @Override public Function, O[]> finisher() { - return (list) -> { + return list -> { @SuppressWarnings("unchecked") final O[] array = (O[]) Array.newInstance(elementType, list.size()); return list.toArray(array); diff --git a/src/test/java/org/apache/commons/lang3/FunctionsTest.java b/src/test/java/org/apache/commons/lang3/FunctionsTest.java index bec8a44b3cb..50c3e184772 100644 --- a/src/test/java/org/apache/commons/lang3/FunctionsTest.java +++ b/src/test/java/org/apache/commons/lang3/FunctionsTest.java @@ -152,7 +152,7 @@ void testRunnable() { @Test void testAsRunnable() { FailureOnOddInvocations.invocation = 0; - final Runnable runnable = Functions.asRunnable(() -> new FailureOnOddInvocations()); + final Runnable runnable = Functions.asRunnable(FailureOnOddInvocations::new); final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, () -> runnable.run()); final Throwable cause = e.getCause(); assertNotNull(cause); @@ -178,9 +178,7 @@ void testCallable() { @Test void testAsCallable() { FailureOnOddInvocations.invocation = 0; - final FailableCallable failableCallable = () -> { - return new FailureOnOddInvocations(); - }; + final FailableCallable failableCallable = () -> new FailureOnOddInvocations(); final Callable callable = Functions.asCallable(failableCallable); final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, () -> callable.call()); final Throwable cause = e.getCause(); @@ -223,7 +221,7 @@ void testAcceptConsumer() { void testAsConsumer() { final IllegalStateException ise = new IllegalStateException(); final Testable testable = new Testable(ise); - final Consumer consumer = Functions.asConsumer((t) -> t.test()); + final Consumer consumer = Functions.asConsumer(t -> t.test()); Throwable e = assertThrows(IllegalStateException.class, () -> consumer.accept(testable)); assertSame(ise, e); @@ -319,7 +317,7 @@ public void testApplyFunction() { public void testAsFunction() { final IllegalStateException ise = new IllegalStateException(); final Testable testable = new Testable(ise); - final FailableFunction failableFunction = (th) -> { + final FailableFunction failableFunction = th -> { testable.setThrowable(th); return Integer.valueOf(testable.testInt()); }; @@ -407,7 +405,7 @@ public void testGetFromSupplier() { @DisplayName("Test that asPredicate(FailablePredicate) is converted to -> Predicate ") public void testAsPredicate() { FailureOnOddInvocations.invocation = 0; - final Functions.FailablePredicate failablePredicate = (t) -> FailureOnOddInvocations.failingBool(); + final Functions.FailablePredicate failablePredicate = t -> FailureOnOddInvocations.failingBool(); final Predicate predicate = Functions.asPredicate(failablePredicate); final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, () -> predicate.test(null)); final Throwable cause = e.getCause(); @@ -436,7 +434,7 @@ public void testAsBiPredicate() { @Test public void testAsSupplier() { FailureOnOddInvocations.invocation = 0; - final FailableSupplier failableSupplier = () -> new FailureOnOddInvocations(); + final FailableSupplier failableSupplier = FailureOnOddInvocations::new; final Supplier supplier = Functions.asSupplier(failableSupplier); final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, () -> supplier.get()); final Throwable cause = e.getCause(); diff --git a/src/test/java/org/apache/commons/lang3/StreamsTest.java b/src/test/java/org/apache/commons/lang3/StreamsTest.java index 48f7818a8ba..0f618b63463 100644 --- a/src/test/java/org/apache/commons/lang3/StreamsTest.java +++ b/src/test/java/org/apache/commons/lang3/StreamsTest.java @@ -36,7 +36,7 @@ class StreamsTest { @Test void testSimpleStreamMap() { final List input = Arrays.asList("1", "2", "3", "4", "5", "6"); - final List output = Functions.stream(input).map((s) -> Integer.valueOf(s)).collect(Collectors.toList()); + final List output = Functions.stream(input).map(s -> Integer.valueOf(s)).collect(Collectors.toList()); assertEquals(6, output.size()); for (int i = 0; i < 6; i++) { assertEquals(i+1, output.get(i).intValue()); @@ -47,7 +47,7 @@ void testSimpleStreamMap() { void testSimpleStreamMapFailing() { final List input = Arrays.asList("1", "2", "3", "4 ", "5", "6"); try { - Functions.stream(input).map((s) -> Integer.valueOf(s)).collect(Collectors.toList()); + Functions.stream(input).map(s -> Integer.valueOf(s)).collect(Collectors.toList()); fail("Expected Exception"); } catch (final NumberFormatException nfe) { assertEquals("For input string: \"4 \"", nfe.getMessage()); @@ -58,7 +58,7 @@ void testSimpleStreamMapFailing() { void testSimpleStreamForEach() { final List input = Arrays.asList("1", "2", "3", "4", "5", "6"); final List output = new ArrayList<>(); - Functions.stream(input).forEach((s) -> output.add(Integer.valueOf(s))); + Functions.stream(input).forEach(s -> output.add(Integer.valueOf(s))); assertEquals(6, output.size()); for (int i = 0; i < 6; i++) { assertEquals(i+1, output.get(i).intValue()); @@ -76,7 +76,7 @@ void testToArray() { } protected FailableConsumer asIntConsumer(final T pThrowable) { - return (s) -> { + return s -> { final Integer i = Integer.valueOf(s); if (i.intValue() == 4) { throw pThrowable; @@ -117,8 +117,8 @@ void testSimpleStreamForEachFailing() { void testSimpleStreamFilter() { final List input = Arrays.asList("1", "2", "3", "4", "5", "6"); final List output = Functions.stream(input) - .map((s) -> Integer.valueOf(s)) - .filter((i) -> { + .map(s -> Integer.valueOf(s)) + .filter(i -> { return i.intValue() %2 == 0; }) .collect(Collectors.toList()); @@ -133,7 +133,7 @@ private void assertEvenNumbers(final List output) { } protected FailablePredicate asIntPredicate(final T pThrowable) { - return (i) -> { + return i -> { if (i.intValue() == 5) { if (pThrowable != null) { throw pThrowable; @@ -147,7 +147,7 @@ protected FailablePredicate asIntPredicate(fin void testSimpleStreamFilterFailing() { final List input = Arrays.asList("1", "2", "3", "4", "5", "6"); final List output = Functions.stream(input) - .map((s) -> Integer.valueOf(s)) + .map(s -> Integer.valueOf(s)) .filter(asIntPredicate(null)) .collect(Collectors.toList()); assertEvenNumbers(output); @@ -156,7 +156,7 @@ void testSimpleStreamFilterFailing() { final IllegalArgumentException iae = new IllegalArgumentException("Invalid argument: " + 5); try { Functions.stream(input) - .map((s) -> Integer.valueOf(s)) + .map(s -> Integer.valueOf(s)) .filter(asIntPredicate(iae)) .collect(Collectors.toList()); fail("Expected Exception"); @@ -168,7 +168,7 @@ void testSimpleStreamFilterFailing() { final OutOfMemoryError oome = new OutOfMemoryError(); try { Functions.stream(input) - .map((s) -> Integer.valueOf(s)) + .map(s -> Integer.valueOf(s)) .filter(asIntPredicate(oome)) .collect(Collectors.toList()); fail("Expected Exception"); @@ -180,7 +180,7 @@ void testSimpleStreamFilterFailing() { final SAXException se = new SAXException(); try { Functions.stream(input) - .map((s) -> Integer.valueOf(s)) + .map(s -> Integer.valueOf(s)) .filter(asIntPredicate(se)) .collect(Collectors.toList()); fail("Expected Exception"); diff --git a/src/test/java/org/apache/commons/lang3/math/IEEE754rUtilsTest.java b/src/test/java/org/apache/commons/lang3/math/IEEE754rUtilsTest.java index 39fe5cd6fa3..8312f03bcbf 100644 --- a/src/test/java/org/apache/commons/lang3/math/IEEE754rUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/math/IEEE754rUtilsTest.java @@ -62,7 +62,7 @@ public void testEnforceExceptions() { assertThrows( IllegalArgumentException.class, - () -> IEEE754rUtils.min(), + IEEE754rUtils::min, "IllegalArgumentException expected for empty input"); assertThrows( @@ -82,7 +82,7 @@ public void testEnforceExceptions() { assertThrows( IllegalArgumentException.class, - () -> IEEE754rUtils.min(), + IEEE754rUtils::min, "IllegalArgumentException expected for empty input"); assertThrows( @@ -92,7 +92,7 @@ public void testEnforceExceptions() { assertThrows( IllegalArgumentException.class, - () -> IEEE754rUtils.max(), + IEEE754rUtils::max, "IllegalArgumentException expected for empty input"); } diff --git a/src/test/java/org/apache/commons/lang3/math/NumberUtilsTest.java b/src/test/java/org/apache/commons/lang3/math/NumberUtilsTest.java index 3e32c90515f..922120be42a 100644 --- a/src/test/java/org/apache/commons/lang3/math/NumberUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/math/NumberUtilsTest.java @@ -691,7 +691,7 @@ public void testMinLong_nullArray() { @Test public void testMinLong_emptyArray() { - assertThrows(IllegalArgumentException.class, () -> NumberUtils.min()); + assertThrows(IllegalArgumentException.class, NumberUtils::min); } @Test @@ -710,7 +710,7 @@ public void testMinInt_nullArray() { @Test public void testMinInt_emptyArray() { - assertThrows(IllegalArgumentException.class, () -> NumberUtils.min()); + assertThrows(IllegalArgumentException.class, NumberUtils::min); } @Test @@ -729,7 +729,7 @@ public void testMinShort_nullArray() { @Test public void testMinShort_emptyArray() { - assertThrows(IllegalArgumentException.class, () -> NumberUtils.min()); + assertThrows(IllegalArgumentException.class, NumberUtils::min); } @Test @@ -767,7 +767,7 @@ public void testMinDouble_nullArray() { @Test public void testMinDouble_emptyArray() { - assertThrows(IllegalArgumentException.class, () -> NumberUtils.min()); + assertThrows(IllegalArgumentException.class, NumberUtils::min); } @Test @@ -786,7 +786,7 @@ public void testMinFloat_nullArray() { @Test public void testMinFloat_emptyArray() { - assertThrows(IllegalArgumentException.class, () -> NumberUtils.min()); + assertThrows(IllegalArgumentException.class, NumberUtils::min); } @Test @@ -805,7 +805,7 @@ public void testMaxLong_nullArray() { @Test public void testMaxLong_emptyArray() { - assertThrows(IllegalArgumentException.class, () -> NumberUtils.max()); + assertThrows(IllegalArgumentException.class, NumberUtils::max); } @Test @@ -824,7 +824,7 @@ public void testMaxInt_nullArray() { @Test public void testMaxInt_emptyArray() { - assertThrows(IllegalArgumentException.class, () -> NumberUtils.max()); + assertThrows(IllegalArgumentException.class, NumberUtils::max); } @Test @@ -843,7 +843,7 @@ public void testMaxShort_nullArray() { @Test public void testMaxShort_emptyArray() { - assertThrows(IllegalArgumentException.class, () -> NumberUtils.max()); + assertThrows(IllegalArgumentException.class, NumberUtils::max); } @Test @@ -881,7 +881,7 @@ public void testMaxDouble_nullArray() { @Test public void testMaxDouble_emptyArray() { - assertThrows(IllegalArgumentException.class, () -> NumberUtils.max()); + assertThrows(IllegalArgumentException.class, NumberUtils::max); } @Test @@ -892,7 +892,7 @@ public void testMaxDouble() { assertThrows( IllegalArgumentException.class, - () -> NumberUtils.max(), + NumberUtils::max, "No exception was thrown for empty input."); assertEquals(5.1f, NumberUtils.max(5.1f), "max(double[]) failed for array length 1"); @@ -909,7 +909,7 @@ public void testMaxFloat_nullArray() { @Test public void testMaxFloat_emptyArray() { - assertThrows(IllegalArgumentException.class, () -> NumberUtils.max()); + assertThrows(IllegalArgumentException.class, NumberUtils::max); } @Test From 9747b14469aa88714bc979cab24e1ffda663aa78 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Mon, 30 Mar 2020 15:03:29 -0400 Subject: [PATCH 0057/3230] Standardize on American English spelling of 'behavior'. --- RELEASE-NOTES.txt | 4 ++-- src/changes/changes.xml | 4 ++-- .../org/apache/commons/lang3/ArrayUtils.java | 2 +- .../apache/commons/lang3/BooleanUtils.java | 2 +- .../apache/commons/lang3/CharSetUtils.java | 2 +- .../org/apache/commons/lang3/CharUtils.java | 2 +- .../org/apache/commons/lang3/ClassUtils.java | 2 +- .../org/apache/commons/lang3/LocaleUtils.java | 4 ++-- .../org/apache/commons/lang3/ObjectUtils.java | 2 +- .../commons/lang3/SerializationUtils.java | 2 +- .../apache/commons/lang3/text/StrBuilder.java | 22 +++++++++---------- .../apache/commons/lang3/text/WordUtils.java | 2 +- .../translate/NumericEntityUnescaper.java | 2 +- .../commons/lang3/tuple/ImmutablePair.java | 2 +- .../commons/lang3/tuple/ImmutableTriple.java | 2 +- .../release-notes/RELEASE-NOTES-2.1.txt | 4 ++-- .../release-notes/RELEASE-NOTES-2.2.txt | 2 +- .../release-notes/RELEASE-NOTES-2.3.txt | 2 +- .../release-notes/RELEASE-NOTES-2.4.txt | 2 +- .../release-notes/RELEASE-NOTES-3.2.1.txt | 2 +- .../release-notes/RELEASE-NOTES-3.2.txt | 2 +- .../release-notes/RELEASE-NOTES-3.3.1.txt | 2 +- .../release-notes/RELEASE-NOTES-3.3.2.txt | 2 +- .../release-notes/RELEASE-NOTES-3.3.txt | 2 +- .../release-notes/RELEASE-NOTES-3.4.txt | 2 +- .../release-notes/RELEASE-NOTES-3.5.txt | 2 +- .../release-notes/RELEASE-NOTES-3.6.txt | 4 ++-- .../release-notes/RELEASE-NOTES-3.7.txt | 4 ++-- .../release-notes/RELEASE-NOTES-3.8.1.txt | 4 ++-- .../release-notes/RELEASE-NOTES-3.8.txt | 4 ++-- .../release-notes/RELEASE-NOTES-3.9.txt | 4 ++-- src/site/xdoc/article3_0.xml | 2 +- src/site/xdoc/upgradeto2_1.xml | 4 ++-- src/site/xdoc/upgradeto2_3.xml | 2 +- src/site/xdoc/upgradeto2_4.xml | 2 +- .../commons/lang3/StringEscapeUtilsTest.java | 4 ++-- 36 files changed, 57 insertions(+), 57 deletions(-) diff --git a/RELEASE-NOTES.txt b/RELEASE-NOTES.txt index 13792540986..33771d08b4c 100644 --- a/RELEASE-NOTES.txt +++ b/RELEASE-NOTES.txt @@ -418,7 +418,7 @@ o LANG-1319: MultilineRecursiveToStringStyle StackOverflowError when object is an array. o LANG-1320: LocaleUtils#toLocale does not support language followed by UN M.49 numeric-3 area code followed by variant. -o LANG-1300: Clarify or improve behaviour of int-based indexOf methods in +o LANG-1300: Clarify or improve behavior of int-based indexOf methods in StringUtils. Thanks to Mark Dacek. o LANG-1286: RandomStringUtils random method can overflow and return characters outside of specified range. @@ -1128,7 +1128,7 @@ o LANG-831: FastDateParser does not handle white-space properly. o LANG-830: FastDateParser could use \Q \E to quote regexes. o LANG-828: FastDateParser does not handle non-Gregorian calendars properly. o LANG-826: FastDateParser does not handle non-ASCII digits correctly. -o LANG-822: NumberUtils#createNumber - bad behaviour for leading "--". +o LANG-822: NumberUtils#createNumber - bad behavior for leading "--". o LANG-818: FastDateFormat's "z" pattern does not respect timezone of Calendar instances passed to format(). o LANG-817: Add org.apache.commons.lang3.SystemUtils.IS_OS_WINDOWS_8. diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 86afaaabcff..f79d5c49b4b 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -189,7 +189,7 @@ The type attribute can be add,update,fix,remove. Add JMH maven dependencies Add null filter to ReflectionToStringBuilder LocaleUtils#toLocale does not support language followed by UN M.49 numeric-3 area code followed by variant - Clarify or improve behaviour of int-based indexOf methods in StringUtils + Clarify or improve behavior of int-based indexOf methods in StringUtils Add method for converting string to an array of code points RandomStringUtils random method can overflow and return characters outside of specified range Add methods to insert arrays into arrays at an index @@ -523,7 +523,7 @@ The type attribute can be add,update,fix,remove. FastDateParser does not handle non-Gregorian calendars properly FastDateParser does not handle non-ASCII digits correctly Create StrBuilder APIs similar to String.format(String, Object...) - NumberUtils#createNumber - bad behaviour for leading "--" + NumberUtils#createNumber - bad behavior for leading "--" FastDateFormat's "z" pattern does not respect timezone of Calendar instances passed to format() Add org.apache.commons.lang3.SystemUtils.IS_OS_WINDOWS_8 StringUtils.equalsIgnoreCase doesn't check string reference equality diff --git a/src/main/java/org/apache/commons/lang3/ArrayUtils.java b/src/main/java/org/apache/commons/lang3/ArrayUtils.java index 010d8c11162..320fba6d38d 100644 --- a/src/main/java/org/apache/commons/lang3/ArrayUtils.java +++ b/src/main/java/org/apache/commons/lang3/ArrayUtils.java @@ -41,7 +41,7 @@ *

This class tries to handle {@code null} input gracefully. * An exception will not be thrown for a {@code null} * array input. However, an Object array that contains a {@code null} - * element may throw an exception. Each method documents its behaviour. + * element may throw an exception. Each method documents its behavior. * *

#ThreadSafe# * @since 2.0 diff --git a/src/main/java/org/apache/commons/lang3/BooleanUtils.java b/src/main/java/org/apache/commons/lang3/BooleanUtils.java index 7cf3794610a..5bfcea29d68 100644 --- a/src/main/java/org/apache/commons/lang3/BooleanUtils.java +++ b/src/main/java/org/apache/commons/lang3/BooleanUtils.java @@ -23,7 +23,7 @@ * *

This class tries to handle {@code null} input gracefully. * An exception will not be thrown for a {@code null} input. - * Each method documents its behaviour in more detail.

+ * Each method documents its behavior in more detail.

* *

#ThreadSafe#

* @since 2.0 diff --git a/src/main/java/org/apache/commons/lang3/CharSetUtils.java b/src/main/java/org/apache/commons/lang3/CharSetUtils.java index b3580b7c25d..03ff899a89d 100644 --- a/src/main/java/org/apache/commons/lang3/CharSetUtils.java +++ b/src/main/java/org/apache/commons/lang3/CharSetUtils.java @@ -21,7 +21,7 @@ * *

This class handles {@code null} input gracefully. * An exception will not be thrown for a {@code null} input. - * Each method documents its behaviour in more detail.

+ * Each method documents its behavior in more detail.

* *

#ThreadSafe#

* @see CharSet diff --git a/src/main/java/org/apache/commons/lang3/CharUtils.java b/src/main/java/org/apache/commons/lang3/CharUtils.java index b872ac0f8d5..b4e8ccf7edb 100644 --- a/src/main/java/org/apache/commons/lang3/CharUtils.java +++ b/src/main/java/org/apache/commons/lang3/CharUtils.java @@ -21,7 +21,7 @@ * *

This class tries to handle {@code null} input gracefully. * An exception will not be thrown for a {@code null} input. - * Each method documents its behaviour in more detail.

+ * Each method documents its behavior in more detail.

* *

#ThreadSafe#

* @since 2.1 diff --git a/src/main/java/org/apache/commons/lang3/ClassUtils.java b/src/main/java/org/apache/commons/lang3/ClassUtils.java index d0891ddd791..a6d1d1ddbd8 100644 --- a/src/main/java/org/apache/commons/lang3/ClassUtils.java +++ b/src/main/java/org/apache/commons/lang3/ClassUtils.java @@ -34,7 +34,7 @@ *

Operates on classes without using reflection.

* *

This class handles invalid {@code null} inputs as best it can. - * Each method documents its behaviour in more detail.

+ * Each method documents its behavior in more detail.

* *

The notion of a {@code canonical name} includes the human * readable name for the type, for example {@code int[]}. The diff --git a/src/main/java/org/apache/commons/lang3/LocaleUtils.java b/src/main/java/org/apache/commons/lang3/LocaleUtils.java index 703b33613fe..3dd8cf1bfe3 100644 --- a/src/main/java/org/apache/commons/lang3/LocaleUtils.java +++ b/src/main/java/org/apache/commons/lang3/LocaleUtils.java @@ -31,7 +31,7 @@ * *

This class tries to handle {@code null} input gracefully. * An exception will not be thrown for a {@code null} input. - * Each method documents its behaviour in more detail.

+ * Each method documents its behavior in more detail.

* * @since 2.2 */ @@ -71,7 +71,7 @@ public LocaleUtils() { * LocaleUtils.toLocale("en_GB_xxx") = new Locale("en", "GB", "xxx") (#) *
* - *

(#) The behaviour of the JDK variant constructor changed between JDK1.3 and JDK1.4. + *

(#) The behavior of the JDK variant constructor changed between JDK1.3 and JDK1.4. * In JDK1.3, the constructor upper cases the variant, in JDK1.4, it doesn't. * Thus, the result from getVariant() may vary depending on your JDK.

* diff --git a/src/main/java/org/apache/commons/lang3/ObjectUtils.java b/src/main/java/org/apache/commons/lang3/ObjectUtils.java index b94c2ae74b3..940dcd808cc 100644 --- a/src/main/java/org/apache/commons/lang3/ObjectUtils.java +++ b/src/main/java/org/apache/commons/lang3/ObjectUtils.java @@ -38,7 +38,7 @@ * *

This class tries to handle {@code null} input gracefully. * An exception will generally not be thrown for a {@code null} input. - * Each method documents its behaviour in more detail.

+ * Each method documents its behavior in more detail.

* *

#ThreadSafe#

* @since 1.0 diff --git a/src/main/java/org/apache/commons/lang3/SerializationUtils.java b/src/main/java/org/apache/commons/lang3/SerializationUtils.java index 14bfc1dc7cf..5f7ed8c12bc 100644 --- a/src/main/java/org/apache/commons/lang3/SerializationUtils.java +++ b/src/main/java/org/apache/commons/lang3/SerializationUtils.java @@ -39,7 +39,7 @@ * * *

This class throws exceptions for invalid {@code null} inputs. - * Each method documents its behaviour in more detail.

+ * Each method documents its behavior in more detail.

* *

#ThreadSafe#

* @since 1.0 diff --git a/src/main/java/org/apache/commons/lang3/text/StrBuilder.java b/src/main/java/org/apache/commons/lang3/text/StrBuilder.java index 31779b474d8..21c88e42529 100644 --- a/src/main/java/org/apache/commons/lang3/text/StrBuilder.java +++ b/src/main/java/org/apache/commons/lang3/text/StrBuilder.java @@ -1894,7 +1894,7 @@ public StrBuilder deleteFirst(final String str) { /** * Deletes all parts of the builder that the matcher matches. *

- * Matchers can be used to perform advanced deletion behaviour. + * Matchers can be used to perform advanced deletion behavior. * For example you could write a matcher to delete all occurrences * where the character 'a' is followed by a number. * @@ -1908,7 +1908,7 @@ public StrBuilder deleteAll(final StrMatcher matcher) { /** * Deletes the first match within the builder using the specified matcher. *

- * Matchers can be used to perform advanced deletion behaviour. + * Matchers can be used to perform advanced deletion behavior. * For example you could write a matcher to delete * where the character 'a' is followed by a number. * @@ -2044,7 +2044,7 @@ public StrBuilder replaceFirst(final String searchStr, final String replaceStr) /** * Replaces all matches within the builder with the replace string. *

- * Matchers can be used to perform advanced replace behaviour. + * Matchers can be used to perform advanced replace behavior. * For example you could write a matcher to replace all occurrences * where the character 'a' is followed by a number. * @@ -2059,7 +2059,7 @@ public StrBuilder replaceAll(final StrMatcher matcher, final String replaceStr) /** * Replaces the first match within the builder with the replace string. *

- * Matchers can be used to perform advanced replace behaviour. + * Matchers can be used to perform advanced replace behavior. * For example you could write a matcher to replace * where the character 'a' is followed by a number. * @@ -2075,7 +2075,7 @@ public StrBuilder replaceFirst(final StrMatcher matcher, final String replaceStr /** * Advanced search and replaces within the builder using a matcher. *

- * Matchers can be used to perform advanced behaviour. + * Matchers can be used to perform advanced behavior. * For example you could write a matcher to delete all occurrences * where the character 'a' is followed by a number. * @@ -2098,7 +2098,7 @@ public StrBuilder replace( /** * Replaces within the builder using a matcher. *

- * Matchers can be used to perform advanced behaviour. + * Matchers can be used to perform advanced behavior. * For example you could write a matcher to delete all occurrences * where the character 'a' is followed by a number. * @@ -2390,7 +2390,7 @@ public boolean contains(final String str) { * Checks if the string builder contains a string matched using the * specified matcher. *

- * Matchers can be used to perform advanced searching behaviour. + * Matchers can be used to perform advanced searching behavior. * For example you could write a matcher to search for the character * 'a' followed by a number. * @@ -2487,7 +2487,7 @@ public int indexOf(final String str, int startIndex) { /** * Searches the string builder using the matcher to find the first match. *

- * Matchers can be used to perform advanced searching behaviour. + * Matchers can be used to perform advanced searching behavior. * For example you could write a matcher to find the character 'a' * followed by a number. * @@ -2502,7 +2502,7 @@ public int indexOf(final StrMatcher matcher) { * Searches the string builder using the matcher to find the first * match searching from the given index. *

- * Matchers can be used to perform advanced searching behaviour. + * Matchers can be used to perform advanced searching behavior. * For example you could write a matcher to find the character 'a' * followed by a number. * @@ -2608,7 +2608,7 @@ public int lastIndexOf(final String str, int startIndex) { /** * Searches the string builder using the matcher to find the last match. *

- * Matchers can be used to perform advanced searching behaviour. + * Matchers can be used to perform advanced searching behavior. * For example you could write a matcher to find the character 'a' * followed by a number. * @@ -2623,7 +2623,7 @@ public int lastIndexOf(final StrMatcher matcher) { * Searches the string builder using the matcher to find the last * match searching from the given index. *

- * Matchers can be used to perform advanced searching behaviour. + * Matchers can be used to perform advanced searching behavior. * For example you could write a matcher to find the character 'a' * followed by a number. * diff --git a/src/main/java/org/apache/commons/lang3/text/WordUtils.java b/src/main/java/org/apache/commons/lang3/text/WordUtils.java index aa84e7512bc..ee1249e1e7d 100644 --- a/src/main/java/org/apache/commons/lang3/text/WordUtils.java +++ b/src/main/java/org/apache/commons/lang3/text/WordUtils.java @@ -27,7 +27,7 @@ * *

This class tries to handle {@code null} input gracefully. * An exception will not be thrown for a {@code null} input. - * Each method documents its behaviour in more detail.

+ * Each method documents its behavior in more detail.

* * @since 2.0 * @deprecated as of 3.6, use commons-text diff --git a/src/main/java/org/apache/commons/lang3/text/translate/NumericEntityUnescaper.java b/src/main/java/org/apache/commons/lang3/text/translate/NumericEntityUnescaper.java index 2b7ee8ec983..b9da84a9856 100644 --- a/src/main/java/org/apache/commons/lang3/text/translate/NumericEntityUnescaper.java +++ b/src/main/java/org/apache/commons/lang3/text/translate/NumericEntityUnescaper.java @@ -54,7 +54,7 @@ public enum OPTION { * and to throw an IllegalArgumentException when they're missing: * new NumericEntityUnescaper(NumericEntityUnescaper.OPTION.errorIfNoSemiColon) * - * Note that the default behaviour is to ignore them. + * Note that the default behavior is to ignore them. * * @param options to apply to this unescaper */ diff --git a/src/main/java/org/apache/commons/lang3/tuple/ImmutablePair.java b/src/main/java/org/apache/commons/lang3/tuple/ImmutablePair.java index a9be293ce28..9c106e63034 100644 --- a/src/main/java/org/apache/commons/lang3/tuple/ImmutablePair.java +++ b/src/main/java/org/apache/commons/lang3/tuple/ImmutablePair.java @@ -24,7 +24,7 @@ *

Although the implementation is immutable, there is no restriction on the objects * that may be stored. If mutable objects are stored in the pair, then the pair * itself effectively becomes mutable. The class is also {@code final}, so a subclass - * can not add undesirable behaviour.

+ * can not add undesirable behavior.

* *

#ThreadSafe# if both paired objects are thread-safe

* diff --git a/src/main/java/org/apache/commons/lang3/tuple/ImmutableTriple.java b/src/main/java/org/apache/commons/lang3/tuple/ImmutableTriple.java index f51df4589c0..e30689e9012 100644 --- a/src/main/java/org/apache/commons/lang3/tuple/ImmutableTriple.java +++ b/src/main/java/org/apache/commons/lang3/tuple/ImmutableTriple.java @@ -22,7 +22,7 @@ *

Although the implementation is immutable, there is no restriction on the objects * that may be stored. If mutable objects are stored in the triple, then the triple * itself effectively becomes mutable. The class is also {@code final}, so a subclass - * can not add undesirable behaviour.

+ * can not add undesirable behavior.

* *

#ThreadSafe# if all three objects are thread-safe

* diff --git a/src/site/resources/release-notes/RELEASE-NOTES-2.1.txt b/src/site/resources/release-notes/RELEASE-NOTES-2.1.txt index 137c3008361..3c363258f54 100644 --- a/src/site/resources/release-notes/RELEASE-NOTES-2.1.txt +++ b/src/site/resources/release-notes/RELEASE-NOTES-2.1.txt @@ -32,7 +32,7 @@ INCOMPATIBLE CHANGES: - The Nestable interface defines the method indexOfThrowable(Class). Previously the implementations checked only for a specific Class. Now they check for subclasses of that Class as well. -For most situations this will be the expected behaviour (ie. its a bug fix). +For most situations this will be the expected behavior (ie. its a bug fix). If it causes problems, please use the ExceptionUtils.indexOfThrowable(Class) method instead. Note that the ExceptionUtils method is available in v1.0 and v2.0 of commons-lang and has not been changed. (An alternative to this is to change the public static matchSubclasses flag on NestableDelegate. @@ -98,7 +98,7 @@ indexOfThrowable method untouched (see incompatible changes section) -- method to parse a date string using multiple patterns - FastDateFormat - extra formatting methods that take in a millisecond long value -- additional static factory methods -- StopWatch - new methods for split behaviour +- StopWatch - new methods for split behavior BUG FIXES: diff --git a/src/site/resources/release-notes/RELEASE-NOTES-2.2.txt b/src/site/resources/release-notes/RELEASE-NOTES-2.2.txt index b47e0744dea..38e70171062 100644 --- a/src/site/resources/release-notes/RELEASE-NOTES-2.2.txt +++ b/src/site/resources/release-notes/RELEASE-NOTES-2.2.txt @@ -35,7 +35,7 @@ ADDITIONAL INCOMPATIBLE CHANGES WITH VERSION 2.0: - The Nestable interface defines the method indexOfThrowable(Class). Previously the implementations checked only for a specific Class. Now they check for subclasses of that Class as well. -For most situations this will be the expected behaviour (ie. its a bug fix). +For most situations this will be the expected behavior (ie. its a bug fix). If it causes problems, please use the ExceptionUtils.indexOfThrowable(Class) method instead. Note that the ExceptionUtils method is available in v1.0 and v2.0 of commons-lang and has not been changed. (An alternative to this is to change the public static matchSubclasses flag on NestableDelegate. diff --git a/src/site/resources/release-notes/RELEASE-NOTES-2.3.txt b/src/site/resources/release-notes/RELEASE-NOTES-2.3.txt index fcaaf2be1b4..f3e774eb9c7 100644 --- a/src/site/resources/release-notes/RELEASE-NOTES-2.3.txt +++ b/src/site/resources/release-notes/RELEASE-NOTES-2.3.txt @@ -37,7 +37,7 @@ ADDITIONAL INCOMPATIBLE CHANGES WITH VERSION 2.0: - The Nestable interface defines the method indexOfThrowable(Class). Previously the implementations checked only for a specific Class. Now they check for subclasses of that Class as well. -For most situations this will be the expected behaviour (ie. its a bug fix). +For most situations this will be the expected behavior (ie. its a bug fix). If it causes problems, please use the ExceptionUtils.indexOfThrowable(Class) method instead. Note that the ExceptionUtils method is available in v1.0 and v2.0 of commons-lang and has not been changed. (An alternative to this is to change the public static matchSubclasses flag on NestableDelegate. diff --git a/src/site/resources/release-notes/RELEASE-NOTES-2.4.txt b/src/site/resources/release-notes/RELEASE-NOTES-2.4.txt index a573521dd2e..a54b34143b9 100644 --- a/src/site/resources/release-notes/RELEASE-NOTES-2.4.txt +++ b/src/site/resources/release-notes/RELEASE-NOTES-2.4.txt @@ -43,7 +43,7 @@ ADDITIONAL INCOMPATIBLE CHANGES WITH VERSION 2.0: - The Nestable interface defines the method indexOfThrowable(Class). Previously the implementations checked only for a specific Class. Now they check for subclasses of that Class as well. -For most situations this will be the expected behaviour (ie. its a bug fix). +For most situations this will be the expected behavior (ie. its a bug fix). If it causes problems, please use the ExceptionUtils.indexOfThrowable(Class) method instead. Note that the ExceptionUtils method is available in v1.0 and v2.0 of commons-lang and has not been changed. (An alternative to this is to change the public static matchSubclasses flag on NestableDelegate. diff --git a/src/site/resources/release-notes/RELEASE-NOTES-3.2.1.txt b/src/site/resources/release-notes/RELEASE-NOTES-3.2.1.txt index e02008aac77..3cfdb836612 100644 --- a/src/site/resources/release-notes/RELEASE-NOTES-3.2.1.txt +++ b/src/site/resources/release-notes/RELEASE-NOTES-3.2.1.txt @@ -147,7 +147,7 @@ o LANG-831: FastDateParser does not handle white-space properly. o LANG-830: FastDateParser could use \Q \E to quote regexes. o LANG-828: FastDateParser does not handle non-Gregorian calendars properly. o LANG-826: FastDateParser does not handle non-ASCII digits correctly. -o LANG-822: NumberUtils#createNumber - bad behaviour for leading "--". +o LANG-822: NumberUtils#createNumber - bad behavior for leading "--". o LANG-818: FastDateFormat's "z" pattern does not respect timezone of Calendar instances passed to format(). o LANG-817: Add org.apache.commons.lang3.SystemUtils.IS_OS_WINDOWS_8. diff --git a/src/site/resources/release-notes/RELEASE-NOTES-3.2.txt b/src/site/resources/release-notes/RELEASE-NOTES-3.2.txt index 29cc42a6752..c19d4c2df12 100644 --- a/src/site/resources/release-notes/RELEASE-NOTES-3.2.txt +++ b/src/site/resources/release-notes/RELEASE-NOTES-3.2.txt @@ -135,7 +135,7 @@ o LANG-831: FastDateParser does not handle white-space properly. o LANG-830: FastDateParser could use \Q \E to quote regexes. o LANG-828: FastDateParser does not handle non-Gregorian calendars properly. o LANG-826: FastDateParser does not handle non-ASCII digits correctly. -o LANG-822: NumberUtils#createNumber - bad behaviour for leading "--". +o LANG-822: NumberUtils#createNumber - bad behavior for leading "--". o LANG-818: FastDateFormat's "z" pattern does not respect timezone of Calendar instances passed to format(). o LANG-817: Add org.apache.commons.lang3.SystemUtils.IS_OS_WINDOWS_8. diff --git a/src/site/resources/release-notes/RELEASE-NOTES-3.3.1.txt b/src/site/resources/release-notes/RELEASE-NOTES-3.3.1.txt index 43a0679dba0..20d195a69ac 100644 --- a/src/site/resources/release-notes/RELEASE-NOTES-3.3.1.txt +++ b/src/site/resources/release-notes/RELEASE-NOTES-3.3.1.txt @@ -226,7 +226,7 @@ o LANG-831: FastDateParser does not handle white-space properly. o LANG-830: FastDateParser could use \Q \E to quote regexes. o LANG-828: FastDateParser does not handle non-Gregorian calendars properly. o LANG-826: FastDateParser does not handle non-ASCII digits correctly. -o LANG-822: NumberUtils#createNumber - bad behaviour for leading "--". +o LANG-822: NumberUtils#createNumber - bad behavior for leading "--". o LANG-818: FastDateFormat's "z" pattern does not respect timezone of Calendar instances passed to format(). o LANG-817: Add org.apache.commons.lang3.SystemUtils.IS_OS_WINDOWS_8. diff --git a/src/site/resources/release-notes/RELEASE-NOTES-3.3.2.txt b/src/site/resources/release-notes/RELEASE-NOTES-3.3.2.txt index d4e1a4621fb..364f20f2a37 100644 --- a/src/site/resources/release-notes/RELEASE-NOTES-3.3.2.txt +++ b/src/site/resources/release-notes/RELEASE-NOTES-3.3.2.txt @@ -239,7 +239,7 @@ o LANG-831: FastDateParser does not handle white-space properly. o LANG-830: FastDateParser could use \Q \E to quote regexes. o LANG-828: FastDateParser does not handle non-Gregorian calendars properly. o LANG-826: FastDateParser does not handle non-ASCII digits correctly. -o LANG-822: NumberUtils#createNumber - bad behaviour for leading "--". +o LANG-822: NumberUtils#createNumber - bad behavior for leading "--". o LANG-818: FastDateFormat's "z" pattern does not respect timezone of Calendar instances passed to format(). o LANG-817: Add org.apache.commons.lang3.SystemUtils.IS_OS_WINDOWS_8. diff --git a/src/site/resources/release-notes/RELEASE-NOTES-3.3.txt b/src/site/resources/release-notes/RELEASE-NOTES-3.3.txt index b810ddf57e1..69d30764c2b 100644 --- a/src/site/resources/release-notes/RELEASE-NOTES-3.3.txt +++ b/src/site/resources/release-notes/RELEASE-NOTES-3.3.txt @@ -212,7 +212,7 @@ o LANG-831: FastDateParser does not handle white-space properly. o LANG-830: FastDateParser could use \Q \E to quote regexes. o LANG-828: FastDateParser does not handle non-Gregorian calendars properly. o LANG-826: FastDateParser does not handle non-ASCII digits correctly. -o LANG-822: NumberUtils#createNumber - bad behaviour for leading "--". +o LANG-822: NumberUtils#createNumber - bad behavior for leading "--". o LANG-818: FastDateFormat's "z" pattern does not respect timezone of Calendar instances passed to format(). o LANG-817: Add org.apache.commons.lang3.SystemUtils.IS_OS_WINDOWS_8. diff --git a/src/site/resources/release-notes/RELEASE-NOTES-3.4.txt b/src/site/resources/release-notes/RELEASE-NOTES-3.4.txt index 7d477943340..43b059e2907 100644 --- a/src/site/resources/release-notes/RELEASE-NOTES-3.4.txt +++ b/src/site/resources/release-notes/RELEASE-NOTES-3.4.txt @@ -372,7 +372,7 @@ o LANG-831: FastDateParser does not handle white-space properly. o LANG-830: FastDateParser could use \Q \E to quote regexes. o LANG-828: FastDateParser does not handle non-Gregorian calendars properly. o LANG-826: FastDateParser does not handle non-ASCII digits correctly. -o LANG-822: NumberUtils#createNumber - bad behaviour for leading "--". +o LANG-822: NumberUtils#createNumber - bad behavior for leading "--". o LANG-818: FastDateFormat's "z" pattern does not respect timezone of Calendar instances passed to format(). o LANG-817: Add org.apache.commons.lang3.SystemUtils.IS_OS_WINDOWS_8. diff --git a/src/site/resources/release-notes/RELEASE-NOTES-3.5.txt b/src/site/resources/release-notes/RELEASE-NOTES-3.5.txt index af36b2bf954..fd14babeb46 100644 --- a/src/site/resources/release-notes/RELEASE-NOTES-3.5.txt +++ b/src/site/resources/release-notes/RELEASE-NOTES-3.5.txt @@ -668,7 +668,7 @@ o LANG-831: FastDateParser does not handle white-space properly. o LANG-830: FastDateParser could use \Q \E to quote regexes. o LANG-828: FastDateParser does not handle non-Gregorian calendars properly. o LANG-826: FastDateParser does not handle non-ASCII digits correctly. -o LANG-822: NumberUtils#createNumber - bad behaviour for leading "--". +o LANG-822: NumberUtils#createNumber - bad behavior for leading "--". o LANG-818: FastDateFormat's "z" pattern does not respect timezone of Calendar instances passed to format(). o LANG-817: Add org.apache.commons.lang3.SystemUtils.IS_OS_WINDOWS_8. diff --git a/src/site/resources/release-notes/RELEASE-NOTES-3.6.txt b/src/site/resources/release-notes/RELEASE-NOTES-3.6.txt index 3cff9206de8..87a738bfc06 100644 --- a/src/site/resources/release-notes/RELEASE-NOTES-3.6.txt +++ b/src/site/resources/release-notes/RELEASE-NOTES-3.6.txt @@ -142,7 +142,7 @@ o LANG-1319: MultilineRecursiveToStringStyle StackOverflowError when object is an array. o LANG-1320: LocaleUtils#toLocale does not support language followed by UN M.49 numeric-3 area code followed by variant. -o LANG-1300: Clarify or improve behaviour of int-based indexOf methods in +o LANG-1300: Clarify or improve behavior of int-based indexOf methods in StringUtils. Thanks to Mark Dacek. o LANG-1286: RandomStringUtils random method can overflow and return characters outside of specified range. @@ -852,7 +852,7 @@ o LANG-831: FastDateParser does not handle white-space properly. o LANG-830: FastDateParser could use \Q \E to quote regexes. o LANG-828: FastDateParser does not handle non-Gregorian calendars properly. o LANG-826: FastDateParser does not handle non-ASCII digits correctly. -o LANG-822: NumberUtils#createNumber - bad behaviour for leading "--". +o LANG-822: NumberUtils#createNumber - bad behavior for leading "--". o LANG-818: FastDateFormat's "z" pattern does not respect timezone of Calendar instances passed to format(). o LANG-817: Add org.apache.commons.lang3.SystemUtils.IS_OS_WINDOWS_8. diff --git a/src/site/resources/release-notes/RELEASE-NOTES-3.7.txt b/src/site/resources/release-notes/RELEASE-NOTES-3.7.txt index d83e0eeffbc..5746fb5adaa 100644 --- a/src/site/resources/release-notes/RELEASE-NOTES-3.7.txt +++ b/src/site/resources/release-notes/RELEASE-NOTES-3.7.txt @@ -194,7 +194,7 @@ o LANG-1319: MultilineRecursiveToStringStyle StackOverflowError when object is an array. o LANG-1320: LocaleUtils#toLocale does not support language followed by UN M.49 numeric-3 area code followed by variant. -o LANG-1300: Clarify or improve behaviour of int-based indexOf methods in +o LANG-1300: Clarify or improve behavior of int-based indexOf methods in StringUtils. Thanks to Mark Dacek. o LANG-1286: RandomStringUtils random method can overflow and return characters outside of specified range. @@ -904,7 +904,7 @@ o LANG-831: FastDateParser does not handle white-space properly. o LANG-830: FastDateParser could use \Q \E to quote regexes. o LANG-828: FastDateParser does not handle non-Gregorian calendars properly. o LANG-826: FastDateParser does not handle non-ASCII digits correctly. -o LANG-822: NumberUtils#createNumber - bad behaviour for leading "--". +o LANG-822: NumberUtils#createNumber - bad behavior for leading "--". o LANG-818: FastDateFormat's "z" pattern does not respect timezone of Calendar instances passed to format(). o LANG-817: Add org.apache.commons.lang3.SystemUtils.IS_OS_WINDOWS_8. diff --git a/src/site/resources/release-notes/RELEASE-NOTES-3.8.1.txt b/src/site/resources/release-notes/RELEASE-NOTES-3.8.1.txt index fc2a18604db..5664a867844 100644 --- a/src/site/resources/release-notes/RELEASE-NOTES-3.8.1.txt +++ b/src/site/resources/release-notes/RELEASE-NOTES-3.8.1.txt @@ -288,7 +288,7 @@ o LANG-1319: MultilineRecursiveToStringStyle StackOverflowError when object is an array. o LANG-1320: LocaleUtils#toLocale does not support language followed by UN M.49 numeric-3 area code followed by variant. -o LANG-1300: Clarify or improve behaviour of int-based indexOf methods in +o LANG-1300: Clarify or improve behavior of int-based indexOf methods in StringUtils. Thanks to Mark Dacek. o LANG-1286: RandomStringUtils random method can overflow and return characters outside of specified range. @@ -998,7 +998,7 @@ o LANG-831: FastDateParser does not handle white-space properly. o LANG-830: FastDateParser could use \Q \E to quote regexes. o LANG-828: FastDateParser does not handle non-Gregorian calendars properly. o LANG-826: FastDateParser does not handle non-ASCII digits correctly. -o LANG-822: NumberUtils#createNumber - bad behaviour for leading "--". +o LANG-822: NumberUtils#createNumber - bad behavior for leading "--". o LANG-818: FastDateFormat's "z" pattern does not respect timezone of Calendar instances passed to format(). o LANG-817: Add org.apache.commons.lang3.SystemUtils.IS_OS_WINDOWS_8. diff --git a/src/site/resources/release-notes/RELEASE-NOTES-3.8.txt b/src/site/resources/release-notes/RELEASE-NOTES-3.8.txt index 02063108278..cea0df26461 100644 --- a/src/site/resources/release-notes/RELEASE-NOTES-3.8.txt +++ b/src/site/resources/release-notes/RELEASE-NOTES-3.8.txt @@ -255,7 +255,7 @@ o LANG-1319: MultilineRecursiveToStringStyle StackOverflowError when object is an array. o LANG-1320: LocaleUtils#toLocale does not support language followed by UN M.49 numeric-3 area code followed by variant. -o LANG-1300: Clarify or improve behaviour of int-based indexOf methods in +o LANG-1300: Clarify or improve behavior of int-based indexOf methods in StringUtils. Thanks to Mark Dacek. o LANG-1286: RandomStringUtils random method can overflow and return characters outside of specified range. @@ -965,7 +965,7 @@ o LANG-831: FastDateParser does not handle white-space properly. o LANG-830: FastDateParser could use \Q \E to quote regexes. o LANG-828: FastDateParser does not handle non-Gregorian calendars properly. o LANG-826: FastDateParser does not handle non-ASCII digits correctly. -o LANG-822: NumberUtils#createNumber - bad behaviour for leading "--". +o LANG-822: NumberUtils#createNumber - bad behavior for leading "--". o LANG-818: FastDateFormat's "z" pattern does not respect timezone of Calendar instances passed to format(). o LANG-817: Add org.apache.commons.lang3.SystemUtils.IS_OS_WINDOWS_8. diff --git a/src/site/resources/release-notes/RELEASE-NOTES-3.9.txt b/src/site/resources/release-notes/RELEASE-NOTES-3.9.txt index f9ee7aa22f3..17d7ed36367 100644 --- a/src/site/resources/release-notes/RELEASE-NOTES-3.9.txt +++ b/src/site/resources/release-notes/RELEASE-NOTES-3.9.txt @@ -311,7 +311,7 @@ o LANG-1319: MultilineRecursiveToStringStyle StackOverflowError when object is an array. o LANG-1320: LocaleUtils#toLocale does not support language followed by UN M.49 numeric-3 area code followed by variant. -o LANG-1300: Clarify or improve behaviour of int-based indexOf methods in +o LANG-1300: Clarify or improve behavior of int-based indexOf methods in StringUtils. Thanks to Mark Dacek. o LANG-1286: RandomStringUtils random method can overflow and return characters outside of specified range. @@ -1021,7 +1021,7 @@ o LANG-831: FastDateParser does not handle white-space properly. o LANG-830: FastDateParser could use \Q \E to quote regexes. o LANG-828: FastDateParser does not handle non-Gregorian calendars properly. o LANG-826: FastDateParser does not handle non-ASCII digits correctly. -o LANG-822: NumberUtils#createNumber - bad behaviour for leading "--". +o LANG-822: NumberUtils#createNumber - bad behavior for leading "--". o LANG-818: FastDateFormat's "z" pattern does not respect timezone of Calendar instances passed to format(). o LANG-817: Add org.apache.commons.lang3.SystemUtils.IS_OS_WINDOWS_8. diff --git a/src/site/xdoc/article3_0.xml b/src/site/xdoc/article3_0.xml index 2a3c51928cb..cfac368e274 100644 --- a/src/site/xdoc/article3_0.xml +++ b/src/site/xdoc/article3_0.xml @@ -184,7 +184,7 @@ available in the user guide.

  • StringUtils.isAlpha, isNumeric and isAlphanumeric now all return false when passed an empty String. Previously they returned true.
  • SystemUtils.isJavaVersionAtLeast now relies on the java.specification.version and not the java.version System property.
  • -
  • StringEscapeUtils.escapeXml and escapeHtml no longer escape high value Unicode characters by default. The text.translate package is available to recreate the old behaviour.
  • +
  • StringEscapeUtils.escapeXml and escapeHtml no longer escape high value Unicode characters by default. The text.translate package is available to recreate the old behavior.
  • Validate utility methods have been changed and genericized to return the validated argument where possible, to allow for inline use.
  • Validate utility methods handle validity violations arising from diff --git a/src/site/xdoc/upgradeto2_1.xml b/src/site/xdoc/upgradeto2_1.xml index ea4015866ef..05aac87d21c 100644 --- a/src/site/xdoc/upgradeto2_1.xml +++ b/src/site/xdoc/upgradeto2_1.xml @@ -39,7 +39,7 @@ INCOMPATIBLE CHANGES: - The Nestable interface defines the method indexOfThrowable(Class). Previously the implementations checked only for a specific Class. Now they check for subclasses of that Class as well. -For most situations this will be the expected behaviour (ie. its a bug fix). +For most situations this will be the expected behavior (ie. its a bug fix). If it causes problems, please use the ExceptionUtils.indexOfThrowable(Class) method instead. Note that the ExceptionUtils method is available in v1.0 and v2.0 of commons-lang and has not been changed. (An alternative to this is to change the public static matchSubclasses flag on NestableDelegate. @@ -105,7 +105,7 @@ indexOfThrowable method untouched (see incompatible changes section) -- method to parse a date string using multiple patterns - FastDateFormat - extra formatting methods that take in a millisecond long value -- additional static factory methods -- StopWatch - new methods for split behaviour +- StopWatch - new methods for split behavior BUG FIXES: diff --git a/src/site/xdoc/upgradeto2_3.xml b/src/site/xdoc/upgradeto2_3.xml index 3abf04bfccd..a641befccbd 100644 --- a/src/site/xdoc/upgradeto2_3.xml +++ b/src/site/xdoc/upgradeto2_3.xml @@ -44,7 +44,7 @@ ADDITIONAL INCOMPATIBLE CHANGES WITH VERSION 2.0: - The Nestable interface defines the method indexOfThrowable(Class). Previously the implementations checked only for a specific Class. Now they check for subclasses of that Class as well. -For most situations this will be the expected behaviour (ie. its a bug fix). +For most situations this will be the expected behavior (ie. its a bug fix). If it causes problems, please use the ExceptionUtils.indexOfThrowable(Class) method instead. Note that the ExceptionUtils method is available in v1.0 and v2.0 of commons-lang and has not been changed. (An alternative to this is to change the public static matchSubclasses flag on NestableDelegate. diff --git a/src/site/xdoc/upgradeto2_4.xml b/src/site/xdoc/upgradeto2_4.xml index e80e0795a46..6e56ca46d87 100644 --- a/src/site/xdoc/upgradeto2_4.xml +++ b/src/site/xdoc/upgradeto2_4.xml @@ -50,7 +50,7 @@ ADDITIONAL INCOMPATIBLE CHANGES WITH VERSION 2.0: - The Nestable interface defines the method indexOfThrowable(Class). Previously the implementations checked only for a specific Class. Now they check for subclasses of that Class as well. -For most situations this will be the expected behaviour (ie. its a bug fix). +For most situations this will be the expected behavior (ie. its a bug fix). If it causes problems, please use the ExceptionUtils.indexOfThrowable(Class) method instead. Note that the ExceptionUtils method is available in v1.0 and v2.0 of commons-lang and has not been changed. (An alternative to this is to change the public static matchSubclasses flag on NestableDelegate. diff --git a/src/test/java/org/apache/commons/lang3/StringEscapeUtilsTest.java b/src/test/java/org/apache/commons/lang3/StringEscapeUtilsTest.java index e04c20e5e86..92ea003460a 100644 --- a/src/test/java/org/apache/commons/lang3/StringEscapeUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/StringEscapeUtilsTest.java @@ -501,11 +501,11 @@ public void testEscapeHiragana() { final String original = "\u304B\u304C\u3068"; final String escaped = StringEscapeUtils.escapeHtml4(original); assertEquals(original, escaped, - "Hiragana character Unicode behaviour should not be being escaped by escapeHtml4"); + "Hiragana character Unicode behavior should not be being escaped by escapeHtml4"); final String unescaped = StringEscapeUtils.unescapeHtml4( escaped ); - assertEquals(escaped, unescaped, "Hiragana character Unicode behaviour has changed - expected no unescaping"); + assertEquals(escaped, unescaped, "Hiragana character Unicode behavior has changed - expected no unescaping"); } /** From fbcde48f8f83a9f2ccf75adfcf606bef7663eb73 Mon Sep 17 00:00:00 2001 From: Stanislav U Date: Tue, 31 Mar 2020 21:34:12 +0700 Subject: [PATCH 0058/3230] Fix typo in StringUtils's Java-Doc. (#507) --- src/main/java/org/apache/commons/lang3/StringUtils.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/apache/commons/lang3/StringUtils.java b/src/main/java/org/apache/commons/lang3/StringUtils.java index 5c31d7bcd60..e74ccefad77 100644 --- a/src/main/java/org/apache/commons/lang3/StringUtils.java +++ b/src/main/java/org/apache/commons/lang3/StringUtils.java @@ -494,7 +494,7 @@ public static String appendIfMissing(final String str, final CharSequence suffix * StringUtils.appendIfMissingIgnoreCase("", "xyz", null) = "xyz" * StringUtils.appendIfMissingIgnoreCase("abc", "xyz", new CharSequence[]{null}) = "abcxyz" * StringUtils.appendIfMissingIgnoreCase("abc", "xyz", "") = "abc" - * StringUtils.appendIfMissingIgnoreCase("abc", "xyz", "mno") = "axyz" + * StringUtils.appendIfMissingIgnoreCase("abc", "xyz", "mno") = "abcxyz" * StringUtils.appendIfMissingIgnoreCase("abcxyz", "xyz", "mno") = "abcxyz" * StringUtils.appendIfMissingIgnoreCase("abcmno", "xyz", "mno") = "abcmno" * StringUtils.appendIfMissingIgnoreCase("abcXYZ", "xyz", "mno") = "abcXYZ" From 312a7b3bb1c9ac0f7f1e0fb5656bf6edc0dc2a4a Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Tue, 31 Mar 2020 10:35:47 -0400 Subject: [PATCH 0059/3230] Fix Javdoc for StringUtils.appendIfMissingIgnoreCase() #507. --- src/changes/changes.xml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index f79d5c49b4b..c54dfacbc95 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -45,6 +45,10 @@ The type attribute can be add,update,fix,remove. + + Fix Javdoc for StringUtils.appendIfMissingIgnoreCase() #507. + + Make test more stable by wrapping assertions in hashset. Generate Javadoc jar on build. From d8a6c6745b881de9cf8a145c6509fbc1dd0900cc Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Tue, 7 Apr 2020 09:39:29 -0400 Subject: [PATCH 0060/3230] Missed an update for 3.9 to 3.10. --- src/site/xdoc/index.xml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/site/xdoc/index.xml b/src/site/xdoc/index.xml index 354503dba46..49e9d11f7fe 100644 --- a/src/site/xdoc/index.xml +++ b/src/site/xdoc/index.xml @@ -50,7 +50,7 @@ and various project reports are provided. The Javadoc API documents are available online:

    @@ -61,10 +61,10 @@ The git repository can be
    -

    The latest stable release of Lang is 3.9. You may:

    +

    The latest stable release of Lang is 3.10. You may:

    @@ -74,7 +74,7 @@ Alternatively you can pull it from the central Maven repositories: <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> - <version>3.9</version> + <version>3.10</version> </dependency>

From e389ce1edcc909444944dcb4064050f4eab7b872 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Tue, 7 Apr 2020 10:09:55 -0400 Subject: [PATCH 0061/3230] Missed an update for 3.9 to 3.10. --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 68932c0916a..33c76208cff 100644 --- a/pom.xml +++ b/pom.xml @@ -47,7 +47,7 @@ scm:git:http://gitbox.apache.org/repos/asf/commons-lang.git scm:git:https://gitbox.apache.org/repos/asf/commons-lang.git https://gitbox.apache.org/repos/asf?p=commons-lang.git - commons-lang-3.9 + commons-lang-3.10 From cfe457636a53d3a1927f3c3f130074bfa0c9d492 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Tue, 7 Apr 2020 11:10:27 -0400 Subject: [PATCH 0062/3230] - org.junit-pioneer:junit-pioneer 0.5.4 -> 0.5.6. - org.junit.jupiter:junit-jupiter 5.6.0 -> 5.6.1. --- pom.xml | 4 ++-- src/changes/changes.xml | 2 ++ 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 33c76208cff..b8a3846678b 100644 --- a/pom.xml +++ b/pom.xml @@ -516,13 +516,13 @@ org.junit.jupiter junit-jupiter - 5.6.0 + 5.6.1 test org.junit-pioneer junit-pioneer - 0.5.4 + 0.5.6 test diff --git a/src/changes/changes.xml b/src/changes/changes.xml index c54dfacbc95..b36abca7c2c 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -47,6 +47,8 @@ The type attribute can be add,update,fix,remove. Fix Javdoc for StringUtils.appendIfMissingIgnoreCase() #507. + org.junit-pioneer:junit-pioneer 0.5.4 -> 0.5.6. + org.junit.jupiter:junit-jupiter 5.6.0 -> 5.6.1. From 9949212b92de00609cb511d6f1b4599290240f73 Mon Sep 17 00:00:00 2001 From: Isira Seneviratne Date: Fri, 17 Apr 2020 12:06:48 +0530 Subject: [PATCH 0063/3230] Fix some spelling and grammar issues in the StringUtils Javadoc. --- .../org/apache/commons/lang3/StringUtils.java | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/StringUtils.java b/src/main/java/org/apache/commons/lang3/StringUtils.java index e74ccefad77..a585c2eb35d 100644 --- a/src/main/java/org/apache/commons/lang3/StringUtils.java +++ b/src/main/java/org/apache/commons/lang3/StringUtils.java @@ -38,17 +38,17 @@ *
  • Trim/Strip * - removes leading and trailing whitespace
  • *
  • Equals/Compare - * - compares two strings null-safe
  • + * - compares two strings in a null-safe manner *
  • startsWith - * - check if a String starts with a prefix null-safe
  • + * - check if a String starts with a prefix in a null-safe manner *
  • endsWith - * - check if a String ends with a suffix null-safe
  • + * - check if a String ends with a suffix in a null-safe manner *
  • IndexOf/LastIndexOf/Contains * - null-safe index-of checks *
  • IndexOfAny/LastIndexOfAny/IndexOfAnyBut/LastIndexOfAnyBut * - index-of any of a set of Strings
  • *
  • ContainsOnly/ContainsNone/ContainsAny - * - does String contains only/none/any of these characters
  • + * - checks if String contains only/none/any of these characters *
  • Substring/Left/Right/Mid * - null-safe substring extractions
  • *
  • SubstringBefore/SubstringAfter/SubstringBetween @@ -80,7 +80,7 @@ *
  • Reverse/ReverseDelimited * - reverses a String
  • *
  • Abbreviate - * - abbreviates a string using ellipsis or another given String
  • + * - abbreviates a string using ellipses or another given String *
  • Difference * - compares Strings and reports on their differences
  • *
  • LevenshteinDistance @@ -107,7 +107,7 @@ * {@code NullPointerException} should be considered a bug in * {@code StringUtils}.

    * - *

    Methods in this class give sample code to explain their operation. + *

    Methods in this class include sample code in their Javadoc comments to explain their operation. * The symbol {@code *} is used to indicate any input including {@code null}.

    * *

    #ThreadSafe#

    @@ -564,7 +564,7 @@ public static String capitalize(final String str) { *

    Centers a String in a larger String of size {@code size} * using the space character (' ').

    * - *

    If the size is less than the String length, the String is returned. + *

    If the size is less than the String length, the original String is returned. * A {@code null} String returns {@code null}. * A negative size is treated as zero.

    * @@ -5015,7 +5015,7 @@ public static int lastIndexOf(final CharSequence seq, final int searchChar, fina } /** - *

    Find the latest index of any of a set of potential substrings.

    + *

    Find the latest index of any substring in a set of potential substrings.

    * *

    A {@code null} CharSequence will return {@code -1}. * A {@code null} search array will return {@code -1}. @@ -6386,7 +6386,7 @@ public static String replace(final String text, final String searchString, final /** *

    Replaces a String with another String inside a larger String, * for the first {@code max} values of the search String, - * case sensitively/insensisitively based on {@code ignoreCase} value.

    + * case sensitively/insensitively based on {@code ignoreCase} value.

    * *

    A {@code null} reference passed to this method is a no-op.

    * From 6265e2ea3bbcc2e810f9e86cc283e0cb5877993e Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Fri, 17 Apr 2020 09:06:52 -0400 Subject: [PATCH 0064/3230] Format tweaks. --- src/main/java/org/apache/commons/lang3/Range.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/main/java/org/apache/commons/lang3/Range.java b/src/main/java/org/apache/commons/lang3/Range.java index b7f0b1c039f..a17254118d7 100644 --- a/src/main/java/org/apache/commons/lang3/Range.java +++ b/src/main/java/org/apache/commons/lang3/Range.java @@ -73,6 +73,7 @@ public int compare(final Object obj1, final Object obj2) { public static > Range between(final T fromInclusive, final T toInclusive) { return between(fromInclusive, toInclusive, null); } + /** *

    Obtains a range with the specified minimum and maximum values (both inclusive).

    * @@ -93,6 +94,7 @@ public static > Range between(final T fromInclusive, public static Range between(final T fromInclusive, final T toInclusive, final Comparator comparator) { return new Range<>(fromInclusive, toInclusive, comparator); } + /** *

    Obtains a range using the specified element as both the minimum * and maximum in this range.

    @@ -109,6 +111,7 @@ public static Range between(final T fromInclusive, final T toInclusive, f public static > Range is(final T element) { return between(element, element, null); } + /** *

    Obtains a range using the specified element as both the minimum * and maximum in this range.

    From d94d76bbecf90beefeb4c1b51effd837e636ae90 Mon Sep 17 00:00:00 2001 From: Isira Seneviratne Date: Sun, 19 Apr 2020 21:12:57 +0530 Subject: [PATCH 0065/3230] Alter assertions to get the class of CharUtils instead of BooleanUtils. --- src/test/java/org/apache/commons/lang3/CharUtilsTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/test/java/org/apache/commons/lang3/CharUtilsTest.java b/src/test/java/org/apache/commons/lang3/CharUtilsTest.java index 49b1a9300fa..6bf50cb36b6 100644 --- a/src/test/java/org/apache/commons/lang3/CharUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/CharUtilsTest.java @@ -52,8 +52,8 @@ public void testConstructor() { final Constructor[] cons = CharUtils.class.getDeclaredConstructors(); assertEquals(1, cons.length); assertTrue(Modifier.isPublic(cons[0].getModifiers())); - assertTrue(Modifier.isPublic(BooleanUtils.class.getModifiers())); - assertFalse(Modifier.isFinal(BooleanUtils.class.getModifiers())); + assertTrue(Modifier.isPublic(CharUtils.class.getModifiers())); + assertFalse(Modifier.isFinal(CharUtils.class.getModifiers())); } @Test From d7f8dcedfa7b5719011fd14b620b045b4dcac9af Mon Sep 17 00:00:00 2001 From: Isira Seneviratne <31027858+Isira-Seneviratne@users.noreply.github.com> Date: Mon, 20 Apr 2020 14:10:39 +0000 Subject: [PATCH 0066/3230] Simplify null checks in Pair.hashCode() using Objects.hashCode(). (#517) --- src/main/java/org/apache/commons/lang3/tuple/Pair.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/tuple/Pair.java b/src/main/java/org/apache/commons/lang3/tuple/Pair.java index 62889bd8d56..32c5d9af08f 100644 --- a/src/main/java/org/apache/commons/lang3/tuple/Pair.java +++ b/src/main/java/org/apache/commons/lang3/tuple/Pair.java @@ -207,8 +207,7 @@ public R getValue() { @Override public int hashCode() { // see Map.Entry API specification - return (getKey() == null ? 0 : getKey().hashCode()) ^ - (getValue() == null ? 0 : getValue().hashCode()); + return Objects.hashCode(getKey()) ^ Objects.hashCode(getValue()); } /** From a1531bcd1e25f0fdf92743c65e01bf9d716d5868 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Mon, 20 Apr 2020 10:12:21 -0400 Subject: [PATCH 0067/3230] Simplify null checks in Pair.hashCode() using Objects.hashCode(). #517. --- src/changes/changes.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index b36abca7c2c..0c7f17fb4e8 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -49,6 +49,7 @@ The type attribute can be add,update,fix,remove. Fix Javdoc for StringUtils.appendIfMissingIgnoreCase() #507. org.junit-pioneer:junit-pioneer 0.5.4 -> 0.5.6. org.junit.jupiter:junit-jupiter 5.6.0 -> 5.6.1. + Simplify null checks in Pair.hashCode() using Objects.hashCode(). #517. From c7ab53f9e34be876309e835f981db69920f79cdc Mon Sep 17 00:00:00 2001 From: Isira Seneviratne <31027858+Isira-Seneviratne@users.noreply.github.com> Date: Mon, 20 Apr 2020 20:43:46 +0000 Subject: [PATCH 0068/3230] Simplify null checks in Triple.hashCode() using Objects.hashCode(). (#516) --- src/main/java/org/apache/commons/lang3/tuple/Triple.java | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/tuple/Triple.java b/src/main/java/org/apache/commons/lang3/tuple/Triple.java index c52fd67bdda..e44dbc27d9a 100644 --- a/src/main/java/org/apache/commons/lang3/tuple/Triple.java +++ b/src/main/java/org/apache/commons/lang3/tuple/Triple.java @@ -171,9 +171,7 @@ public boolean equals(final Object obj) { */ @Override public int hashCode() { - return (getLeft() == null ? 0 : getLeft().hashCode()) ^ - (getMiddle() == null ? 0 : getMiddle().hashCode()) ^ - (getRight() == null ? 0 : getRight().hashCode()); + return Objects.hashCode(getLeft()) ^ Objects.hashCode(getMiddle()) ^ Objects.hashCode(getRight()); } /** From f13f787a6629e6eba2d027dd9635fb7cdcf0c17b Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Mon, 20 Apr 2020 16:44:29 -0400 Subject: [PATCH 0069/3230] Simplify null checks in Triple.hashCode() using Objects.hashCode(). #516. --- src/changes/changes.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 0c7f17fb4e8..e0be103cac5 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -50,6 +50,7 @@ The type attribute can be add,update,fix,remove. org.junit-pioneer:junit-pioneer 0.5.4 -> 0.5.6. org.junit.jupiter:junit-jupiter 5.6.0 -> 5.6.1. Simplify null checks in Pair.hashCode() using Objects.hashCode(). #517. + Simplify null checks in Triple.hashCode() using Objects.hashCode(). #516. From 675d30d88282e4ee8e96952d672ea1e7fa330ee6 Mon Sep 17 00:00:00 2001 From: Isira Seneviratne <31027858+Isira-Seneviratne@users.noreply.github.com> Date: Mon, 20 Apr 2020 20:52:56 +0000 Subject: [PATCH 0070/3230] Simplify some if statements in StringUtils. (#521) * Simplify if-else statements at the start of abbreviate(). * Combine if statements in abbreviateMiddle(). * Simplify the first if condition of substringBetween(). * Simplify the first if condition of stripAll(). --- .../org/apache/commons/lang3/StringUtils.java | 20 +++++++------------ 1 file changed, 7 insertions(+), 13 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/StringUtils.java b/src/main/java/org/apache/commons/lang3/StringUtils.java index a585c2eb35d..941dd5c45cd 100644 --- a/src/main/java/org/apache/commons/lang3/StringUtils.java +++ b/src/main/java/org/apache/commons/lang3/StringUtils.java @@ -330,11 +330,9 @@ public static String abbreviate(final String str, final String abbrevMarker, fin * @since 3.6 */ public static String abbreviate(final String str, final String abbrevMarker, int offset, final int maxWidth) { - if (isEmpty(str) && isEmpty(abbrevMarker)) { - return str; - } else if (isNotEmpty(str) && EMPTY.equals(abbrevMarker) && maxWidth > 0) { - return str.substring(0, maxWidth); - } else if (isEmpty(str) || isEmpty(abbrevMarker)) { + if (isNotEmpty(str) && EMPTY.equals(abbrevMarker) && maxWidth > 0) { + return substring(str, 0, maxWidth); + } else if (isAnyEmpty(str, abbrevMarker)) { return str; } final int abbrevMarkerLength = abbrevMarker.length(); @@ -395,11 +393,7 @@ public static String abbreviate(final String str, final String abbrevMarker, int * @since 2.5 */ public static String abbreviateMiddle(final String str, final String middle, final int length) { - if (isEmpty(str) || isEmpty(middle)) { - return str; - } - - if (length >= str.length() || length < middle.length()+2) { + if (isAnyEmpty(str, middle) || length >= str.length() || length < middle.length()+2) { return str; } @@ -8274,8 +8268,8 @@ public static String[] stripAll(final String... strs) { * @return the stripped Strings, {@code null} if null array input */ public static String[] stripAll(final String[] strs, final String stripChars) { - int strsLen; - if (strs == null || (strsLen = strs.length) == 0) { + int strsLen = ArrayUtils.getLength(strs); + if (strsLen == 0) { return strs; } final String[] newArr = new String[strsLen]; @@ -8772,7 +8766,7 @@ public static String substringBetween(final String str, final String tag) { * @since 2.0 */ public static String substringBetween(final String str, final String open, final String close) { - if (str == null || open == null || close == null) { + if (!ObjectUtils.allNotNull(str, open, close)) { return null; } final int start = str.indexOf(open); From 96caf42b31df9da0bada58ae2ae2d277ebe20434 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Mon, 20 Apr 2020 16:53:29 -0400 Subject: [PATCH 0071/3230] Simplify some if statements in StringUtils. #521. --- src/changes/changes.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index e0be103cac5..0c7a3a6d8b9 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -51,6 +51,7 @@ The type attribute can be add,update,fix,remove. org.junit.jupiter:junit-jupiter 5.6.0 -> 5.6.1. Simplify null checks in Pair.hashCode() using Objects.hashCode(). #517. Simplify null checks in Triple.hashCode() using Objects.hashCode(). #516. + Simplify some if statements in StringUtils. #521. From 0b899ee40b23e8e73e11f1604342be3e278b467d Mon Sep 17 00:00:00 2001 From: Isira Seneviratne <31027858+Isira-Seneviratne@users.noreply.github.com> Date: Mon, 20 Apr 2020 20:54:33 +0000 Subject: [PATCH 0072/3230] Simplify a null check in the private replaceEach() method. (#514) --- src/main/java/org/apache/commons/lang3/StringUtils.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/StringUtils.java b/src/main/java/org/apache/commons/lang3/StringUtils.java index 941dd5c45cd..3caf9e168cf 100644 --- a/src/main/java/org/apache/commons/lang3/StringUtils.java +++ b/src/main/java/org/apache/commons/lang3/StringUtils.java @@ -6717,8 +6717,7 @@ private static String replaceEach( // index of replace array that will replace the search string found // NOTE: logic duplicated below START for (int i = 0; i < searchLength; i++) { - if (noMoreMatchesForReplIndex[i] || searchList[i] == null || - searchList[i].isEmpty() || replacementList[i] == null) { + if (noMoreMatchesForReplIndex[i] || isEmpty(searchList[i]) || replacementList[i] == null) { continue; } tempIndex = text.indexOf(searchList[i]); From 271cf4c9e945cbab3a1f87e905d4c6d52facd95d Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Mon, 20 Apr 2020 16:56:02 -0400 Subject: [PATCH 0073/3230] [LANG-1537] Simplify a null check in the private replaceEach() method of StringUtils. #514. --- src/changes/changes.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 0c7a3a6d8b9..c91fd189507 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -52,6 +52,7 @@ The type attribute can be add,update,fix,remove. Simplify null checks in Pair.hashCode() using Objects.hashCode(). #517. Simplify null checks in Triple.hashCode() using Objects.hashCode(). #516. Simplify some if statements in StringUtils. #521. + Simplify a null check in the private replaceEach() method of StringUtils. #514. From 44d4acc6218bf06843833eaf275ccf5f2d526999 Mon Sep 17 00:00:00 2001 From: Isira Seneviratne <31027858+Isira-Seneviratne@users.noreply.github.com> Date: Mon, 20 Apr 2020 20:57:41 +0000 Subject: [PATCH 0074/3230] Simplify some usages of the ternary operator with calls to Math.max() and Math.min(). (#512) --- src/main/java/org/apache/commons/lang3/StringUtils.java | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/StringUtils.java b/src/main/java/org/apache/commons/lang3/StringUtils.java index 3caf9e168cf..4f20fd82c36 100644 --- a/src/main/java/org/apache/commons/lang3/StringUtils.java +++ b/src/main/java/org/apache/commons/lang3/StringUtils.java @@ -6421,9 +6421,8 @@ private static String replace(final String text, String searchString, final Stri return text; } final int replLength = searchString.length(); - int increase = replacement.length() - replLength; - increase = increase < 0 ? 0 : increase; - increase *= max < 0 ? 16 : max > 64 ? 64 : max; + int increase = Math.max(replacement.length() - replLength, 0); + increase *= max < 0 ? 16 : Math.min(max, 64); final StringBuilder buf = new StringBuilder(text.length() + increase); while (end != INDEX_NOT_FOUND) { buf.append(text, start, end).append(replacement); @@ -9168,7 +9167,7 @@ public static String truncate(final String str, final int offset, final int maxW return EMPTY; } if (str.length() > maxWidth) { - final int ix = offset + maxWidth > str.length() ? str.length() : offset + maxWidth; + final int ix = Math.min(offset + maxWidth, str.length()); return str.substring(offset, ix); } return str.substring(offset); From 9388c5747f4a742d2de28ae6fc0d92f97efc6b32 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Mon, 20 Apr 2020 16:58:20 -0400 Subject: [PATCH 0075/3230] [LANG-1534] Replace some usages of the ternary operator with calls to Math.max() and Math.min() #512. --- src/changes/changes.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index c91fd189507..befdbf49b00 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -53,6 +53,7 @@ The type attribute can be add,update,fix,remove. Simplify null checks in Triple.hashCode() using Objects.hashCode(). #516. Simplify some if statements in StringUtils. #521. Simplify a null check in the private replaceEach() method of StringUtils. #514. + Replace some usages of the ternary operator with calls to Math.max() and Math.min() #512. From 22500d11ae62c0d54021081d1909b504178e0276 Mon Sep 17 00:00:00 2001 From: "Arend v. Reinersdorff" Date: Mon, 20 Apr 2020 23:08:55 +0200 Subject: [PATCH 0076/3230] (doc) Fix throwable is returned, not index (#518) --- .../apache/commons/lang3/exception/ExceptionUtils.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/exception/ExceptionUtils.java b/src/main/java/org/apache/commons/lang3/exception/ExceptionUtils.java index a2a67b4bc0d..205e1ae6761 100644 --- a/src/main/java/org/apache/commons/lang3/exception/ExceptionUtils.java +++ b/src/main/java/org/apache/commons/lang3/exception/ExceptionUtils.java @@ -810,7 +810,7 @@ private static T throwableOf(final Throwable throwable, fi * @param the type of Throwable you are searching. * @param throwable the throwable to inspect, may be null * @param clazz the class to search for, subclasses do not match, null returns null - * @return the index into the throwable chain, null if no match or null input + * @return the first matching throwable from the throwable chain, null if no match or null input * @since 3.10 */ public static T throwableOfThrowable(final Throwable throwable, final Class clazz) { @@ -835,7 +835,7 @@ public static T throwableOfThrowable(final Throwable throw * @param clazz the class to search for, subclasses do not match, null returns null * @param fromIndex the (zero-based) index of the starting position, * negative treated as zero, larger than chain size returns null - * @return the index into the throwable chain, null if no match or null input + * @return the first matching throwable from the throwable chain, null if no match or null input * @since 3.10 */ public static T throwableOfThrowable(final Throwable throwable, final Class clazz, final int fromIndex) { @@ -855,7 +855,7 @@ public static T throwableOfThrowable(final Throwable throw * @param the type of Throwable you are searching. * @param throwable the throwable to inspect, may be null * @param type the type to search for, subclasses match, null returns null - * @return the index into the throwable chain, null if no match or null input + * @return the first matching throwable from the throwable chain, null if no match or null input * @since 3.10 */ public static T throwableOfType(final Throwable throwable, final Class type) { @@ -880,7 +880,7 @@ public static T throwableOfType(final Throwable throwable, * @param type the type to search for, subclasses match, null returns null * @param fromIndex the (zero-based) index of the starting position, * negative treated as zero, larger than chain size returns null - * @return the index into the throwable chain, null if no match or null input + * @return the first matching throwable from the throwable chain, null if no match or null input * @since 3.10 */ public static T throwableOfType(final Throwable throwable, final Class type, final int fromIndex) { From 7c754d9c1e96c2a3e90e4bf632b421a43f235e22 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Mon, 20 Apr 2020 17:10:42 -0400 Subject: [PATCH 0077/3230] (Javadoc) Fix return tag for throwableOf*() methods #518. --- src/changes/changes.xml | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index befdbf49b00..d7a9336679a 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -49,11 +49,12 @@ The type attribute can be add,update,fix,remove. Fix Javdoc for StringUtils.appendIfMissingIgnoreCase() #507. org.junit-pioneer:junit-pioneer 0.5.4 -> 0.5.6. org.junit.jupiter:junit-jupiter 5.6.0 -> 5.6.1. - Simplify null checks in Pair.hashCode() using Objects.hashCode(). #517. - Simplify null checks in Triple.hashCode() using Objects.hashCode(). #516. - Simplify some if statements in StringUtils. #521. - Simplify a null check in the private replaceEach() method of StringUtils. #514. - Replace some usages of the ternary operator with calls to Math.max() and Math.min() #512. + Simplify null checks in Pair.hashCode() using Objects.hashCode(). #517. + Simplify null checks in Triple.hashCode() using Objects.hashCode(). #516. + Simplify some if statements in StringUtils. #521. + Simplify a null check in the private replaceEach() method of StringUtils. #514. + Replace some usages of the ternary operator with calls to Math.max() and Math.min() #512. + (Javadoc) Fix return tag for throwableOf*() methods #518. From 299736554ae0b71be544debbc931c4c40909bf06 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Mon, 20 Apr 2020 17:13:50 -0400 Subject: [PATCH 0078/3230] spotbugs.plugin.version 4.0.0 -> 4.0.2. --- pom.xml | 2 +- src/changes/changes.xml | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index b8a3846678b..8ad661d5901 100644 --- a/pom.xml +++ b/pom.xml @@ -603,7 +603,7 @@ 8.29 src/site/resources/checkstyle - 4.0.0 + 4.0.2 false diff --git a/src/changes/changes.xml b/src/changes/changes.xml index d7a9336679a..61242a19170 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -49,6 +49,7 @@ The type attribute can be add,update,fix,remove. Fix Javdoc for StringUtils.appendIfMissingIgnoreCase() #507. org.junit-pioneer:junit-pioneer 0.5.4 -> 0.5.6. org.junit.jupiter:junit-jupiter 5.6.0 -> 5.6.1. + spotbugs.plugin.version 4.0.0 -> 4.0.2. Simplify null checks in Pair.hashCode() using Objects.hashCode(). #517. Simplify null checks in Triple.hashCode() using Objects.hashCode(). #516. Simplify some if statements in StringUtils. #521. From f6923510352fc3fbfad68bc6c5ac5258a34671b7 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Mon, 20 Apr 2020 17:23:31 -0400 Subject: [PATCH 0079/3230] - com.github.spotbugs:spotbugs 4.0.0 -> 4.0.2. - com.puppycrawl.tools:checkstyle 8.29 -> 8.31. --- pom.xml | 6 +++--- src/changes/changes.xml | 3 ++- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/pom.xml b/pom.xml index 8ad661d5901..b8c8a886b91 100644 --- a/pom.xml +++ b/pom.xml @@ -600,10 +600,10 @@ utf-8 3.1.1 - 8.29 + 8.31 src/site/resources/checkstyle - 4.0.2 + 4.0.0 false @@ -765,7 +765,7 @@ com.github.spotbugs spotbugs - 4.0.0 + 4.0.2 diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 61242a19170..ac9a2cd752c 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -49,7 +49,8 @@ The type attribute can be add,update,fix,remove. Fix Javdoc for StringUtils.appendIfMissingIgnoreCase() #507. org.junit-pioneer:junit-pioneer 0.5.4 -> 0.5.6. org.junit.jupiter:junit-jupiter 5.6.0 -> 5.6.1. - spotbugs.plugin.version 4.0.0 -> 4.0.2. + com.github.spotbugs:spotbugs 4.0.0 -> 4.0.2. + com.puppycrawl.tools:checkstyle 8.29 -> 8.31. Simplify null checks in Pair.hashCode() using Objects.hashCode(). #517. Simplify null checks in Triple.hashCode() using Objects.hashCode(). #516. Simplify some if statements in StringUtils. #521. From daa4193fb289e57bd15e10555378f97f90d79dcd Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sun, 24 May 2020 11:05:21 -0400 Subject: [PATCH 0080/3230] Add ArrayUtils.isSameLength() to compare more array types #430. --- .../org/apache/commons/lang3/ArrayUtils.java | 19 +- .../apache/commons/lang3/ArrayUtilsTest.java | 1336 +++++++++++++++++ 2 files changed, 1353 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/ArrayUtils.java b/src/main/java/org/apache/commons/lang3/ArrayUtils.java index 320fba6d38d..d8d7ff5c6f1 100644 --- a/src/main/java/org/apache/commons/lang3/ArrayUtils.java +++ b/src/main/java/org/apache/commons/lang3/ArrayUtils.java @@ -3406,8 +3406,23 @@ public static boolean isSameLength(final long[] array1, final long[] array2) { return getLength(array1) == getLength(array2); } - // Is same length - //----------------------------------------------------------------------- + + /** + *

    Checks whether two arrays are the same length, treating + * {@code null} arrays as length {@code 0}. + * + *

    Any multi-dimensional aspects of the arrays are ignored. + * + * @param array1 the first array, may be {@code null} + * @param array2 the second array, may be {@code null} + * @return {@code true} if length of arrays matches, treating + * {@code null} as an empty array + * @since 3.11 + */ + public static boolean isSameLength(final Object array1, final Object array2) { + return getLength(array1) == getLength(array2); + } + /** *

    Checks whether two arrays are the same length, treating * {@code null} arrays as length {@code 0}. diff --git a/src/test/java/org/apache/commons/lang3/ArrayUtilsTest.java b/src/test/java/org/apache/commons/lang3/ArrayUtilsTest.java index 3831f090a62..66b4d277df7 100644 --- a/src/test/java/org/apache/commons/lang3/ArrayUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/ArrayUtilsTest.java @@ -1405,6 +1405,1342 @@ public void testSameLengthFloat() { assertTrue(ArrayUtils.isSameLength(twoArray, twoArray)); } + @Test + public void testSameLengthAll() { + final Object[] nullArrayObject = null; + final Object[] emptyArrayObject = new Object[0]; + final Object[] oneArrayObject = new Object[]{"pick"}; + final Object[] twoArrayObject = new Object[]{"pick", "stick"}; + final boolean[] nullArrayBoolean = null; + final boolean[] emptyArrayBoolean = new boolean[0]; + final boolean[] oneArrayBoolean = new boolean[]{true}; + final boolean[] twoArrayBoolean = new boolean[]{true, false}; + final long[] nullArrayLong = null; + final long[] emptyArrayLong = new long[0]; + final long[] oneArrayLong = new long[]{0L}; + final long[] twoArrayLong = new long[]{0L, 76L}; + final int[] nullArrayInt = null; + final int[] emptyArrayInt = new int[0]; + final int[] oneArrayInt = new int[]{4}; + final int[] twoArrayInt = new int[]{5, 7}; + final short[] nullArrayShort = null; + final short[] emptyArrayShort = new short[0]; + final short[] oneArrayShort = new short[]{4}; + final short[] twoArrayShort = new short[]{6, 8}; + final char[] nullArrayChar = null; + final char[] emptyArrayChar = new char[0]; + final char[] oneArrayChar = new char[]{'f'}; + final char[] twoArrayChar = new char[]{'d', 't'}; + final byte[] nullArrayByte = null; + final byte[] emptyArrayByte = new byte[0]; + final byte[] oneArrayByte = new byte[]{3}; + final byte[] twoArrayByte = new byte[]{4, 6}; + final double[] nullArrayDouble = null; + final double[] emptyArrayDouble = new double[0]; + final double[] oneArrayDouble = new double[]{1.3d}; + final double[] twoArrayDouble = new double[]{4.5d, 6.3d}; + final float[] nullArrayFloat = null; + final float[] emptyArrayFloat = new float[0]; + final float[] oneArrayFloat = new float[]{2.5f}; + final float[] twoArrayFloat = new float[]{6.4f, 5.8f}; + assertTrue(ArrayUtils.isSameLength(nullArrayObject, nullArrayObject)); + assertTrue(ArrayUtils.isSameLength(nullArrayObject, nullArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(nullArrayObject, nullArrayLong)); + assertTrue(ArrayUtils.isSameLength(nullArrayObject, nullArrayInt)); + assertTrue(ArrayUtils.isSameLength(nullArrayObject, nullArrayShort)); + assertTrue(ArrayUtils.isSameLength(nullArrayObject, nullArrayChar)); + assertTrue(ArrayUtils.isSameLength(nullArrayObject, nullArrayByte)); + assertTrue(ArrayUtils.isSameLength(nullArrayObject, nullArrayDouble)); + assertTrue(ArrayUtils.isSameLength(nullArrayObject, nullArrayFloat)); + assertTrue(ArrayUtils.isSameLength(nullArrayBoolean, nullArrayObject)); + assertTrue(ArrayUtils.isSameLength(nullArrayBoolean, nullArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(nullArrayBoolean, nullArrayLong)); + assertTrue(ArrayUtils.isSameLength(nullArrayBoolean, nullArrayInt)); + assertTrue(ArrayUtils.isSameLength(nullArrayBoolean, nullArrayShort)); + assertTrue(ArrayUtils.isSameLength(nullArrayBoolean, nullArrayChar)); + assertTrue(ArrayUtils.isSameLength(nullArrayBoolean, nullArrayByte)); + assertTrue(ArrayUtils.isSameLength(nullArrayBoolean, nullArrayDouble)); + assertTrue(ArrayUtils.isSameLength(nullArrayBoolean, nullArrayFloat)); + assertTrue(ArrayUtils.isSameLength(nullArrayLong, nullArrayObject)); + assertTrue(ArrayUtils.isSameLength(nullArrayLong, nullArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(nullArrayLong, nullArrayLong)); + assertTrue(ArrayUtils.isSameLength(nullArrayLong, nullArrayInt)); + assertTrue(ArrayUtils.isSameLength(nullArrayLong, nullArrayShort)); + assertTrue(ArrayUtils.isSameLength(nullArrayLong, nullArrayChar)); + assertTrue(ArrayUtils.isSameLength(nullArrayLong, nullArrayByte)); + assertTrue(ArrayUtils.isSameLength(nullArrayLong, nullArrayDouble)); + assertTrue(ArrayUtils.isSameLength(nullArrayLong, nullArrayFloat)); + assertTrue(ArrayUtils.isSameLength(nullArrayInt, nullArrayObject)); + assertTrue(ArrayUtils.isSameLength(nullArrayInt, nullArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(nullArrayInt, nullArrayLong)); + assertTrue(ArrayUtils.isSameLength(nullArrayInt, nullArrayInt)); + assertTrue(ArrayUtils.isSameLength(nullArrayInt, nullArrayShort)); + assertTrue(ArrayUtils.isSameLength(nullArrayInt, nullArrayChar)); + assertTrue(ArrayUtils.isSameLength(nullArrayInt, nullArrayByte)); + assertTrue(ArrayUtils.isSameLength(nullArrayInt, nullArrayDouble)); + assertTrue(ArrayUtils.isSameLength(nullArrayInt, nullArrayFloat)); + assertTrue(ArrayUtils.isSameLength(nullArrayShort, nullArrayObject)); + assertTrue(ArrayUtils.isSameLength(nullArrayShort, nullArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(nullArrayShort, nullArrayLong)); + assertTrue(ArrayUtils.isSameLength(nullArrayShort, nullArrayInt)); + assertTrue(ArrayUtils.isSameLength(nullArrayShort, nullArrayShort)); + assertTrue(ArrayUtils.isSameLength(nullArrayShort, nullArrayChar)); + assertTrue(ArrayUtils.isSameLength(nullArrayShort, nullArrayByte)); + assertTrue(ArrayUtils.isSameLength(nullArrayShort, nullArrayDouble)); + assertTrue(ArrayUtils.isSameLength(nullArrayShort, nullArrayFloat)); + assertTrue(ArrayUtils.isSameLength(nullArrayChar, nullArrayObject)); + assertTrue(ArrayUtils.isSameLength(nullArrayChar, nullArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(nullArrayChar, nullArrayLong)); + assertTrue(ArrayUtils.isSameLength(nullArrayChar, nullArrayInt)); + assertTrue(ArrayUtils.isSameLength(nullArrayChar, nullArrayShort)); + assertTrue(ArrayUtils.isSameLength(nullArrayChar, nullArrayChar)); + assertTrue(ArrayUtils.isSameLength(nullArrayChar, nullArrayByte)); + assertTrue(ArrayUtils.isSameLength(nullArrayChar, nullArrayDouble)); + assertTrue(ArrayUtils.isSameLength(nullArrayChar, nullArrayFloat)); + assertTrue(ArrayUtils.isSameLength(nullArrayByte, nullArrayObject)); + assertTrue(ArrayUtils.isSameLength(nullArrayByte, nullArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(nullArrayByte, nullArrayLong)); + assertTrue(ArrayUtils.isSameLength(nullArrayByte, nullArrayInt)); + assertTrue(ArrayUtils.isSameLength(nullArrayByte, nullArrayShort)); + assertTrue(ArrayUtils.isSameLength(nullArrayByte, nullArrayChar)); + assertTrue(ArrayUtils.isSameLength(nullArrayByte, nullArrayByte)); + assertTrue(ArrayUtils.isSameLength(nullArrayByte, nullArrayDouble)); + assertTrue(ArrayUtils.isSameLength(nullArrayByte, nullArrayFloat)); + assertTrue(ArrayUtils.isSameLength(nullArrayDouble, nullArrayObject)); + assertTrue(ArrayUtils.isSameLength(nullArrayDouble, nullArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(nullArrayDouble, nullArrayLong)); + assertTrue(ArrayUtils.isSameLength(nullArrayDouble, nullArrayInt)); + assertTrue(ArrayUtils.isSameLength(nullArrayDouble, nullArrayShort)); + assertTrue(ArrayUtils.isSameLength(nullArrayDouble, nullArrayChar)); + assertTrue(ArrayUtils.isSameLength(nullArrayDouble, nullArrayByte)); + assertTrue(ArrayUtils.isSameLength(nullArrayDouble, nullArrayDouble)); + assertTrue(ArrayUtils.isSameLength(nullArrayDouble, nullArrayFloat)); + assertTrue(ArrayUtils.isSameLength(nullArrayFloat, nullArrayObject)); + assertTrue(ArrayUtils.isSameLength(nullArrayFloat, nullArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(nullArrayFloat, nullArrayLong)); + assertTrue(ArrayUtils.isSameLength(nullArrayFloat, nullArrayInt)); + assertTrue(ArrayUtils.isSameLength(nullArrayFloat, nullArrayShort)); + assertTrue(ArrayUtils.isSameLength(nullArrayFloat, nullArrayChar)); + assertTrue(ArrayUtils.isSameLength(nullArrayFloat, nullArrayByte)); + assertTrue(ArrayUtils.isSameLength(nullArrayFloat, nullArrayDouble)); + assertTrue(ArrayUtils.isSameLength(nullArrayFloat, nullArrayFloat)); + assertTrue(ArrayUtils.isSameLength(nullArrayObject, emptyArrayObject)); + assertTrue(ArrayUtils.isSameLength(nullArrayObject, emptyArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(nullArrayObject, emptyArrayLong)); + assertTrue(ArrayUtils.isSameLength(nullArrayObject, emptyArrayInt)); + assertTrue(ArrayUtils.isSameLength(nullArrayObject, emptyArrayShort)); + assertTrue(ArrayUtils.isSameLength(nullArrayObject, emptyArrayChar)); + assertTrue(ArrayUtils.isSameLength(nullArrayObject, emptyArrayByte)); + assertTrue(ArrayUtils.isSameLength(nullArrayObject, emptyArrayDouble)); + assertTrue(ArrayUtils.isSameLength(nullArrayObject, emptyArrayFloat)); + assertTrue(ArrayUtils.isSameLength(nullArrayBoolean, emptyArrayObject)); + assertTrue(ArrayUtils.isSameLength(nullArrayBoolean, emptyArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(nullArrayBoolean, emptyArrayLong)); + assertTrue(ArrayUtils.isSameLength(nullArrayBoolean, emptyArrayInt)); + assertTrue(ArrayUtils.isSameLength(nullArrayBoolean, emptyArrayShort)); + assertTrue(ArrayUtils.isSameLength(nullArrayBoolean, emptyArrayChar)); + assertTrue(ArrayUtils.isSameLength(nullArrayBoolean, emptyArrayByte)); + assertTrue(ArrayUtils.isSameLength(nullArrayBoolean, emptyArrayDouble)); + assertTrue(ArrayUtils.isSameLength(nullArrayBoolean, emptyArrayFloat)); + assertTrue(ArrayUtils.isSameLength(nullArrayLong, emptyArrayObject)); + assertTrue(ArrayUtils.isSameLength(nullArrayLong, emptyArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(nullArrayLong, emptyArrayLong)); + assertTrue(ArrayUtils.isSameLength(nullArrayLong, emptyArrayInt)); + assertTrue(ArrayUtils.isSameLength(nullArrayLong, emptyArrayShort)); + assertTrue(ArrayUtils.isSameLength(nullArrayLong, emptyArrayChar)); + assertTrue(ArrayUtils.isSameLength(nullArrayLong, emptyArrayByte)); + assertTrue(ArrayUtils.isSameLength(nullArrayLong, emptyArrayDouble)); + assertTrue(ArrayUtils.isSameLength(nullArrayLong, emptyArrayFloat)); + assertTrue(ArrayUtils.isSameLength(nullArrayInt, emptyArrayObject)); + assertTrue(ArrayUtils.isSameLength(nullArrayInt, emptyArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(nullArrayInt, emptyArrayLong)); + assertTrue(ArrayUtils.isSameLength(nullArrayInt, emptyArrayInt)); + assertTrue(ArrayUtils.isSameLength(nullArrayInt, emptyArrayShort)); + assertTrue(ArrayUtils.isSameLength(nullArrayInt, emptyArrayChar)); + assertTrue(ArrayUtils.isSameLength(nullArrayInt, emptyArrayByte)); + assertTrue(ArrayUtils.isSameLength(nullArrayInt, emptyArrayDouble)); + assertTrue(ArrayUtils.isSameLength(nullArrayInt, emptyArrayFloat)); + assertTrue(ArrayUtils.isSameLength(nullArrayShort, emptyArrayObject)); + assertTrue(ArrayUtils.isSameLength(nullArrayShort, emptyArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(nullArrayShort, emptyArrayLong)); + assertTrue(ArrayUtils.isSameLength(nullArrayShort, emptyArrayInt)); + assertTrue(ArrayUtils.isSameLength(nullArrayShort, emptyArrayShort)); + assertTrue(ArrayUtils.isSameLength(nullArrayShort, emptyArrayChar)); + assertTrue(ArrayUtils.isSameLength(nullArrayShort, emptyArrayByte)); + assertTrue(ArrayUtils.isSameLength(nullArrayShort, emptyArrayDouble)); + assertTrue(ArrayUtils.isSameLength(nullArrayShort, emptyArrayFloat)); + assertTrue(ArrayUtils.isSameLength(nullArrayChar, emptyArrayObject)); + assertTrue(ArrayUtils.isSameLength(nullArrayChar, emptyArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(nullArrayChar, emptyArrayLong)); + assertTrue(ArrayUtils.isSameLength(nullArrayChar, emptyArrayInt)); + assertTrue(ArrayUtils.isSameLength(nullArrayChar, emptyArrayShort)); + assertTrue(ArrayUtils.isSameLength(nullArrayChar, emptyArrayChar)); + assertTrue(ArrayUtils.isSameLength(nullArrayChar, emptyArrayByte)); + assertTrue(ArrayUtils.isSameLength(nullArrayChar, emptyArrayDouble)); + assertTrue(ArrayUtils.isSameLength(nullArrayChar, emptyArrayFloat)); + assertTrue(ArrayUtils.isSameLength(nullArrayByte, emptyArrayObject)); + assertTrue(ArrayUtils.isSameLength(nullArrayByte, emptyArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(nullArrayByte, emptyArrayLong)); + assertTrue(ArrayUtils.isSameLength(nullArrayByte, emptyArrayInt)); + assertTrue(ArrayUtils.isSameLength(nullArrayByte, emptyArrayShort)); + assertTrue(ArrayUtils.isSameLength(nullArrayByte, emptyArrayChar)); + assertTrue(ArrayUtils.isSameLength(nullArrayByte, emptyArrayByte)); + assertTrue(ArrayUtils.isSameLength(nullArrayByte, emptyArrayDouble)); + assertTrue(ArrayUtils.isSameLength(nullArrayByte, emptyArrayFloat)); + assertTrue(ArrayUtils.isSameLength(nullArrayDouble, emptyArrayObject)); + assertTrue(ArrayUtils.isSameLength(nullArrayDouble, emptyArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(nullArrayDouble, emptyArrayLong)); + assertTrue(ArrayUtils.isSameLength(nullArrayDouble, emptyArrayInt)); + assertTrue(ArrayUtils.isSameLength(nullArrayDouble, emptyArrayShort)); + assertTrue(ArrayUtils.isSameLength(nullArrayDouble, emptyArrayChar)); + assertTrue(ArrayUtils.isSameLength(nullArrayDouble, emptyArrayByte)); + assertTrue(ArrayUtils.isSameLength(nullArrayDouble, emptyArrayDouble)); + assertTrue(ArrayUtils.isSameLength(nullArrayDouble, emptyArrayFloat)); + assertTrue(ArrayUtils.isSameLength(nullArrayFloat, emptyArrayObject)); + assertTrue(ArrayUtils.isSameLength(nullArrayFloat, emptyArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(nullArrayFloat, emptyArrayLong)); + assertTrue(ArrayUtils.isSameLength(nullArrayFloat, emptyArrayInt)); + assertTrue(ArrayUtils.isSameLength(nullArrayFloat, emptyArrayShort)); + assertTrue(ArrayUtils.isSameLength(nullArrayFloat, emptyArrayChar)); + assertTrue(ArrayUtils.isSameLength(nullArrayFloat, emptyArrayByte)); + assertTrue(ArrayUtils.isSameLength(nullArrayFloat, emptyArrayDouble)); + assertTrue(ArrayUtils.isSameLength(nullArrayFloat, emptyArrayFloat)); + assertFalse(ArrayUtils.isSameLength(nullArrayObject, oneArrayObject)); + assertFalse(ArrayUtils.isSameLength(nullArrayObject, oneArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(nullArrayObject, oneArrayLong)); + assertFalse(ArrayUtils.isSameLength(nullArrayObject, oneArrayInt)); + assertFalse(ArrayUtils.isSameLength(nullArrayObject, oneArrayShort)); + assertFalse(ArrayUtils.isSameLength(nullArrayObject, oneArrayChar)); + assertFalse(ArrayUtils.isSameLength(nullArrayObject, oneArrayByte)); + assertFalse(ArrayUtils.isSameLength(nullArrayObject, oneArrayDouble)); + assertFalse(ArrayUtils.isSameLength(nullArrayObject, oneArrayFloat)); + assertFalse(ArrayUtils.isSameLength(nullArrayBoolean, oneArrayObject)); + assertFalse(ArrayUtils.isSameLength(nullArrayBoolean, oneArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(nullArrayBoolean, oneArrayLong)); + assertFalse(ArrayUtils.isSameLength(nullArrayBoolean, oneArrayInt)); + assertFalse(ArrayUtils.isSameLength(nullArrayBoolean, oneArrayShort)); + assertFalse(ArrayUtils.isSameLength(nullArrayBoolean, oneArrayChar)); + assertFalse(ArrayUtils.isSameLength(nullArrayBoolean, oneArrayByte)); + assertFalse(ArrayUtils.isSameLength(nullArrayBoolean, oneArrayDouble)); + assertFalse(ArrayUtils.isSameLength(nullArrayBoolean, oneArrayFloat)); + assertFalse(ArrayUtils.isSameLength(nullArrayLong, oneArrayObject)); + assertFalse(ArrayUtils.isSameLength(nullArrayLong, oneArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(nullArrayLong, oneArrayLong)); + assertFalse(ArrayUtils.isSameLength(nullArrayLong, oneArrayInt)); + assertFalse(ArrayUtils.isSameLength(nullArrayLong, oneArrayShort)); + assertFalse(ArrayUtils.isSameLength(nullArrayLong, oneArrayChar)); + assertFalse(ArrayUtils.isSameLength(nullArrayLong, oneArrayByte)); + assertFalse(ArrayUtils.isSameLength(nullArrayLong, oneArrayDouble)); + assertFalse(ArrayUtils.isSameLength(nullArrayLong, oneArrayFloat)); + assertFalse(ArrayUtils.isSameLength(nullArrayInt, oneArrayObject)); + assertFalse(ArrayUtils.isSameLength(nullArrayInt, oneArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(nullArrayInt, oneArrayLong)); + assertFalse(ArrayUtils.isSameLength(nullArrayInt, oneArrayInt)); + assertFalse(ArrayUtils.isSameLength(nullArrayInt, oneArrayShort)); + assertFalse(ArrayUtils.isSameLength(nullArrayInt, oneArrayChar)); + assertFalse(ArrayUtils.isSameLength(nullArrayInt, oneArrayByte)); + assertFalse(ArrayUtils.isSameLength(nullArrayInt, oneArrayDouble)); + assertFalse(ArrayUtils.isSameLength(nullArrayInt, oneArrayFloat)); + assertFalse(ArrayUtils.isSameLength(nullArrayShort, oneArrayObject)); + assertFalse(ArrayUtils.isSameLength(nullArrayShort, oneArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(nullArrayShort, oneArrayLong)); + assertFalse(ArrayUtils.isSameLength(nullArrayShort, oneArrayInt)); + assertFalse(ArrayUtils.isSameLength(nullArrayShort, oneArrayShort)); + assertFalse(ArrayUtils.isSameLength(nullArrayShort, oneArrayChar)); + assertFalse(ArrayUtils.isSameLength(nullArrayShort, oneArrayByte)); + assertFalse(ArrayUtils.isSameLength(nullArrayShort, oneArrayDouble)); + assertFalse(ArrayUtils.isSameLength(nullArrayShort, oneArrayFloat)); + assertFalse(ArrayUtils.isSameLength(nullArrayChar, oneArrayObject)); + assertFalse(ArrayUtils.isSameLength(nullArrayChar, oneArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(nullArrayChar, oneArrayLong)); + assertFalse(ArrayUtils.isSameLength(nullArrayChar, oneArrayInt)); + assertFalse(ArrayUtils.isSameLength(nullArrayChar, oneArrayShort)); + assertFalse(ArrayUtils.isSameLength(nullArrayChar, oneArrayChar)); + assertFalse(ArrayUtils.isSameLength(nullArrayChar, oneArrayByte)); + assertFalse(ArrayUtils.isSameLength(nullArrayChar, oneArrayDouble)); + assertFalse(ArrayUtils.isSameLength(nullArrayChar, oneArrayFloat)); + assertFalse(ArrayUtils.isSameLength(nullArrayByte, oneArrayObject)); + assertFalse(ArrayUtils.isSameLength(nullArrayByte, oneArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(nullArrayByte, oneArrayLong)); + assertFalse(ArrayUtils.isSameLength(nullArrayByte, oneArrayInt)); + assertFalse(ArrayUtils.isSameLength(nullArrayByte, oneArrayShort)); + assertFalse(ArrayUtils.isSameLength(nullArrayByte, oneArrayChar)); + assertFalse(ArrayUtils.isSameLength(nullArrayByte, oneArrayByte)); + assertFalse(ArrayUtils.isSameLength(nullArrayByte, oneArrayDouble)); + assertFalse(ArrayUtils.isSameLength(nullArrayByte, oneArrayFloat)); + assertFalse(ArrayUtils.isSameLength(nullArrayDouble, oneArrayObject)); + assertFalse(ArrayUtils.isSameLength(nullArrayDouble, oneArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(nullArrayDouble, oneArrayLong)); + assertFalse(ArrayUtils.isSameLength(nullArrayDouble, oneArrayInt)); + assertFalse(ArrayUtils.isSameLength(nullArrayDouble, oneArrayShort)); + assertFalse(ArrayUtils.isSameLength(nullArrayDouble, oneArrayChar)); + assertFalse(ArrayUtils.isSameLength(nullArrayDouble, oneArrayByte)); + assertFalse(ArrayUtils.isSameLength(nullArrayDouble, oneArrayDouble)); + assertFalse(ArrayUtils.isSameLength(nullArrayDouble, oneArrayFloat)); + assertFalse(ArrayUtils.isSameLength(nullArrayFloat, oneArrayObject)); + assertFalse(ArrayUtils.isSameLength(nullArrayFloat, oneArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(nullArrayFloat, oneArrayLong)); + assertFalse(ArrayUtils.isSameLength(nullArrayFloat, oneArrayInt)); + assertFalse(ArrayUtils.isSameLength(nullArrayFloat, oneArrayShort)); + assertFalse(ArrayUtils.isSameLength(nullArrayFloat, oneArrayChar)); + assertFalse(ArrayUtils.isSameLength(nullArrayFloat, oneArrayByte)); + assertFalse(ArrayUtils.isSameLength(nullArrayFloat, oneArrayDouble)); + assertFalse(ArrayUtils.isSameLength(nullArrayFloat, oneArrayFloat)); + assertFalse(ArrayUtils.isSameLength(nullArrayObject, twoArrayObject)); + assertFalse(ArrayUtils.isSameLength(nullArrayObject, twoArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(nullArrayObject, twoArrayLong)); + assertFalse(ArrayUtils.isSameLength(nullArrayObject, twoArrayInt)); + assertFalse(ArrayUtils.isSameLength(nullArrayObject, twoArrayShort)); + assertFalse(ArrayUtils.isSameLength(nullArrayObject, twoArrayChar)); + assertFalse(ArrayUtils.isSameLength(nullArrayObject, twoArrayByte)); + assertFalse(ArrayUtils.isSameLength(nullArrayObject, twoArrayDouble)); + assertFalse(ArrayUtils.isSameLength(nullArrayObject, twoArrayFloat)); + assertFalse(ArrayUtils.isSameLength(nullArrayBoolean, twoArrayObject)); + assertFalse(ArrayUtils.isSameLength(nullArrayBoolean, twoArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(nullArrayBoolean, twoArrayLong)); + assertFalse(ArrayUtils.isSameLength(nullArrayBoolean, twoArrayInt)); + assertFalse(ArrayUtils.isSameLength(nullArrayBoolean, twoArrayShort)); + assertFalse(ArrayUtils.isSameLength(nullArrayBoolean, twoArrayChar)); + assertFalse(ArrayUtils.isSameLength(nullArrayBoolean, twoArrayByte)); + assertFalse(ArrayUtils.isSameLength(nullArrayBoolean, twoArrayDouble)); + assertFalse(ArrayUtils.isSameLength(nullArrayBoolean, twoArrayFloat)); + assertFalse(ArrayUtils.isSameLength(nullArrayLong, twoArrayObject)); + assertFalse(ArrayUtils.isSameLength(nullArrayLong, twoArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(nullArrayLong, twoArrayLong)); + assertFalse(ArrayUtils.isSameLength(nullArrayLong, twoArrayInt)); + assertFalse(ArrayUtils.isSameLength(nullArrayLong, twoArrayShort)); + assertFalse(ArrayUtils.isSameLength(nullArrayLong, twoArrayChar)); + assertFalse(ArrayUtils.isSameLength(nullArrayLong, twoArrayByte)); + assertFalse(ArrayUtils.isSameLength(nullArrayLong, twoArrayDouble)); + assertFalse(ArrayUtils.isSameLength(nullArrayLong, twoArrayFloat)); + assertFalse(ArrayUtils.isSameLength(nullArrayInt, twoArrayObject)); + assertFalse(ArrayUtils.isSameLength(nullArrayInt, twoArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(nullArrayInt, twoArrayLong)); + assertFalse(ArrayUtils.isSameLength(nullArrayInt, twoArrayInt)); + assertFalse(ArrayUtils.isSameLength(nullArrayInt, twoArrayShort)); + assertFalse(ArrayUtils.isSameLength(nullArrayInt, twoArrayChar)); + assertFalse(ArrayUtils.isSameLength(nullArrayInt, twoArrayByte)); + assertFalse(ArrayUtils.isSameLength(nullArrayInt, twoArrayDouble)); + assertFalse(ArrayUtils.isSameLength(nullArrayInt, twoArrayFloat)); + assertFalse(ArrayUtils.isSameLength(nullArrayShort, twoArrayObject)); + assertFalse(ArrayUtils.isSameLength(nullArrayShort, twoArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(nullArrayShort, twoArrayLong)); + assertFalse(ArrayUtils.isSameLength(nullArrayShort, twoArrayInt)); + assertFalse(ArrayUtils.isSameLength(nullArrayShort, twoArrayShort)); + assertFalse(ArrayUtils.isSameLength(nullArrayShort, twoArrayChar)); + assertFalse(ArrayUtils.isSameLength(nullArrayShort, twoArrayByte)); + assertFalse(ArrayUtils.isSameLength(nullArrayShort, twoArrayDouble)); + assertFalse(ArrayUtils.isSameLength(nullArrayShort, twoArrayFloat)); + assertFalse(ArrayUtils.isSameLength(nullArrayChar, twoArrayObject)); + assertFalse(ArrayUtils.isSameLength(nullArrayChar, twoArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(nullArrayChar, twoArrayLong)); + assertFalse(ArrayUtils.isSameLength(nullArrayChar, twoArrayInt)); + assertFalse(ArrayUtils.isSameLength(nullArrayChar, twoArrayShort)); + assertFalse(ArrayUtils.isSameLength(nullArrayChar, twoArrayChar)); + assertFalse(ArrayUtils.isSameLength(nullArrayChar, twoArrayByte)); + assertFalse(ArrayUtils.isSameLength(nullArrayChar, twoArrayDouble)); + assertFalse(ArrayUtils.isSameLength(nullArrayChar, twoArrayFloat)); + assertFalse(ArrayUtils.isSameLength(nullArrayByte, twoArrayObject)); + assertFalse(ArrayUtils.isSameLength(nullArrayByte, twoArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(nullArrayByte, twoArrayLong)); + assertFalse(ArrayUtils.isSameLength(nullArrayByte, twoArrayInt)); + assertFalse(ArrayUtils.isSameLength(nullArrayByte, twoArrayShort)); + assertFalse(ArrayUtils.isSameLength(nullArrayByte, twoArrayChar)); + assertFalse(ArrayUtils.isSameLength(nullArrayByte, twoArrayByte)); + assertFalse(ArrayUtils.isSameLength(nullArrayByte, twoArrayDouble)); + assertFalse(ArrayUtils.isSameLength(nullArrayByte, twoArrayFloat)); + assertFalse(ArrayUtils.isSameLength(nullArrayDouble, twoArrayObject)); + assertFalse(ArrayUtils.isSameLength(nullArrayDouble, twoArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(nullArrayDouble, twoArrayLong)); + assertFalse(ArrayUtils.isSameLength(nullArrayDouble, twoArrayInt)); + assertFalse(ArrayUtils.isSameLength(nullArrayDouble, twoArrayShort)); + assertFalse(ArrayUtils.isSameLength(nullArrayDouble, twoArrayChar)); + assertFalse(ArrayUtils.isSameLength(nullArrayDouble, twoArrayByte)); + assertFalse(ArrayUtils.isSameLength(nullArrayDouble, twoArrayDouble)); + assertFalse(ArrayUtils.isSameLength(nullArrayDouble, twoArrayFloat)); + assertFalse(ArrayUtils.isSameLength(nullArrayFloat, twoArrayObject)); + assertFalse(ArrayUtils.isSameLength(nullArrayFloat, twoArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(nullArrayFloat, twoArrayLong)); + assertFalse(ArrayUtils.isSameLength(nullArrayFloat, twoArrayInt)); + assertFalse(ArrayUtils.isSameLength(nullArrayFloat, twoArrayShort)); + assertFalse(ArrayUtils.isSameLength(nullArrayFloat, twoArrayChar)); + assertFalse(ArrayUtils.isSameLength(nullArrayFloat, twoArrayByte)); + assertFalse(ArrayUtils.isSameLength(nullArrayFloat, twoArrayDouble)); + assertFalse(ArrayUtils.isSameLength(nullArrayFloat, twoArrayFloat)); + assertTrue(ArrayUtils.isSameLength(emptyArrayObject, nullArrayObject)); + assertTrue(ArrayUtils.isSameLength(emptyArrayObject, nullArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(emptyArrayObject, nullArrayLong)); + assertTrue(ArrayUtils.isSameLength(emptyArrayObject, nullArrayInt)); + assertTrue(ArrayUtils.isSameLength(emptyArrayObject, nullArrayShort)); + assertTrue(ArrayUtils.isSameLength(emptyArrayObject, nullArrayChar)); + assertTrue(ArrayUtils.isSameLength(emptyArrayObject, nullArrayByte)); + assertTrue(ArrayUtils.isSameLength(emptyArrayObject, nullArrayDouble)); + assertTrue(ArrayUtils.isSameLength(emptyArrayObject, nullArrayFloat)); + assertTrue(ArrayUtils.isSameLength(emptyArrayBoolean, nullArrayObject)); + assertTrue(ArrayUtils.isSameLength(emptyArrayBoolean, nullArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(emptyArrayBoolean, nullArrayLong)); + assertTrue(ArrayUtils.isSameLength(emptyArrayBoolean, nullArrayInt)); + assertTrue(ArrayUtils.isSameLength(emptyArrayBoolean, nullArrayShort)); + assertTrue(ArrayUtils.isSameLength(emptyArrayBoolean, nullArrayChar)); + assertTrue(ArrayUtils.isSameLength(emptyArrayBoolean, nullArrayByte)); + assertTrue(ArrayUtils.isSameLength(emptyArrayBoolean, nullArrayDouble)); + assertTrue(ArrayUtils.isSameLength(emptyArrayBoolean, nullArrayFloat)); + assertTrue(ArrayUtils.isSameLength(emptyArrayLong, nullArrayObject)); + assertTrue(ArrayUtils.isSameLength(emptyArrayLong, nullArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(emptyArrayLong, nullArrayLong)); + assertTrue(ArrayUtils.isSameLength(emptyArrayLong, nullArrayInt)); + assertTrue(ArrayUtils.isSameLength(emptyArrayLong, nullArrayShort)); + assertTrue(ArrayUtils.isSameLength(emptyArrayLong, nullArrayChar)); + assertTrue(ArrayUtils.isSameLength(emptyArrayLong, nullArrayByte)); + assertTrue(ArrayUtils.isSameLength(emptyArrayLong, nullArrayDouble)); + assertTrue(ArrayUtils.isSameLength(emptyArrayLong, nullArrayFloat)); + assertTrue(ArrayUtils.isSameLength(emptyArrayInt, nullArrayObject)); + assertTrue(ArrayUtils.isSameLength(emptyArrayInt, nullArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(emptyArrayInt, nullArrayLong)); + assertTrue(ArrayUtils.isSameLength(emptyArrayInt, nullArrayInt)); + assertTrue(ArrayUtils.isSameLength(emptyArrayInt, nullArrayShort)); + assertTrue(ArrayUtils.isSameLength(emptyArrayInt, nullArrayChar)); + assertTrue(ArrayUtils.isSameLength(emptyArrayInt, nullArrayByte)); + assertTrue(ArrayUtils.isSameLength(emptyArrayInt, nullArrayDouble)); + assertTrue(ArrayUtils.isSameLength(emptyArrayInt, nullArrayFloat)); + assertTrue(ArrayUtils.isSameLength(emptyArrayShort, nullArrayObject)); + assertTrue(ArrayUtils.isSameLength(emptyArrayShort, nullArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(emptyArrayShort, nullArrayLong)); + assertTrue(ArrayUtils.isSameLength(emptyArrayShort, nullArrayInt)); + assertTrue(ArrayUtils.isSameLength(emptyArrayShort, nullArrayShort)); + assertTrue(ArrayUtils.isSameLength(emptyArrayShort, nullArrayChar)); + assertTrue(ArrayUtils.isSameLength(emptyArrayShort, nullArrayByte)); + assertTrue(ArrayUtils.isSameLength(emptyArrayShort, nullArrayDouble)); + assertTrue(ArrayUtils.isSameLength(emptyArrayShort, nullArrayFloat)); + assertTrue(ArrayUtils.isSameLength(emptyArrayChar, nullArrayObject)); + assertTrue(ArrayUtils.isSameLength(emptyArrayChar, nullArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(emptyArrayChar, nullArrayLong)); + assertTrue(ArrayUtils.isSameLength(emptyArrayChar, nullArrayInt)); + assertTrue(ArrayUtils.isSameLength(emptyArrayChar, nullArrayShort)); + assertTrue(ArrayUtils.isSameLength(emptyArrayChar, nullArrayChar)); + assertTrue(ArrayUtils.isSameLength(emptyArrayChar, nullArrayByte)); + assertTrue(ArrayUtils.isSameLength(emptyArrayChar, nullArrayDouble)); + assertTrue(ArrayUtils.isSameLength(emptyArrayChar, nullArrayFloat)); + assertTrue(ArrayUtils.isSameLength(emptyArrayByte, nullArrayObject)); + assertTrue(ArrayUtils.isSameLength(emptyArrayByte, nullArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(emptyArrayByte, nullArrayLong)); + assertTrue(ArrayUtils.isSameLength(emptyArrayByte, nullArrayInt)); + assertTrue(ArrayUtils.isSameLength(emptyArrayByte, nullArrayShort)); + assertTrue(ArrayUtils.isSameLength(emptyArrayByte, nullArrayChar)); + assertTrue(ArrayUtils.isSameLength(emptyArrayByte, nullArrayByte)); + assertTrue(ArrayUtils.isSameLength(emptyArrayByte, nullArrayDouble)); + assertTrue(ArrayUtils.isSameLength(emptyArrayByte, nullArrayFloat)); + assertTrue(ArrayUtils.isSameLength(emptyArrayDouble, nullArrayObject)); + assertTrue(ArrayUtils.isSameLength(emptyArrayDouble, nullArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(emptyArrayDouble, nullArrayLong)); + assertTrue(ArrayUtils.isSameLength(emptyArrayDouble, nullArrayInt)); + assertTrue(ArrayUtils.isSameLength(emptyArrayDouble, nullArrayShort)); + assertTrue(ArrayUtils.isSameLength(emptyArrayDouble, nullArrayChar)); + assertTrue(ArrayUtils.isSameLength(emptyArrayDouble, nullArrayByte)); + assertTrue(ArrayUtils.isSameLength(emptyArrayDouble, nullArrayDouble)); + assertTrue(ArrayUtils.isSameLength(emptyArrayDouble, nullArrayFloat)); + assertTrue(ArrayUtils.isSameLength(emptyArrayFloat, nullArrayObject)); + assertTrue(ArrayUtils.isSameLength(emptyArrayFloat, nullArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(emptyArrayFloat, nullArrayLong)); + assertTrue(ArrayUtils.isSameLength(emptyArrayFloat, nullArrayInt)); + assertTrue(ArrayUtils.isSameLength(emptyArrayFloat, nullArrayShort)); + assertTrue(ArrayUtils.isSameLength(emptyArrayFloat, nullArrayChar)); + assertTrue(ArrayUtils.isSameLength(emptyArrayFloat, nullArrayByte)); + assertTrue(ArrayUtils.isSameLength(emptyArrayFloat, nullArrayDouble)); + assertTrue(ArrayUtils.isSameLength(emptyArrayFloat, nullArrayFloat)); + assertTrue(ArrayUtils.isSameLength(emptyArrayObject, emptyArrayObject)); + assertTrue(ArrayUtils.isSameLength(emptyArrayObject, emptyArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(emptyArrayObject, emptyArrayLong)); + assertTrue(ArrayUtils.isSameLength(emptyArrayObject, emptyArrayInt)); + assertTrue(ArrayUtils.isSameLength(emptyArrayObject, emptyArrayShort)); + assertTrue(ArrayUtils.isSameLength(emptyArrayObject, emptyArrayChar)); + assertTrue(ArrayUtils.isSameLength(emptyArrayObject, emptyArrayByte)); + assertTrue(ArrayUtils.isSameLength(emptyArrayObject, emptyArrayDouble)); + assertTrue(ArrayUtils.isSameLength(emptyArrayObject, emptyArrayFloat)); + assertTrue(ArrayUtils.isSameLength(emptyArrayBoolean, emptyArrayObject)); + assertTrue(ArrayUtils.isSameLength(emptyArrayBoolean, emptyArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(emptyArrayBoolean, emptyArrayLong)); + assertTrue(ArrayUtils.isSameLength(emptyArrayBoolean, emptyArrayInt)); + assertTrue(ArrayUtils.isSameLength(emptyArrayBoolean, emptyArrayShort)); + assertTrue(ArrayUtils.isSameLength(emptyArrayBoolean, emptyArrayChar)); + assertTrue(ArrayUtils.isSameLength(emptyArrayBoolean, emptyArrayByte)); + assertTrue(ArrayUtils.isSameLength(emptyArrayBoolean, emptyArrayDouble)); + assertTrue(ArrayUtils.isSameLength(emptyArrayBoolean, emptyArrayFloat)); + assertTrue(ArrayUtils.isSameLength(emptyArrayLong, emptyArrayObject)); + assertTrue(ArrayUtils.isSameLength(emptyArrayLong, emptyArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(emptyArrayLong, emptyArrayLong)); + assertTrue(ArrayUtils.isSameLength(emptyArrayLong, emptyArrayInt)); + assertTrue(ArrayUtils.isSameLength(emptyArrayLong, emptyArrayShort)); + assertTrue(ArrayUtils.isSameLength(emptyArrayLong, emptyArrayChar)); + assertTrue(ArrayUtils.isSameLength(emptyArrayLong, emptyArrayByte)); + assertTrue(ArrayUtils.isSameLength(emptyArrayLong, emptyArrayDouble)); + assertTrue(ArrayUtils.isSameLength(emptyArrayLong, emptyArrayFloat)); + assertTrue(ArrayUtils.isSameLength(emptyArrayInt, emptyArrayObject)); + assertTrue(ArrayUtils.isSameLength(emptyArrayInt, emptyArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(emptyArrayInt, emptyArrayLong)); + assertTrue(ArrayUtils.isSameLength(emptyArrayInt, emptyArrayInt)); + assertTrue(ArrayUtils.isSameLength(emptyArrayInt, emptyArrayShort)); + assertTrue(ArrayUtils.isSameLength(emptyArrayInt, emptyArrayChar)); + assertTrue(ArrayUtils.isSameLength(emptyArrayInt, emptyArrayByte)); + assertTrue(ArrayUtils.isSameLength(emptyArrayInt, emptyArrayDouble)); + assertTrue(ArrayUtils.isSameLength(emptyArrayInt, emptyArrayFloat)); + assertTrue(ArrayUtils.isSameLength(emptyArrayShort, emptyArrayObject)); + assertTrue(ArrayUtils.isSameLength(emptyArrayShort, emptyArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(emptyArrayShort, emptyArrayLong)); + assertTrue(ArrayUtils.isSameLength(emptyArrayShort, emptyArrayInt)); + assertTrue(ArrayUtils.isSameLength(emptyArrayShort, emptyArrayShort)); + assertTrue(ArrayUtils.isSameLength(emptyArrayShort, emptyArrayChar)); + assertTrue(ArrayUtils.isSameLength(emptyArrayShort, emptyArrayByte)); + assertTrue(ArrayUtils.isSameLength(emptyArrayShort, emptyArrayDouble)); + assertTrue(ArrayUtils.isSameLength(emptyArrayShort, emptyArrayFloat)); + assertTrue(ArrayUtils.isSameLength(emptyArrayChar, emptyArrayObject)); + assertTrue(ArrayUtils.isSameLength(emptyArrayChar, emptyArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(emptyArrayChar, emptyArrayLong)); + assertTrue(ArrayUtils.isSameLength(emptyArrayChar, emptyArrayInt)); + assertTrue(ArrayUtils.isSameLength(emptyArrayChar, emptyArrayShort)); + assertTrue(ArrayUtils.isSameLength(emptyArrayChar, emptyArrayChar)); + assertTrue(ArrayUtils.isSameLength(emptyArrayChar, emptyArrayByte)); + assertTrue(ArrayUtils.isSameLength(emptyArrayChar, emptyArrayDouble)); + assertTrue(ArrayUtils.isSameLength(emptyArrayChar, emptyArrayFloat)); + assertTrue(ArrayUtils.isSameLength(emptyArrayByte, emptyArrayObject)); + assertTrue(ArrayUtils.isSameLength(emptyArrayByte, emptyArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(emptyArrayByte, emptyArrayLong)); + assertTrue(ArrayUtils.isSameLength(emptyArrayByte, emptyArrayInt)); + assertTrue(ArrayUtils.isSameLength(emptyArrayByte, emptyArrayShort)); + assertTrue(ArrayUtils.isSameLength(emptyArrayByte, emptyArrayChar)); + assertTrue(ArrayUtils.isSameLength(emptyArrayByte, emptyArrayByte)); + assertTrue(ArrayUtils.isSameLength(emptyArrayByte, emptyArrayDouble)); + assertTrue(ArrayUtils.isSameLength(emptyArrayByte, emptyArrayFloat)); + assertTrue(ArrayUtils.isSameLength(emptyArrayDouble, emptyArrayObject)); + assertTrue(ArrayUtils.isSameLength(emptyArrayDouble, emptyArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(emptyArrayDouble, emptyArrayLong)); + assertTrue(ArrayUtils.isSameLength(emptyArrayDouble, emptyArrayInt)); + assertTrue(ArrayUtils.isSameLength(emptyArrayDouble, emptyArrayShort)); + assertTrue(ArrayUtils.isSameLength(emptyArrayDouble, emptyArrayChar)); + assertTrue(ArrayUtils.isSameLength(emptyArrayDouble, emptyArrayByte)); + assertTrue(ArrayUtils.isSameLength(emptyArrayDouble, emptyArrayDouble)); + assertTrue(ArrayUtils.isSameLength(emptyArrayDouble, emptyArrayFloat)); + assertTrue(ArrayUtils.isSameLength(emptyArrayFloat, emptyArrayObject)); + assertTrue(ArrayUtils.isSameLength(emptyArrayFloat, emptyArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(emptyArrayFloat, emptyArrayLong)); + assertTrue(ArrayUtils.isSameLength(emptyArrayFloat, emptyArrayInt)); + assertTrue(ArrayUtils.isSameLength(emptyArrayFloat, emptyArrayShort)); + assertTrue(ArrayUtils.isSameLength(emptyArrayFloat, emptyArrayChar)); + assertTrue(ArrayUtils.isSameLength(emptyArrayFloat, emptyArrayByte)); + assertTrue(ArrayUtils.isSameLength(emptyArrayFloat, emptyArrayDouble)); + assertTrue(ArrayUtils.isSameLength(emptyArrayFloat, emptyArrayFloat)); + assertFalse(ArrayUtils.isSameLength(emptyArrayObject, oneArrayObject)); + assertFalse(ArrayUtils.isSameLength(emptyArrayObject, oneArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(emptyArrayObject, oneArrayLong)); + assertFalse(ArrayUtils.isSameLength(emptyArrayObject, oneArrayInt)); + assertFalse(ArrayUtils.isSameLength(emptyArrayObject, oneArrayShort)); + assertFalse(ArrayUtils.isSameLength(emptyArrayObject, oneArrayChar)); + assertFalse(ArrayUtils.isSameLength(emptyArrayObject, oneArrayByte)); + assertFalse(ArrayUtils.isSameLength(emptyArrayObject, oneArrayDouble)); + assertFalse(ArrayUtils.isSameLength(emptyArrayObject, oneArrayFloat)); + assertFalse(ArrayUtils.isSameLength(emptyArrayBoolean, oneArrayObject)); + assertFalse(ArrayUtils.isSameLength(emptyArrayBoolean, oneArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(emptyArrayBoolean, oneArrayLong)); + assertFalse(ArrayUtils.isSameLength(emptyArrayBoolean, oneArrayInt)); + assertFalse(ArrayUtils.isSameLength(emptyArrayBoolean, oneArrayShort)); + assertFalse(ArrayUtils.isSameLength(emptyArrayBoolean, oneArrayChar)); + assertFalse(ArrayUtils.isSameLength(emptyArrayBoolean, oneArrayByte)); + assertFalse(ArrayUtils.isSameLength(emptyArrayBoolean, oneArrayDouble)); + assertFalse(ArrayUtils.isSameLength(emptyArrayBoolean, oneArrayFloat)); + assertFalse(ArrayUtils.isSameLength(emptyArrayLong, oneArrayObject)); + assertFalse(ArrayUtils.isSameLength(emptyArrayLong, oneArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(emptyArrayLong, oneArrayLong)); + assertFalse(ArrayUtils.isSameLength(emptyArrayLong, oneArrayInt)); + assertFalse(ArrayUtils.isSameLength(emptyArrayLong, oneArrayShort)); + assertFalse(ArrayUtils.isSameLength(emptyArrayLong, oneArrayChar)); + assertFalse(ArrayUtils.isSameLength(emptyArrayLong, oneArrayByte)); + assertFalse(ArrayUtils.isSameLength(emptyArrayLong, oneArrayDouble)); + assertFalse(ArrayUtils.isSameLength(emptyArrayLong, oneArrayFloat)); + assertFalse(ArrayUtils.isSameLength(emptyArrayInt, oneArrayObject)); + assertFalse(ArrayUtils.isSameLength(emptyArrayInt, oneArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(emptyArrayInt, oneArrayLong)); + assertFalse(ArrayUtils.isSameLength(emptyArrayInt, oneArrayInt)); + assertFalse(ArrayUtils.isSameLength(emptyArrayInt, oneArrayShort)); + assertFalse(ArrayUtils.isSameLength(emptyArrayInt, oneArrayChar)); + assertFalse(ArrayUtils.isSameLength(emptyArrayInt, oneArrayByte)); + assertFalse(ArrayUtils.isSameLength(emptyArrayInt, oneArrayDouble)); + assertFalse(ArrayUtils.isSameLength(emptyArrayInt, oneArrayFloat)); + assertFalse(ArrayUtils.isSameLength(emptyArrayShort, oneArrayObject)); + assertFalse(ArrayUtils.isSameLength(emptyArrayShort, oneArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(emptyArrayShort, oneArrayLong)); + assertFalse(ArrayUtils.isSameLength(emptyArrayShort, oneArrayInt)); + assertFalse(ArrayUtils.isSameLength(emptyArrayShort, oneArrayShort)); + assertFalse(ArrayUtils.isSameLength(emptyArrayShort, oneArrayChar)); + assertFalse(ArrayUtils.isSameLength(emptyArrayShort, oneArrayByte)); + assertFalse(ArrayUtils.isSameLength(emptyArrayShort, oneArrayDouble)); + assertFalse(ArrayUtils.isSameLength(emptyArrayShort, oneArrayFloat)); + assertFalse(ArrayUtils.isSameLength(emptyArrayChar, oneArrayObject)); + assertFalse(ArrayUtils.isSameLength(emptyArrayChar, oneArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(emptyArrayChar, oneArrayLong)); + assertFalse(ArrayUtils.isSameLength(emptyArrayChar, oneArrayInt)); + assertFalse(ArrayUtils.isSameLength(emptyArrayChar, oneArrayShort)); + assertFalse(ArrayUtils.isSameLength(emptyArrayChar, oneArrayChar)); + assertFalse(ArrayUtils.isSameLength(emptyArrayChar, oneArrayByte)); + assertFalse(ArrayUtils.isSameLength(emptyArrayChar, oneArrayDouble)); + assertFalse(ArrayUtils.isSameLength(emptyArrayChar, oneArrayFloat)); + assertFalse(ArrayUtils.isSameLength(emptyArrayByte, oneArrayObject)); + assertFalse(ArrayUtils.isSameLength(emptyArrayByte, oneArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(emptyArrayByte, oneArrayLong)); + assertFalse(ArrayUtils.isSameLength(emptyArrayByte, oneArrayInt)); + assertFalse(ArrayUtils.isSameLength(emptyArrayByte, oneArrayShort)); + assertFalse(ArrayUtils.isSameLength(emptyArrayByte, oneArrayChar)); + assertFalse(ArrayUtils.isSameLength(emptyArrayByte, oneArrayByte)); + assertFalse(ArrayUtils.isSameLength(emptyArrayByte, oneArrayDouble)); + assertFalse(ArrayUtils.isSameLength(emptyArrayByte, oneArrayFloat)); + assertFalse(ArrayUtils.isSameLength(emptyArrayDouble, oneArrayObject)); + assertFalse(ArrayUtils.isSameLength(emptyArrayDouble, oneArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(emptyArrayDouble, oneArrayLong)); + assertFalse(ArrayUtils.isSameLength(emptyArrayDouble, oneArrayInt)); + assertFalse(ArrayUtils.isSameLength(emptyArrayDouble, oneArrayShort)); + assertFalse(ArrayUtils.isSameLength(emptyArrayDouble, oneArrayChar)); + assertFalse(ArrayUtils.isSameLength(emptyArrayDouble, oneArrayByte)); + assertFalse(ArrayUtils.isSameLength(emptyArrayDouble, oneArrayDouble)); + assertFalse(ArrayUtils.isSameLength(emptyArrayDouble, oneArrayFloat)); + assertFalse(ArrayUtils.isSameLength(emptyArrayFloat, oneArrayObject)); + assertFalse(ArrayUtils.isSameLength(emptyArrayFloat, oneArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(emptyArrayFloat, oneArrayLong)); + assertFalse(ArrayUtils.isSameLength(emptyArrayFloat, oneArrayInt)); + assertFalse(ArrayUtils.isSameLength(emptyArrayFloat, oneArrayShort)); + assertFalse(ArrayUtils.isSameLength(emptyArrayFloat, oneArrayChar)); + assertFalse(ArrayUtils.isSameLength(emptyArrayFloat, oneArrayByte)); + assertFalse(ArrayUtils.isSameLength(emptyArrayFloat, oneArrayDouble)); + assertFalse(ArrayUtils.isSameLength(emptyArrayFloat, oneArrayFloat)); + assertFalse(ArrayUtils.isSameLength(emptyArrayObject, twoArrayObject)); + assertFalse(ArrayUtils.isSameLength(emptyArrayObject, twoArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(emptyArrayObject, twoArrayLong)); + assertFalse(ArrayUtils.isSameLength(emptyArrayObject, twoArrayInt)); + assertFalse(ArrayUtils.isSameLength(emptyArrayObject, twoArrayShort)); + assertFalse(ArrayUtils.isSameLength(emptyArrayObject, twoArrayChar)); + assertFalse(ArrayUtils.isSameLength(emptyArrayObject, twoArrayByte)); + assertFalse(ArrayUtils.isSameLength(emptyArrayObject, twoArrayDouble)); + assertFalse(ArrayUtils.isSameLength(emptyArrayObject, twoArrayFloat)); + assertFalse(ArrayUtils.isSameLength(emptyArrayBoolean, twoArrayObject)); + assertFalse(ArrayUtils.isSameLength(emptyArrayBoolean, twoArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(emptyArrayBoolean, twoArrayLong)); + assertFalse(ArrayUtils.isSameLength(emptyArrayBoolean, twoArrayInt)); + assertFalse(ArrayUtils.isSameLength(emptyArrayBoolean, twoArrayShort)); + assertFalse(ArrayUtils.isSameLength(emptyArrayBoolean, twoArrayChar)); + assertFalse(ArrayUtils.isSameLength(emptyArrayBoolean, twoArrayByte)); + assertFalse(ArrayUtils.isSameLength(emptyArrayBoolean, twoArrayDouble)); + assertFalse(ArrayUtils.isSameLength(emptyArrayBoolean, twoArrayFloat)); + assertFalse(ArrayUtils.isSameLength(emptyArrayLong, twoArrayObject)); + assertFalse(ArrayUtils.isSameLength(emptyArrayLong, twoArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(emptyArrayLong, twoArrayLong)); + assertFalse(ArrayUtils.isSameLength(emptyArrayLong, twoArrayInt)); + assertFalse(ArrayUtils.isSameLength(emptyArrayLong, twoArrayShort)); + assertFalse(ArrayUtils.isSameLength(emptyArrayLong, twoArrayChar)); + assertFalse(ArrayUtils.isSameLength(emptyArrayLong, twoArrayByte)); + assertFalse(ArrayUtils.isSameLength(emptyArrayLong, twoArrayDouble)); + assertFalse(ArrayUtils.isSameLength(emptyArrayLong, twoArrayFloat)); + assertFalse(ArrayUtils.isSameLength(emptyArrayInt, twoArrayObject)); + assertFalse(ArrayUtils.isSameLength(emptyArrayInt, twoArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(emptyArrayInt, twoArrayLong)); + assertFalse(ArrayUtils.isSameLength(emptyArrayInt, twoArrayInt)); + assertFalse(ArrayUtils.isSameLength(emptyArrayInt, twoArrayShort)); + assertFalse(ArrayUtils.isSameLength(emptyArrayInt, twoArrayChar)); + assertFalse(ArrayUtils.isSameLength(emptyArrayInt, twoArrayByte)); + assertFalse(ArrayUtils.isSameLength(emptyArrayInt, twoArrayDouble)); + assertFalse(ArrayUtils.isSameLength(emptyArrayInt, twoArrayFloat)); + assertFalse(ArrayUtils.isSameLength(emptyArrayShort, twoArrayObject)); + assertFalse(ArrayUtils.isSameLength(emptyArrayShort, twoArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(emptyArrayShort, twoArrayLong)); + assertFalse(ArrayUtils.isSameLength(emptyArrayShort, twoArrayInt)); + assertFalse(ArrayUtils.isSameLength(emptyArrayShort, twoArrayShort)); + assertFalse(ArrayUtils.isSameLength(emptyArrayShort, twoArrayChar)); + assertFalse(ArrayUtils.isSameLength(emptyArrayShort, twoArrayByte)); + assertFalse(ArrayUtils.isSameLength(emptyArrayShort, twoArrayDouble)); + assertFalse(ArrayUtils.isSameLength(emptyArrayShort, twoArrayFloat)); + assertFalse(ArrayUtils.isSameLength(emptyArrayChar, twoArrayObject)); + assertFalse(ArrayUtils.isSameLength(emptyArrayChar, twoArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(emptyArrayChar, twoArrayLong)); + assertFalse(ArrayUtils.isSameLength(emptyArrayChar, twoArrayInt)); + assertFalse(ArrayUtils.isSameLength(emptyArrayChar, twoArrayShort)); + assertFalse(ArrayUtils.isSameLength(emptyArrayChar, twoArrayChar)); + assertFalse(ArrayUtils.isSameLength(emptyArrayChar, twoArrayByte)); + assertFalse(ArrayUtils.isSameLength(emptyArrayChar, twoArrayDouble)); + assertFalse(ArrayUtils.isSameLength(emptyArrayChar, twoArrayFloat)); + assertFalse(ArrayUtils.isSameLength(emptyArrayByte, twoArrayObject)); + assertFalse(ArrayUtils.isSameLength(emptyArrayByte, twoArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(emptyArrayByte, twoArrayLong)); + assertFalse(ArrayUtils.isSameLength(emptyArrayByte, twoArrayInt)); + assertFalse(ArrayUtils.isSameLength(emptyArrayByte, twoArrayShort)); + assertFalse(ArrayUtils.isSameLength(emptyArrayByte, twoArrayChar)); + assertFalse(ArrayUtils.isSameLength(emptyArrayByte, twoArrayByte)); + assertFalse(ArrayUtils.isSameLength(emptyArrayByte, twoArrayDouble)); + assertFalse(ArrayUtils.isSameLength(emptyArrayByte, twoArrayFloat)); + assertFalse(ArrayUtils.isSameLength(emptyArrayDouble, twoArrayObject)); + assertFalse(ArrayUtils.isSameLength(emptyArrayDouble, twoArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(emptyArrayDouble, twoArrayLong)); + assertFalse(ArrayUtils.isSameLength(emptyArrayDouble, twoArrayInt)); + assertFalse(ArrayUtils.isSameLength(emptyArrayDouble, twoArrayShort)); + assertFalse(ArrayUtils.isSameLength(emptyArrayDouble, twoArrayChar)); + assertFalse(ArrayUtils.isSameLength(emptyArrayDouble, twoArrayByte)); + assertFalse(ArrayUtils.isSameLength(emptyArrayDouble, twoArrayDouble)); + assertFalse(ArrayUtils.isSameLength(emptyArrayDouble, twoArrayFloat)); + assertFalse(ArrayUtils.isSameLength(emptyArrayFloat, twoArrayObject)); + assertFalse(ArrayUtils.isSameLength(emptyArrayFloat, twoArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(emptyArrayFloat, twoArrayLong)); + assertFalse(ArrayUtils.isSameLength(emptyArrayFloat, twoArrayInt)); + assertFalse(ArrayUtils.isSameLength(emptyArrayFloat, twoArrayShort)); + assertFalse(ArrayUtils.isSameLength(emptyArrayFloat, twoArrayChar)); + assertFalse(ArrayUtils.isSameLength(emptyArrayFloat, twoArrayByte)); + assertFalse(ArrayUtils.isSameLength(emptyArrayFloat, twoArrayDouble)); + assertFalse(ArrayUtils.isSameLength(emptyArrayFloat, twoArrayFloat)); + assertFalse(ArrayUtils.isSameLength(oneArrayObject, nullArrayObject)); + assertFalse(ArrayUtils.isSameLength(oneArrayObject, nullArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(oneArrayObject, nullArrayLong)); + assertFalse(ArrayUtils.isSameLength(oneArrayObject, nullArrayInt)); + assertFalse(ArrayUtils.isSameLength(oneArrayObject, nullArrayShort)); + assertFalse(ArrayUtils.isSameLength(oneArrayObject, nullArrayChar)); + assertFalse(ArrayUtils.isSameLength(oneArrayObject, nullArrayByte)); + assertFalse(ArrayUtils.isSameLength(oneArrayObject, nullArrayDouble)); + assertFalse(ArrayUtils.isSameLength(oneArrayObject, nullArrayFloat)); + assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, nullArrayObject)); + assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, nullArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, nullArrayLong)); + assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, nullArrayInt)); + assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, nullArrayShort)); + assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, nullArrayChar)); + assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, nullArrayByte)); + assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, nullArrayDouble)); + assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, nullArrayFloat)); + assertFalse(ArrayUtils.isSameLength(oneArrayLong, nullArrayObject)); + assertFalse(ArrayUtils.isSameLength(oneArrayLong, nullArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(oneArrayLong, nullArrayLong)); + assertFalse(ArrayUtils.isSameLength(oneArrayLong, nullArrayInt)); + assertFalse(ArrayUtils.isSameLength(oneArrayLong, nullArrayShort)); + assertFalse(ArrayUtils.isSameLength(oneArrayLong, nullArrayChar)); + assertFalse(ArrayUtils.isSameLength(oneArrayLong, nullArrayByte)); + assertFalse(ArrayUtils.isSameLength(oneArrayLong, nullArrayDouble)); + assertFalse(ArrayUtils.isSameLength(oneArrayLong, nullArrayFloat)); + assertFalse(ArrayUtils.isSameLength(oneArrayInt, nullArrayObject)); + assertFalse(ArrayUtils.isSameLength(oneArrayInt, nullArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(oneArrayInt, nullArrayLong)); + assertFalse(ArrayUtils.isSameLength(oneArrayInt, nullArrayInt)); + assertFalse(ArrayUtils.isSameLength(oneArrayInt, nullArrayShort)); + assertFalse(ArrayUtils.isSameLength(oneArrayInt, nullArrayChar)); + assertFalse(ArrayUtils.isSameLength(oneArrayInt, nullArrayByte)); + assertFalse(ArrayUtils.isSameLength(oneArrayInt, nullArrayDouble)); + assertFalse(ArrayUtils.isSameLength(oneArrayInt, nullArrayFloat)); + assertFalse(ArrayUtils.isSameLength(oneArrayShort, nullArrayObject)); + assertFalse(ArrayUtils.isSameLength(oneArrayShort, nullArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(oneArrayShort, nullArrayLong)); + assertFalse(ArrayUtils.isSameLength(oneArrayShort, nullArrayInt)); + assertFalse(ArrayUtils.isSameLength(oneArrayShort, nullArrayShort)); + assertFalse(ArrayUtils.isSameLength(oneArrayShort, nullArrayChar)); + assertFalse(ArrayUtils.isSameLength(oneArrayShort, nullArrayByte)); + assertFalse(ArrayUtils.isSameLength(oneArrayShort, nullArrayDouble)); + assertFalse(ArrayUtils.isSameLength(oneArrayShort, nullArrayFloat)); + assertFalse(ArrayUtils.isSameLength(oneArrayChar, nullArrayObject)); + assertFalse(ArrayUtils.isSameLength(oneArrayChar, nullArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(oneArrayChar, nullArrayLong)); + assertFalse(ArrayUtils.isSameLength(oneArrayChar, nullArrayInt)); + assertFalse(ArrayUtils.isSameLength(oneArrayChar, nullArrayShort)); + assertFalse(ArrayUtils.isSameLength(oneArrayChar, nullArrayChar)); + assertFalse(ArrayUtils.isSameLength(oneArrayChar, nullArrayByte)); + assertFalse(ArrayUtils.isSameLength(oneArrayChar, nullArrayDouble)); + assertFalse(ArrayUtils.isSameLength(oneArrayChar, nullArrayFloat)); + assertFalse(ArrayUtils.isSameLength(oneArrayByte, nullArrayObject)); + assertFalse(ArrayUtils.isSameLength(oneArrayByte, nullArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(oneArrayByte, nullArrayLong)); + assertFalse(ArrayUtils.isSameLength(oneArrayByte, nullArrayInt)); + assertFalse(ArrayUtils.isSameLength(oneArrayByte, nullArrayShort)); + assertFalse(ArrayUtils.isSameLength(oneArrayByte, nullArrayChar)); + assertFalse(ArrayUtils.isSameLength(oneArrayByte, nullArrayByte)); + assertFalse(ArrayUtils.isSameLength(oneArrayByte, nullArrayDouble)); + assertFalse(ArrayUtils.isSameLength(oneArrayByte, nullArrayFloat)); + assertFalse(ArrayUtils.isSameLength(oneArrayDouble, nullArrayObject)); + assertFalse(ArrayUtils.isSameLength(oneArrayDouble, nullArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(oneArrayDouble, nullArrayLong)); + assertFalse(ArrayUtils.isSameLength(oneArrayDouble, nullArrayInt)); + assertFalse(ArrayUtils.isSameLength(oneArrayDouble, nullArrayShort)); + assertFalse(ArrayUtils.isSameLength(oneArrayDouble, nullArrayChar)); + assertFalse(ArrayUtils.isSameLength(oneArrayDouble, nullArrayByte)); + assertFalse(ArrayUtils.isSameLength(oneArrayDouble, nullArrayDouble)); + assertFalse(ArrayUtils.isSameLength(oneArrayDouble, nullArrayFloat)); + assertFalse(ArrayUtils.isSameLength(oneArrayFloat, nullArrayObject)); + assertFalse(ArrayUtils.isSameLength(oneArrayFloat, nullArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(oneArrayFloat, nullArrayLong)); + assertFalse(ArrayUtils.isSameLength(oneArrayFloat, nullArrayInt)); + assertFalse(ArrayUtils.isSameLength(oneArrayFloat, nullArrayShort)); + assertFalse(ArrayUtils.isSameLength(oneArrayFloat, nullArrayChar)); + assertFalse(ArrayUtils.isSameLength(oneArrayFloat, nullArrayByte)); + assertFalse(ArrayUtils.isSameLength(oneArrayFloat, nullArrayDouble)); + assertFalse(ArrayUtils.isSameLength(oneArrayFloat, nullArrayFloat)); + assertFalse(ArrayUtils.isSameLength(oneArrayObject, emptyArrayObject)); + assertFalse(ArrayUtils.isSameLength(oneArrayObject, emptyArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(oneArrayObject, emptyArrayLong)); + assertFalse(ArrayUtils.isSameLength(oneArrayObject, emptyArrayInt)); + assertFalse(ArrayUtils.isSameLength(oneArrayObject, emptyArrayShort)); + assertFalse(ArrayUtils.isSameLength(oneArrayObject, emptyArrayChar)); + assertFalse(ArrayUtils.isSameLength(oneArrayObject, emptyArrayByte)); + assertFalse(ArrayUtils.isSameLength(oneArrayObject, emptyArrayDouble)); + assertFalse(ArrayUtils.isSameLength(oneArrayObject, emptyArrayFloat)); + assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, emptyArrayObject)); + assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, emptyArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, emptyArrayLong)); + assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, emptyArrayInt)); + assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, emptyArrayShort)); + assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, emptyArrayChar)); + assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, emptyArrayByte)); + assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, emptyArrayDouble)); + assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, emptyArrayFloat)); + assertFalse(ArrayUtils.isSameLength(oneArrayLong, emptyArrayObject)); + assertFalse(ArrayUtils.isSameLength(oneArrayLong, emptyArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(oneArrayLong, emptyArrayLong)); + assertFalse(ArrayUtils.isSameLength(oneArrayLong, emptyArrayInt)); + assertFalse(ArrayUtils.isSameLength(oneArrayLong, emptyArrayShort)); + assertFalse(ArrayUtils.isSameLength(oneArrayLong, emptyArrayChar)); + assertFalse(ArrayUtils.isSameLength(oneArrayLong, emptyArrayByte)); + assertFalse(ArrayUtils.isSameLength(oneArrayLong, emptyArrayDouble)); + assertFalse(ArrayUtils.isSameLength(oneArrayLong, emptyArrayFloat)); + assertFalse(ArrayUtils.isSameLength(oneArrayInt, emptyArrayObject)); + assertFalse(ArrayUtils.isSameLength(oneArrayInt, emptyArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(oneArrayInt, emptyArrayLong)); + assertFalse(ArrayUtils.isSameLength(oneArrayInt, emptyArrayInt)); + assertFalse(ArrayUtils.isSameLength(oneArrayInt, emptyArrayShort)); + assertFalse(ArrayUtils.isSameLength(oneArrayInt, emptyArrayChar)); + assertFalse(ArrayUtils.isSameLength(oneArrayInt, emptyArrayByte)); + assertFalse(ArrayUtils.isSameLength(oneArrayInt, emptyArrayDouble)); + assertFalse(ArrayUtils.isSameLength(oneArrayInt, emptyArrayFloat)); + assertFalse(ArrayUtils.isSameLength(oneArrayShort, emptyArrayObject)); + assertFalse(ArrayUtils.isSameLength(oneArrayShort, emptyArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(oneArrayShort, emptyArrayLong)); + assertFalse(ArrayUtils.isSameLength(oneArrayShort, emptyArrayInt)); + assertFalse(ArrayUtils.isSameLength(oneArrayShort, emptyArrayShort)); + assertFalse(ArrayUtils.isSameLength(oneArrayShort, emptyArrayChar)); + assertFalse(ArrayUtils.isSameLength(oneArrayShort, emptyArrayByte)); + assertFalse(ArrayUtils.isSameLength(oneArrayShort, emptyArrayDouble)); + assertFalse(ArrayUtils.isSameLength(oneArrayShort, emptyArrayFloat)); + assertFalse(ArrayUtils.isSameLength(oneArrayChar, emptyArrayObject)); + assertFalse(ArrayUtils.isSameLength(oneArrayChar, emptyArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(oneArrayChar, emptyArrayLong)); + assertFalse(ArrayUtils.isSameLength(oneArrayChar, emptyArrayInt)); + assertFalse(ArrayUtils.isSameLength(oneArrayChar, emptyArrayShort)); + assertFalse(ArrayUtils.isSameLength(oneArrayChar, emptyArrayChar)); + assertFalse(ArrayUtils.isSameLength(oneArrayChar, emptyArrayByte)); + assertFalse(ArrayUtils.isSameLength(oneArrayChar, emptyArrayDouble)); + assertFalse(ArrayUtils.isSameLength(oneArrayChar, emptyArrayFloat)); + assertFalse(ArrayUtils.isSameLength(oneArrayByte, emptyArrayObject)); + assertFalse(ArrayUtils.isSameLength(oneArrayByte, emptyArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(oneArrayByte, emptyArrayLong)); + assertFalse(ArrayUtils.isSameLength(oneArrayByte, emptyArrayInt)); + assertFalse(ArrayUtils.isSameLength(oneArrayByte, emptyArrayShort)); + assertFalse(ArrayUtils.isSameLength(oneArrayByte, emptyArrayChar)); + assertFalse(ArrayUtils.isSameLength(oneArrayByte, emptyArrayByte)); + assertFalse(ArrayUtils.isSameLength(oneArrayByte, emptyArrayDouble)); + assertFalse(ArrayUtils.isSameLength(oneArrayByte, emptyArrayFloat)); + assertFalse(ArrayUtils.isSameLength(oneArrayDouble, emptyArrayObject)); + assertFalse(ArrayUtils.isSameLength(oneArrayDouble, emptyArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(oneArrayDouble, emptyArrayLong)); + assertFalse(ArrayUtils.isSameLength(oneArrayDouble, emptyArrayInt)); + assertFalse(ArrayUtils.isSameLength(oneArrayDouble, emptyArrayShort)); + assertFalse(ArrayUtils.isSameLength(oneArrayDouble, emptyArrayChar)); + assertFalse(ArrayUtils.isSameLength(oneArrayDouble, emptyArrayByte)); + assertFalse(ArrayUtils.isSameLength(oneArrayDouble, emptyArrayDouble)); + assertFalse(ArrayUtils.isSameLength(oneArrayDouble, emptyArrayFloat)); + assertFalse(ArrayUtils.isSameLength(oneArrayFloat, emptyArrayObject)); + assertFalse(ArrayUtils.isSameLength(oneArrayFloat, emptyArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(oneArrayFloat, emptyArrayLong)); + assertFalse(ArrayUtils.isSameLength(oneArrayFloat, emptyArrayInt)); + assertFalse(ArrayUtils.isSameLength(oneArrayFloat, emptyArrayShort)); + assertFalse(ArrayUtils.isSameLength(oneArrayFloat, emptyArrayChar)); + assertFalse(ArrayUtils.isSameLength(oneArrayFloat, emptyArrayByte)); + assertFalse(ArrayUtils.isSameLength(oneArrayFloat, emptyArrayDouble)); + assertFalse(ArrayUtils.isSameLength(oneArrayFloat, emptyArrayFloat)); + assertTrue(ArrayUtils.isSameLength(oneArrayObject, oneArrayObject)); + assertTrue(ArrayUtils.isSameLength(oneArrayObject, oneArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(oneArrayObject, oneArrayLong)); + assertTrue(ArrayUtils.isSameLength(oneArrayObject, oneArrayInt)); + assertTrue(ArrayUtils.isSameLength(oneArrayObject, oneArrayShort)); + assertTrue(ArrayUtils.isSameLength(oneArrayObject, oneArrayChar)); + assertTrue(ArrayUtils.isSameLength(oneArrayObject, oneArrayByte)); + assertTrue(ArrayUtils.isSameLength(oneArrayObject, oneArrayDouble)); + assertTrue(ArrayUtils.isSameLength(oneArrayObject, oneArrayFloat)); + assertTrue(ArrayUtils.isSameLength(oneArrayBoolean, oneArrayObject)); + assertTrue(ArrayUtils.isSameLength(oneArrayBoolean, oneArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(oneArrayBoolean, oneArrayLong)); + assertTrue(ArrayUtils.isSameLength(oneArrayBoolean, oneArrayInt)); + assertTrue(ArrayUtils.isSameLength(oneArrayBoolean, oneArrayShort)); + assertTrue(ArrayUtils.isSameLength(oneArrayBoolean, oneArrayChar)); + assertTrue(ArrayUtils.isSameLength(oneArrayBoolean, oneArrayByte)); + assertTrue(ArrayUtils.isSameLength(oneArrayBoolean, oneArrayDouble)); + assertTrue(ArrayUtils.isSameLength(oneArrayBoolean, oneArrayFloat)); + assertTrue(ArrayUtils.isSameLength(oneArrayLong, oneArrayObject)); + assertTrue(ArrayUtils.isSameLength(oneArrayLong, oneArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(oneArrayLong, oneArrayLong)); + assertTrue(ArrayUtils.isSameLength(oneArrayLong, oneArrayInt)); + assertTrue(ArrayUtils.isSameLength(oneArrayLong, oneArrayShort)); + assertTrue(ArrayUtils.isSameLength(oneArrayLong, oneArrayChar)); + assertTrue(ArrayUtils.isSameLength(oneArrayLong, oneArrayByte)); + assertTrue(ArrayUtils.isSameLength(oneArrayLong, oneArrayDouble)); + assertTrue(ArrayUtils.isSameLength(oneArrayLong, oneArrayFloat)); + assertTrue(ArrayUtils.isSameLength(oneArrayInt, oneArrayObject)); + assertTrue(ArrayUtils.isSameLength(oneArrayInt, oneArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(oneArrayInt, oneArrayLong)); + assertTrue(ArrayUtils.isSameLength(oneArrayInt, oneArrayInt)); + assertTrue(ArrayUtils.isSameLength(oneArrayInt, oneArrayShort)); + assertTrue(ArrayUtils.isSameLength(oneArrayInt, oneArrayChar)); + assertTrue(ArrayUtils.isSameLength(oneArrayInt, oneArrayByte)); + assertTrue(ArrayUtils.isSameLength(oneArrayInt, oneArrayDouble)); + assertTrue(ArrayUtils.isSameLength(oneArrayInt, oneArrayFloat)); + assertTrue(ArrayUtils.isSameLength(oneArrayShort, oneArrayObject)); + assertTrue(ArrayUtils.isSameLength(oneArrayShort, oneArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(oneArrayShort, oneArrayLong)); + assertTrue(ArrayUtils.isSameLength(oneArrayShort, oneArrayInt)); + assertTrue(ArrayUtils.isSameLength(oneArrayShort, oneArrayShort)); + assertTrue(ArrayUtils.isSameLength(oneArrayShort, oneArrayChar)); + assertTrue(ArrayUtils.isSameLength(oneArrayShort, oneArrayByte)); + assertTrue(ArrayUtils.isSameLength(oneArrayShort, oneArrayDouble)); + assertTrue(ArrayUtils.isSameLength(oneArrayShort, oneArrayFloat)); + assertTrue(ArrayUtils.isSameLength(oneArrayChar, oneArrayObject)); + assertTrue(ArrayUtils.isSameLength(oneArrayChar, oneArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(oneArrayChar, oneArrayLong)); + assertTrue(ArrayUtils.isSameLength(oneArrayChar, oneArrayInt)); + assertTrue(ArrayUtils.isSameLength(oneArrayChar, oneArrayShort)); + assertTrue(ArrayUtils.isSameLength(oneArrayChar, oneArrayChar)); + assertTrue(ArrayUtils.isSameLength(oneArrayChar, oneArrayByte)); + assertTrue(ArrayUtils.isSameLength(oneArrayChar, oneArrayDouble)); + assertTrue(ArrayUtils.isSameLength(oneArrayChar, oneArrayFloat)); + assertTrue(ArrayUtils.isSameLength(oneArrayByte, oneArrayObject)); + assertTrue(ArrayUtils.isSameLength(oneArrayByte, oneArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(oneArrayByte, oneArrayLong)); + assertTrue(ArrayUtils.isSameLength(oneArrayByte, oneArrayInt)); + assertTrue(ArrayUtils.isSameLength(oneArrayByte, oneArrayShort)); + assertTrue(ArrayUtils.isSameLength(oneArrayByte, oneArrayChar)); + assertTrue(ArrayUtils.isSameLength(oneArrayByte, oneArrayByte)); + assertTrue(ArrayUtils.isSameLength(oneArrayByte, oneArrayDouble)); + assertTrue(ArrayUtils.isSameLength(oneArrayByte, oneArrayFloat)); + assertTrue(ArrayUtils.isSameLength(oneArrayDouble, oneArrayObject)); + assertTrue(ArrayUtils.isSameLength(oneArrayDouble, oneArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(oneArrayDouble, oneArrayLong)); + assertTrue(ArrayUtils.isSameLength(oneArrayDouble, oneArrayInt)); + assertTrue(ArrayUtils.isSameLength(oneArrayDouble, oneArrayShort)); + assertTrue(ArrayUtils.isSameLength(oneArrayDouble, oneArrayChar)); + assertTrue(ArrayUtils.isSameLength(oneArrayDouble, oneArrayByte)); + assertTrue(ArrayUtils.isSameLength(oneArrayDouble, oneArrayDouble)); + assertTrue(ArrayUtils.isSameLength(oneArrayDouble, oneArrayFloat)); + assertTrue(ArrayUtils.isSameLength(oneArrayFloat, oneArrayObject)); + assertTrue(ArrayUtils.isSameLength(oneArrayFloat, oneArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(oneArrayFloat, oneArrayLong)); + assertTrue(ArrayUtils.isSameLength(oneArrayFloat, oneArrayInt)); + assertTrue(ArrayUtils.isSameLength(oneArrayFloat, oneArrayShort)); + assertTrue(ArrayUtils.isSameLength(oneArrayFloat, oneArrayChar)); + assertTrue(ArrayUtils.isSameLength(oneArrayFloat, oneArrayByte)); + assertTrue(ArrayUtils.isSameLength(oneArrayFloat, oneArrayDouble)); + assertTrue(ArrayUtils.isSameLength(oneArrayFloat, oneArrayFloat)); + assertFalse(ArrayUtils.isSameLength(oneArrayObject, twoArrayObject)); + assertFalse(ArrayUtils.isSameLength(oneArrayObject, twoArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(oneArrayObject, twoArrayLong)); + assertFalse(ArrayUtils.isSameLength(oneArrayObject, twoArrayInt)); + assertFalse(ArrayUtils.isSameLength(oneArrayObject, twoArrayShort)); + assertFalse(ArrayUtils.isSameLength(oneArrayObject, twoArrayChar)); + assertFalse(ArrayUtils.isSameLength(oneArrayObject, twoArrayByte)); + assertFalse(ArrayUtils.isSameLength(oneArrayObject, twoArrayDouble)); + assertFalse(ArrayUtils.isSameLength(oneArrayObject, twoArrayFloat)); + assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, twoArrayObject)); + assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, twoArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, twoArrayLong)); + assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, twoArrayInt)); + assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, twoArrayShort)); + assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, twoArrayChar)); + assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, twoArrayByte)); + assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, twoArrayDouble)); + assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, twoArrayFloat)); + assertFalse(ArrayUtils.isSameLength(oneArrayLong, twoArrayObject)); + assertFalse(ArrayUtils.isSameLength(oneArrayLong, twoArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(oneArrayLong, twoArrayLong)); + assertFalse(ArrayUtils.isSameLength(oneArrayLong, twoArrayInt)); + assertFalse(ArrayUtils.isSameLength(oneArrayLong, twoArrayShort)); + assertFalse(ArrayUtils.isSameLength(oneArrayLong, twoArrayChar)); + assertFalse(ArrayUtils.isSameLength(oneArrayLong, twoArrayByte)); + assertFalse(ArrayUtils.isSameLength(oneArrayLong, twoArrayDouble)); + assertFalse(ArrayUtils.isSameLength(oneArrayLong, twoArrayFloat)); + assertFalse(ArrayUtils.isSameLength(oneArrayInt, twoArrayObject)); + assertFalse(ArrayUtils.isSameLength(oneArrayInt, twoArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(oneArrayInt, twoArrayLong)); + assertFalse(ArrayUtils.isSameLength(oneArrayInt, twoArrayInt)); + assertFalse(ArrayUtils.isSameLength(oneArrayInt, twoArrayShort)); + assertFalse(ArrayUtils.isSameLength(oneArrayInt, twoArrayChar)); + assertFalse(ArrayUtils.isSameLength(oneArrayInt, twoArrayByte)); + assertFalse(ArrayUtils.isSameLength(oneArrayInt, twoArrayDouble)); + assertFalse(ArrayUtils.isSameLength(oneArrayInt, twoArrayFloat)); + assertFalse(ArrayUtils.isSameLength(oneArrayShort, twoArrayObject)); + assertFalse(ArrayUtils.isSameLength(oneArrayShort, twoArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(oneArrayShort, twoArrayLong)); + assertFalse(ArrayUtils.isSameLength(oneArrayShort, twoArrayInt)); + assertFalse(ArrayUtils.isSameLength(oneArrayShort, twoArrayShort)); + assertFalse(ArrayUtils.isSameLength(oneArrayShort, twoArrayChar)); + assertFalse(ArrayUtils.isSameLength(oneArrayShort, twoArrayByte)); + assertFalse(ArrayUtils.isSameLength(oneArrayShort, twoArrayDouble)); + assertFalse(ArrayUtils.isSameLength(oneArrayShort, twoArrayFloat)); + assertFalse(ArrayUtils.isSameLength(oneArrayChar, twoArrayObject)); + assertFalse(ArrayUtils.isSameLength(oneArrayChar, twoArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(oneArrayChar, twoArrayLong)); + assertFalse(ArrayUtils.isSameLength(oneArrayChar, twoArrayInt)); + assertFalse(ArrayUtils.isSameLength(oneArrayChar, twoArrayShort)); + assertFalse(ArrayUtils.isSameLength(oneArrayChar, twoArrayChar)); + assertFalse(ArrayUtils.isSameLength(oneArrayChar, twoArrayByte)); + assertFalse(ArrayUtils.isSameLength(oneArrayChar, twoArrayDouble)); + assertFalse(ArrayUtils.isSameLength(oneArrayChar, twoArrayFloat)); + assertFalse(ArrayUtils.isSameLength(oneArrayByte, twoArrayObject)); + assertFalse(ArrayUtils.isSameLength(oneArrayByte, twoArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(oneArrayByte, twoArrayLong)); + assertFalse(ArrayUtils.isSameLength(oneArrayByte, twoArrayInt)); + assertFalse(ArrayUtils.isSameLength(oneArrayByte, twoArrayShort)); + assertFalse(ArrayUtils.isSameLength(oneArrayByte, twoArrayChar)); + assertFalse(ArrayUtils.isSameLength(oneArrayByte, twoArrayByte)); + assertFalse(ArrayUtils.isSameLength(oneArrayByte, twoArrayDouble)); + assertFalse(ArrayUtils.isSameLength(oneArrayByte, twoArrayFloat)); + assertFalse(ArrayUtils.isSameLength(oneArrayDouble, twoArrayObject)); + assertFalse(ArrayUtils.isSameLength(oneArrayDouble, twoArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(oneArrayDouble, twoArrayLong)); + assertFalse(ArrayUtils.isSameLength(oneArrayDouble, twoArrayInt)); + assertFalse(ArrayUtils.isSameLength(oneArrayDouble, twoArrayShort)); + assertFalse(ArrayUtils.isSameLength(oneArrayDouble, twoArrayChar)); + assertFalse(ArrayUtils.isSameLength(oneArrayDouble, twoArrayByte)); + assertFalse(ArrayUtils.isSameLength(oneArrayDouble, twoArrayDouble)); + assertFalse(ArrayUtils.isSameLength(oneArrayDouble, twoArrayFloat)); + assertFalse(ArrayUtils.isSameLength(oneArrayFloat, twoArrayObject)); + assertFalse(ArrayUtils.isSameLength(oneArrayFloat, twoArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(oneArrayFloat, twoArrayLong)); + assertFalse(ArrayUtils.isSameLength(oneArrayFloat, twoArrayInt)); + assertFalse(ArrayUtils.isSameLength(oneArrayFloat, twoArrayShort)); + assertFalse(ArrayUtils.isSameLength(oneArrayFloat, twoArrayChar)); + assertFalse(ArrayUtils.isSameLength(oneArrayFloat, twoArrayByte)); + assertFalse(ArrayUtils.isSameLength(oneArrayFloat, twoArrayDouble)); + assertFalse(ArrayUtils.isSameLength(oneArrayFloat, twoArrayFloat)); + assertFalse(ArrayUtils.isSameLength(twoArrayObject, nullArrayObject)); + assertFalse(ArrayUtils.isSameLength(twoArrayObject, nullArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(twoArrayObject, nullArrayLong)); + assertFalse(ArrayUtils.isSameLength(twoArrayObject, nullArrayInt)); + assertFalse(ArrayUtils.isSameLength(twoArrayObject, nullArrayShort)); + assertFalse(ArrayUtils.isSameLength(twoArrayObject, nullArrayChar)); + assertFalse(ArrayUtils.isSameLength(twoArrayObject, nullArrayByte)); + assertFalse(ArrayUtils.isSameLength(twoArrayObject, nullArrayDouble)); + assertFalse(ArrayUtils.isSameLength(twoArrayObject, nullArrayFloat)); + assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, nullArrayObject)); + assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, nullArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, nullArrayLong)); + assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, nullArrayInt)); + assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, nullArrayShort)); + assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, nullArrayChar)); + assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, nullArrayByte)); + assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, nullArrayDouble)); + assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, nullArrayFloat)); + assertFalse(ArrayUtils.isSameLength(twoArrayLong, nullArrayObject)); + assertFalse(ArrayUtils.isSameLength(twoArrayLong, nullArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(twoArrayLong, nullArrayLong)); + assertFalse(ArrayUtils.isSameLength(twoArrayLong, nullArrayInt)); + assertFalse(ArrayUtils.isSameLength(twoArrayLong, nullArrayShort)); + assertFalse(ArrayUtils.isSameLength(twoArrayLong, nullArrayChar)); + assertFalse(ArrayUtils.isSameLength(twoArrayLong, nullArrayByte)); + assertFalse(ArrayUtils.isSameLength(twoArrayLong, nullArrayDouble)); + assertFalse(ArrayUtils.isSameLength(twoArrayLong, nullArrayFloat)); + assertFalse(ArrayUtils.isSameLength(twoArrayInt, nullArrayObject)); + assertFalse(ArrayUtils.isSameLength(twoArrayInt, nullArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(twoArrayInt, nullArrayLong)); + assertFalse(ArrayUtils.isSameLength(twoArrayInt, nullArrayInt)); + assertFalse(ArrayUtils.isSameLength(twoArrayInt, nullArrayShort)); + assertFalse(ArrayUtils.isSameLength(twoArrayInt, nullArrayChar)); + assertFalse(ArrayUtils.isSameLength(twoArrayInt, nullArrayByte)); + assertFalse(ArrayUtils.isSameLength(twoArrayInt, nullArrayDouble)); + assertFalse(ArrayUtils.isSameLength(twoArrayInt, nullArrayFloat)); + assertFalse(ArrayUtils.isSameLength(twoArrayShort, nullArrayObject)); + assertFalse(ArrayUtils.isSameLength(twoArrayShort, nullArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(twoArrayShort, nullArrayLong)); + assertFalse(ArrayUtils.isSameLength(twoArrayShort, nullArrayInt)); + assertFalse(ArrayUtils.isSameLength(twoArrayShort, nullArrayShort)); + assertFalse(ArrayUtils.isSameLength(twoArrayShort, nullArrayChar)); + assertFalse(ArrayUtils.isSameLength(twoArrayShort, nullArrayByte)); + assertFalse(ArrayUtils.isSameLength(twoArrayShort, nullArrayDouble)); + assertFalse(ArrayUtils.isSameLength(twoArrayShort, nullArrayFloat)); + assertFalse(ArrayUtils.isSameLength(twoArrayChar, nullArrayObject)); + assertFalse(ArrayUtils.isSameLength(twoArrayChar, nullArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(twoArrayChar, nullArrayLong)); + assertFalse(ArrayUtils.isSameLength(twoArrayChar, nullArrayInt)); + assertFalse(ArrayUtils.isSameLength(twoArrayChar, nullArrayShort)); + assertFalse(ArrayUtils.isSameLength(twoArrayChar, nullArrayChar)); + assertFalse(ArrayUtils.isSameLength(twoArrayChar, nullArrayByte)); + assertFalse(ArrayUtils.isSameLength(twoArrayChar, nullArrayDouble)); + assertFalse(ArrayUtils.isSameLength(twoArrayChar, nullArrayFloat)); + assertFalse(ArrayUtils.isSameLength(twoArrayByte, nullArrayObject)); + assertFalse(ArrayUtils.isSameLength(twoArrayByte, nullArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(twoArrayByte, nullArrayLong)); + assertFalse(ArrayUtils.isSameLength(twoArrayByte, nullArrayInt)); + assertFalse(ArrayUtils.isSameLength(twoArrayByte, nullArrayShort)); + assertFalse(ArrayUtils.isSameLength(twoArrayByte, nullArrayChar)); + assertFalse(ArrayUtils.isSameLength(twoArrayByte, nullArrayByte)); + assertFalse(ArrayUtils.isSameLength(twoArrayByte, nullArrayDouble)); + assertFalse(ArrayUtils.isSameLength(twoArrayByte, nullArrayFloat)); + assertFalse(ArrayUtils.isSameLength(twoArrayDouble, nullArrayObject)); + assertFalse(ArrayUtils.isSameLength(twoArrayDouble, nullArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(twoArrayDouble, nullArrayLong)); + assertFalse(ArrayUtils.isSameLength(twoArrayDouble, nullArrayInt)); + assertFalse(ArrayUtils.isSameLength(twoArrayDouble, nullArrayShort)); + assertFalse(ArrayUtils.isSameLength(twoArrayDouble, nullArrayChar)); + assertFalse(ArrayUtils.isSameLength(twoArrayDouble, nullArrayByte)); + assertFalse(ArrayUtils.isSameLength(twoArrayDouble, nullArrayDouble)); + assertFalse(ArrayUtils.isSameLength(twoArrayDouble, nullArrayFloat)); + assertFalse(ArrayUtils.isSameLength(twoArrayFloat, nullArrayObject)); + assertFalse(ArrayUtils.isSameLength(twoArrayFloat, nullArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(twoArrayFloat, nullArrayLong)); + assertFalse(ArrayUtils.isSameLength(twoArrayFloat, nullArrayInt)); + assertFalse(ArrayUtils.isSameLength(twoArrayFloat, nullArrayShort)); + assertFalse(ArrayUtils.isSameLength(twoArrayFloat, nullArrayChar)); + assertFalse(ArrayUtils.isSameLength(twoArrayFloat, nullArrayByte)); + assertFalse(ArrayUtils.isSameLength(twoArrayFloat, nullArrayDouble)); + assertFalse(ArrayUtils.isSameLength(twoArrayFloat, nullArrayFloat)); + assertFalse(ArrayUtils.isSameLength(twoArrayObject, emptyArrayObject)); + assertFalse(ArrayUtils.isSameLength(twoArrayObject, emptyArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(twoArrayObject, emptyArrayLong)); + assertFalse(ArrayUtils.isSameLength(twoArrayObject, emptyArrayInt)); + assertFalse(ArrayUtils.isSameLength(twoArrayObject, emptyArrayShort)); + assertFalse(ArrayUtils.isSameLength(twoArrayObject, emptyArrayChar)); + assertFalse(ArrayUtils.isSameLength(twoArrayObject, emptyArrayByte)); + assertFalse(ArrayUtils.isSameLength(twoArrayObject, emptyArrayDouble)); + assertFalse(ArrayUtils.isSameLength(twoArrayObject, emptyArrayFloat)); + assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, emptyArrayObject)); + assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, emptyArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, emptyArrayLong)); + assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, emptyArrayInt)); + assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, emptyArrayShort)); + assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, emptyArrayChar)); + assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, emptyArrayByte)); + assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, emptyArrayDouble)); + assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, emptyArrayFloat)); + assertFalse(ArrayUtils.isSameLength(twoArrayLong, emptyArrayObject)); + assertFalse(ArrayUtils.isSameLength(twoArrayLong, emptyArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(twoArrayLong, emptyArrayLong)); + assertFalse(ArrayUtils.isSameLength(twoArrayLong, emptyArrayInt)); + assertFalse(ArrayUtils.isSameLength(twoArrayLong, emptyArrayShort)); + assertFalse(ArrayUtils.isSameLength(twoArrayLong, emptyArrayChar)); + assertFalse(ArrayUtils.isSameLength(twoArrayLong, emptyArrayByte)); + assertFalse(ArrayUtils.isSameLength(twoArrayLong, emptyArrayDouble)); + assertFalse(ArrayUtils.isSameLength(twoArrayLong, emptyArrayFloat)); + assertFalse(ArrayUtils.isSameLength(twoArrayInt, emptyArrayObject)); + assertFalse(ArrayUtils.isSameLength(twoArrayInt, emptyArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(twoArrayInt, emptyArrayLong)); + assertFalse(ArrayUtils.isSameLength(twoArrayInt, emptyArrayInt)); + assertFalse(ArrayUtils.isSameLength(twoArrayInt, emptyArrayShort)); + assertFalse(ArrayUtils.isSameLength(twoArrayInt, emptyArrayChar)); + assertFalse(ArrayUtils.isSameLength(twoArrayInt, emptyArrayByte)); + assertFalse(ArrayUtils.isSameLength(twoArrayInt, emptyArrayDouble)); + assertFalse(ArrayUtils.isSameLength(twoArrayInt, emptyArrayFloat)); + assertFalse(ArrayUtils.isSameLength(twoArrayShort, emptyArrayObject)); + assertFalse(ArrayUtils.isSameLength(twoArrayShort, emptyArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(twoArrayShort, emptyArrayLong)); + assertFalse(ArrayUtils.isSameLength(twoArrayShort, emptyArrayInt)); + assertFalse(ArrayUtils.isSameLength(twoArrayShort, emptyArrayShort)); + assertFalse(ArrayUtils.isSameLength(twoArrayShort, emptyArrayChar)); + assertFalse(ArrayUtils.isSameLength(twoArrayShort, emptyArrayByte)); + assertFalse(ArrayUtils.isSameLength(twoArrayShort, emptyArrayDouble)); + assertFalse(ArrayUtils.isSameLength(twoArrayShort, emptyArrayFloat)); + assertFalse(ArrayUtils.isSameLength(twoArrayChar, emptyArrayObject)); + assertFalse(ArrayUtils.isSameLength(twoArrayChar, emptyArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(twoArrayChar, emptyArrayLong)); + assertFalse(ArrayUtils.isSameLength(twoArrayChar, emptyArrayInt)); + assertFalse(ArrayUtils.isSameLength(twoArrayChar, emptyArrayShort)); + assertFalse(ArrayUtils.isSameLength(twoArrayChar, emptyArrayChar)); + assertFalse(ArrayUtils.isSameLength(twoArrayChar, emptyArrayByte)); + assertFalse(ArrayUtils.isSameLength(twoArrayChar, emptyArrayDouble)); + assertFalse(ArrayUtils.isSameLength(twoArrayChar, emptyArrayFloat)); + assertFalse(ArrayUtils.isSameLength(twoArrayByte, emptyArrayObject)); + assertFalse(ArrayUtils.isSameLength(twoArrayByte, emptyArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(twoArrayByte, emptyArrayLong)); + assertFalse(ArrayUtils.isSameLength(twoArrayByte, emptyArrayInt)); + assertFalse(ArrayUtils.isSameLength(twoArrayByte, emptyArrayShort)); + assertFalse(ArrayUtils.isSameLength(twoArrayByte, emptyArrayChar)); + assertFalse(ArrayUtils.isSameLength(twoArrayByte, emptyArrayByte)); + assertFalse(ArrayUtils.isSameLength(twoArrayByte, emptyArrayDouble)); + assertFalse(ArrayUtils.isSameLength(twoArrayByte, emptyArrayFloat)); + assertFalse(ArrayUtils.isSameLength(twoArrayDouble, emptyArrayObject)); + assertFalse(ArrayUtils.isSameLength(twoArrayDouble, emptyArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(twoArrayDouble, emptyArrayLong)); + assertFalse(ArrayUtils.isSameLength(twoArrayDouble, emptyArrayInt)); + assertFalse(ArrayUtils.isSameLength(twoArrayDouble, emptyArrayShort)); + assertFalse(ArrayUtils.isSameLength(twoArrayDouble, emptyArrayChar)); + assertFalse(ArrayUtils.isSameLength(twoArrayDouble, emptyArrayByte)); + assertFalse(ArrayUtils.isSameLength(twoArrayDouble, emptyArrayDouble)); + assertFalse(ArrayUtils.isSameLength(twoArrayDouble, emptyArrayFloat)); + assertFalse(ArrayUtils.isSameLength(twoArrayFloat, emptyArrayObject)); + assertFalse(ArrayUtils.isSameLength(twoArrayFloat, emptyArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(twoArrayFloat, emptyArrayLong)); + assertFalse(ArrayUtils.isSameLength(twoArrayFloat, emptyArrayInt)); + assertFalse(ArrayUtils.isSameLength(twoArrayFloat, emptyArrayShort)); + assertFalse(ArrayUtils.isSameLength(twoArrayFloat, emptyArrayChar)); + assertFalse(ArrayUtils.isSameLength(twoArrayFloat, emptyArrayByte)); + assertFalse(ArrayUtils.isSameLength(twoArrayFloat, emptyArrayDouble)); + assertFalse(ArrayUtils.isSameLength(twoArrayFloat, emptyArrayFloat)); + assertFalse(ArrayUtils.isSameLength(twoArrayObject, oneArrayObject)); + assertFalse(ArrayUtils.isSameLength(twoArrayObject, oneArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(twoArrayObject, oneArrayLong)); + assertFalse(ArrayUtils.isSameLength(twoArrayObject, oneArrayInt)); + assertFalse(ArrayUtils.isSameLength(twoArrayObject, oneArrayShort)); + assertFalse(ArrayUtils.isSameLength(twoArrayObject, oneArrayChar)); + assertFalse(ArrayUtils.isSameLength(twoArrayObject, oneArrayByte)); + assertFalse(ArrayUtils.isSameLength(twoArrayObject, oneArrayDouble)); + assertFalse(ArrayUtils.isSameLength(twoArrayObject, oneArrayFloat)); + assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, oneArrayObject)); + assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, oneArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, oneArrayLong)); + assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, oneArrayInt)); + assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, oneArrayShort)); + assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, oneArrayChar)); + assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, oneArrayByte)); + assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, oneArrayDouble)); + assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, oneArrayFloat)); + assertFalse(ArrayUtils.isSameLength(twoArrayLong, oneArrayObject)); + assertFalse(ArrayUtils.isSameLength(twoArrayLong, oneArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(twoArrayLong, oneArrayLong)); + assertFalse(ArrayUtils.isSameLength(twoArrayLong, oneArrayInt)); + assertFalse(ArrayUtils.isSameLength(twoArrayLong, oneArrayShort)); + assertFalse(ArrayUtils.isSameLength(twoArrayLong, oneArrayChar)); + assertFalse(ArrayUtils.isSameLength(twoArrayLong, oneArrayByte)); + assertFalse(ArrayUtils.isSameLength(twoArrayLong, oneArrayDouble)); + assertFalse(ArrayUtils.isSameLength(twoArrayLong, oneArrayFloat)); + assertFalse(ArrayUtils.isSameLength(twoArrayInt, oneArrayObject)); + assertFalse(ArrayUtils.isSameLength(twoArrayInt, oneArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(twoArrayInt, oneArrayLong)); + assertFalse(ArrayUtils.isSameLength(twoArrayInt, oneArrayInt)); + assertFalse(ArrayUtils.isSameLength(twoArrayInt, oneArrayShort)); + assertFalse(ArrayUtils.isSameLength(twoArrayInt, oneArrayChar)); + assertFalse(ArrayUtils.isSameLength(twoArrayInt, oneArrayByte)); + assertFalse(ArrayUtils.isSameLength(twoArrayInt, oneArrayDouble)); + assertFalse(ArrayUtils.isSameLength(twoArrayInt, oneArrayFloat)); + assertFalse(ArrayUtils.isSameLength(twoArrayShort, oneArrayObject)); + assertFalse(ArrayUtils.isSameLength(twoArrayShort, oneArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(twoArrayShort, oneArrayLong)); + assertFalse(ArrayUtils.isSameLength(twoArrayShort, oneArrayInt)); + assertFalse(ArrayUtils.isSameLength(twoArrayShort, oneArrayShort)); + assertFalse(ArrayUtils.isSameLength(twoArrayShort, oneArrayChar)); + assertFalse(ArrayUtils.isSameLength(twoArrayShort, oneArrayByte)); + assertFalse(ArrayUtils.isSameLength(twoArrayShort, oneArrayDouble)); + assertFalse(ArrayUtils.isSameLength(twoArrayShort, oneArrayFloat)); + assertFalse(ArrayUtils.isSameLength(twoArrayChar, oneArrayObject)); + assertFalse(ArrayUtils.isSameLength(twoArrayChar, oneArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(twoArrayChar, oneArrayLong)); + assertFalse(ArrayUtils.isSameLength(twoArrayChar, oneArrayInt)); + assertFalse(ArrayUtils.isSameLength(twoArrayChar, oneArrayShort)); + assertFalse(ArrayUtils.isSameLength(twoArrayChar, oneArrayChar)); + assertFalse(ArrayUtils.isSameLength(twoArrayChar, oneArrayByte)); + assertFalse(ArrayUtils.isSameLength(twoArrayChar, oneArrayDouble)); + assertFalse(ArrayUtils.isSameLength(twoArrayChar, oneArrayFloat)); + assertFalse(ArrayUtils.isSameLength(twoArrayByte, oneArrayObject)); + assertFalse(ArrayUtils.isSameLength(twoArrayByte, oneArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(twoArrayByte, oneArrayLong)); + assertFalse(ArrayUtils.isSameLength(twoArrayByte, oneArrayInt)); + assertFalse(ArrayUtils.isSameLength(twoArrayByte, oneArrayShort)); + assertFalse(ArrayUtils.isSameLength(twoArrayByte, oneArrayChar)); + assertFalse(ArrayUtils.isSameLength(twoArrayByte, oneArrayByte)); + assertFalse(ArrayUtils.isSameLength(twoArrayByte, oneArrayDouble)); + assertFalse(ArrayUtils.isSameLength(twoArrayByte, oneArrayFloat)); + assertFalse(ArrayUtils.isSameLength(twoArrayDouble, oneArrayObject)); + assertFalse(ArrayUtils.isSameLength(twoArrayDouble, oneArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(twoArrayDouble, oneArrayLong)); + assertFalse(ArrayUtils.isSameLength(twoArrayDouble, oneArrayInt)); + assertFalse(ArrayUtils.isSameLength(twoArrayDouble, oneArrayShort)); + assertFalse(ArrayUtils.isSameLength(twoArrayDouble, oneArrayChar)); + assertFalse(ArrayUtils.isSameLength(twoArrayDouble, oneArrayByte)); + assertFalse(ArrayUtils.isSameLength(twoArrayDouble, oneArrayDouble)); + assertFalse(ArrayUtils.isSameLength(twoArrayDouble, oneArrayFloat)); + assertFalse(ArrayUtils.isSameLength(twoArrayFloat, oneArrayObject)); + assertFalse(ArrayUtils.isSameLength(twoArrayFloat, oneArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(twoArrayFloat, oneArrayLong)); + assertFalse(ArrayUtils.isSameLength(twoArrayFloat, oneArrayInt)); + assertFalse(ArrayUtils.isSameLength(twoArrayFloat, oneArrayShort)); + assertFalse(ArrayUtils.isSameLength(twoArrayFloat, oneArrayChar)); + assertFalse(ArrayUtils.isSameLength(twoArrayFloat, oneArrayByte)); + assertFalse(ArrayUtils.isSameLength(twoArrayFloat, oneArrayDouble)); + assertFalse(ArrayUtils.isSameLength(twoArrayFloat, oneArrayFloat)); + assertTrue(ArrayUtils.isSameLength(twoArrayObject, twoArrayObject)); + assertTrue(ArrayUtils.isSameLength(twoArrayObject, twoArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(twoArrayObject, twoArrayLong)); + assertTrue(ArrayUtils.isSameLength(twoArrayObject, twoArrayInt)); + assertTrue(ArrayUtils.isSameLength(twoArrayObject, twoArrayShort)); + assertTrue(ArrayUtils.isSameLength(twoArrayObject, twoArrayChar)); + assertTrue(ArrayUtils.isSameLength(twoArrayObject, twoArrayByte)); + assertTrue(ArrayUtils.isSameLength(twoArrayObject, twoArrayDouble)); + assertTrue(ArrayUtils.isSameLength(twoArrayObject, twoArrayFloat)); + assertTrue(ArrayUtils.isSameLength(twoArrayBoolean, twoArrayObject)); + assertTrue(ArrayUtils.isSameLength(twoArrayBoolean, twoArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(twoArrayBoolean, twoArrayLong)); + assertTrue(ArrayUtils.isSameLength(twoArrayBoolean, twoArrayInt)); + assertTrue(ArrayUtils.isSameLength(twoArrayBoolean, twoArrayShort)); + assertTrue(ArrayUtils.isSameLength(twoArrayBoolean, twoArrayChar)); + assertTrue(ArrayUtils.isSameLength(twoArrayBoolean, twoArrayByte)); + assertTrue(ArrayUtils.isSameLength(twoArrayBoolean, twoArrayDouble)); + assertTrue(ArrayUtils.isSameLength(twoArrayBoolean, twoArrayFloat)); + assertTrue(ArrayUtils.isSameLength(twoArrayLong, twoArrayObject)); + assertTrue(ArrayUtils.isSameLength(twoArrayLong, twoArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(twoArrayLong, twoArrayLong)); + assertTrue(ArrayUtils.isSameLength(twoArrayLong, twoArrayInt)); + assertTrue(ArrayUtils.isSameLength(twoArrayLong, twoArrayShort)); + assertTrue(ArrayUtils.isSameLength(twoArrayLong, twoArrayChar)); + assertTrue(ArrayUtils.isSameLength(twoArrayLong, twoArrayByte)); + assertTrue(ArrayUtils.isSameLength(twoArrayLong, twoArrayDouble)); + assertTrue(ArrayUtils.isSameLength(twoArrayLong, twoArrayFloat)); + assertTrue(ArrayUtils.isSameLength(twoArrayInt, twoArrayObject)); + assertTrue(ArrayUtils.isSameLength(twoArrayInt, twoArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(twoArrayInt, twoArrayLong)); + assertTrue(ArrayUtils.isSameLength(twoArrayInt, twoArrayInt)); + assertTrue(ArrayUtils.isSameLength(twoArrayInt, twoArrayShort)); + assertTrue(ArrayUtils.isSameLength(twoArrayInt, twoArrayChar)); + assertTrue(ArrayUtils.isSameLength(twoArrayInt, twoArrayByte)); + assertTrue(ArrayUtils.isSameLength(twoArrayInt, twoArrayDouble)); + assertTrue(ArrayUtils.isSameLength(twoArrayInt, twoArrayFloat)); + assertTrue(ArrayUtils.isSameLength(twoArrayShort, twoArrayObject)); + assertTrue(ArrayUtils.isSameLength(twoArrayShort, twoArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(twoArrayShort, twoArrayLong)); + assertTrue(ArrayUtils.isSameLength(twoArrayShort, twoArrayInt)); + assertTrue(ArrayUtils.isSameLength(twoArrayShort, twoArrayShort)); + assertTrue(ArrayUtils.isSameLength(twoArrayShort, twoArrayChar)); + assertTrue(ArrayUtils.isSameLength(twoArrayShort, twoArrayByte)); + assertTrue(ArrayUtils.isSameLength(twoArrayShort, twoArrayDouble)); + assertTrue(ArrayUtils.isSameLength(twoArrayShort, twoArrayFloat)); + assertTrue(ArrayUtils.isSameLength(twoArrayChar, twoArrayObject)); + assertTrue(ArrayUtils.isSameLength(twoArrayChar, twoArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(twoArrayChar, twoArrayLong)); + assertTrue(ArrayUtils.isSameLength(twoArrayChar, twoArrayInt)); + assertTrue(ArrayUtils.isSameLength(twoArrayChar, twoArrayShort)); + assertTrue(ArrayUtils.isSameLength(twoArrayChar, twoArrayChar)); + assertTrue(ArrayUtils.isSameLength(twoArrayChar, twoArrayByte)); + assertTrue(ArrayUtils.isSameLength(twoArrayChar, twoArrayDouble)); + assertTrue(ArrayUtils.isSameLength(twoArrayChar, twoArrayFloat)); + assertTrue(ArrayUtils.isSameLength(twoArrayByte, twoArrayObject)); + assertTrue(ArrayUtils.isSameLength(twoArrayByte, twoArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(twoArrayByte, twoArrayLong)); + assertTrue(ArrayUtils.isSameLength(twoArrayByte, twoArrayInt)); + assertTrue(ArrayUtils.isSameLength(twoArrayByte, twoArrayShort)); + assertTrue(ArrayUtils.isSameLength(twoArrayByte, twoArrayChar)); + assertTrue(ArrayUtils.isSameLength(twoArrayByte, twoArrayByte)); + assertTrue(ArrayUtils.isSameLength(twoArrayByte, twoArrayDouble)); + assertTrue(ArrayUtils.isSameLength(twoArrayByte, twoArrayFloat)); + assertTrue(ArrayUtils.isSameLength(twoArrayDouble, twoArrayObject)); + assertTrue(ArrayUtils.isSameLength(twoArrayDouble, twoArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(twoArrayDouble, twoArrayLong)); + assertTrue(ArrayUtils.isSameLength(twoArrayDouble, twoArrayInt)); + assertTrue(ArrayUtils.isSameLength(twoArrayDouble, twoArrayShort)); + assertTrue(ArrayUtils.isSameLength(twoArrayDouble, twoArrayChar)); + assertTrue(ArrayUtils.isSameLength(twoArrayDouble, twoArrayByte)); + assertTrue(ArrayUtils.isSameLength(twoArrayDouble, twoArrayDouble)); + assertTrue(ArrayUtils.isSameLength(twoArrayDouble, twoArrayFloat)); + assertTrue(ArrayUtils.isSameLength(twoArrayFloat, twoArrayObject)); + assertTrue(ArrayUtils.isSameLength(twoArrayFloat, twoArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(twoArrayFloat, twoArrayLong)); + assertTrue(ArrayUtils.isSameLength(twoArrayFloat, twoArrayInt)); + assertTrue(ArrayUtils.isSameLength(twoArrayFloat, twoArrayShort)); + assertTrue(ArrayUtils.isSameLength(twoArrayFloat, twoArrayChar)); + assertTrue(ArrayUtils.isSameLength(twoArrayFloat, twoArrayByte)); + assertTrue(ArrayUtils.isSameLength(twoArrayFloat, twoArrayDouble)); + assertTrue(ArrayUtils.isSameLength(twoArrayFloat, twoArrayFloat)); + } + //----------------------------------------------------------------------- @Test public void testSameType() { From 4db28967504e830090d9d942f933a2a3877330b7 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sun, 24 May 2020 11:07:18 -0400 Subject: [PATCH 0081/3230] The next release will be 3.11. --- pom.xml | 6 +++--- src/changes/changes.xml | 3 ++- src/site/xdoc/index.xml | 2 +- 3 files changed, 6 insertions(+), 5 deletions(-) diff --git a/pom.xml b/pom.xml index b8c8a886b91..21603087420 100644 --- a/pom.xml +++ b/pom.xml @@ -26,7 +26,7 @@ 4.0.0 commons-lang3 - 3.10.1-SNAPSHOT + 3.11-SNAPSHOT Apache Commons Lang 2001 @@ -47,7 +47,7 @@ scm:git:http://gitbox.apache.org/repos/asf/commons-lang.git scm:git:https://gitbox.apache.org/repos/asf/commons-lang.git https://gitbox.apache.org/repos/asf?p=commons-lang.git - commons-lang-3.10 + commons-lang-3.11 @@ -584,7 +584,7 @@ lang3 org.apache.commons.lang3 - 3.10 + 3.11 (Java 8+) 2.6 diff --git a/src/changes/changes.xml b/src/changes/changes.xml index ac9a2cd752c..69036303638 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -45,7 +45,7 @@ The type attribute can be add,update,fix,remove. - + Fix Javdoc for StringUtils.appendIfMissingIgnoreCase() #507. org.junit-pioneer:junit-pioneer 0.5.4 -> 0.5.6. org.junit.jupiter:junit-jupiter 5.6.0 -> 5.6.1. @@ -57,6 +57,7 @@ The type attribute can be add,update,fix,remove. Simplify a null check in the private replaceEach() method of StringUtils. #514. Replace some usages of the ternary operator with calls to Math.max() and Math.min() #512. (Javadoc) Fix return tag for throwableOf*() methods #518. + Add ArrayUtils.isSameLength() to compare more array types #430. diff --git a/src/site/xdoc/index.xml b/src/site/xdoc/index.xml index 49e9d11f7fe..7f7667a28cf 100644 --- a/src/site/xdoc/index.xml +++ b/src/site/xdoc/index.xml @@ -50,7 +50,7 @@ and various project reports are provided. The Javadoc API documents are available online:

    From 84a80552b87a0c5264cef14c081dd7d7b66c9e37 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sun, 24 May 2020 11:13:00 -0400 Subject: [PATCH 0082/3230] Update org.junit-pioneer:junit-pioneer from 0.5.6 to 0.6.0. --- pom.xml | 2 +- src/changes/changes.xml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 21603087420..52721574796 100644 --- a/pom.xml +++ b/pom.xml @@ -522,7 +522,7 @@ org.junit-pioneer junit-pioneer - 0.5.6 + 0.6.0 test diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 69036303638..6d3b1d619a3 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -47,7 +47,7 @@ The type attribute can be add,update,fix,remove. Fix Javdoc for StringUtils.appendIfMissingIgnoreCase() #507. - org.junit-pioneer:junit-pioneer 0.5.4 -> 0.5.6. + org.junit-pioneer:junit-pioneer 0.5.4 -> 0.6.0. org.junit.jupiter:junit-jupiter 5.6.0 -> 5.6.1. com.github.spotbugs:spotbugs 4.0.0 -> 4.0.2. com.puppycrawl.tools:checkstyle 8.29 -> 8.31. From c0d0d4f3ea898398d1bac7316084ef03b8de6433 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sun, 24 May 2020 11:19:42 -0400 Subject: [PATCH 0083/3230] Update com.github.spotbugs:spotbugs from 4.0.2 to 4.0.3. Update com.puppycrawl.tools:checkstyle from 8.31 to 8.32. --- pom.xml | 4 ++-- src/changes/changes.xml | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/pom.xml b/pom.xml index 52721574796..871571c2e95 100644 --- a/pom.xml +++ b/pom.xml @@ -600,7 +600,7 @@ utf-8 3.1.1 - 8.31 + 8.32 src/site/resources/checkstyle 4.0.0 @@ -765,7 +765,7 @@ com.github.spotbugs spotbugs - 4.0.2 + 4.0.3 diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 6d3b1d619a3..bc55ac28fb7 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -49,8 +49,8 @@ The type attribute can be add,update,fix,remove. Fix Javdoc for StringUtils.appendIfMissingIgnoreCase() #507. org.junit-pioneer:junit-pioneer 0.5.4 -> 0.6.0. org.junit.jupiter:junit-jupiter 5.6.0 -> 5.6.1. - com.github.spotbugs:spotbugs 4.0.0 -> 4.0.2. - com.puppycrawl.tools:checkstyle 8.29 -> 8.31. + com.github.spotbugs:spotbugs 4.0.0 -> 4.0.3. + com.puppycrawl.tools:checkstyle 8.29 -> 8.32. Simplify null checks in Pair.hashCode() using Objects.hashCode(). #517. Simplify null checks in Triple.hashCode() using Objects.hashCode(). #516. Simplify some if statements in StringUtils. #521. From 2c7e5e4b29c80d5475e971232458d3481bbe7136 Mon Sep 17 00:00:00 2001 From: XenoAmess Date: Mon, 25 May 2020 21:41:18 +0800 Subject: [PATCH 0084/3230] [LANG-1545] CharSequenceUtils.regionMatches is wrong dealing with Georgian. (#529) * CharSequenceUtils.regionMatches is wrong dealing with Georgian. see details in tests. * refine tests --- .../commons/lang3/CharSequenceUtils.java | 7 ++--- .../apache/commons/lang3/StringUtilsTest.java | 27 +++++++++++++++++++ 2 files changed, 31 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/CharSequenceUtils.java b/src/main/java/org/apache/commons/lang3/CharSequenceUtils.java index 58c04536e46..fdb91220bb2 100644 --- a/src/main/java/org/apache/commons/lang3/CharSequenceUtils.java +++ b/src/main/java/org/apache/commons/lang3/CharSequenceUtils.java @@ -294,9 +294,10 @@ static boolean regionMatches(final CharSequence cs, final boolean ignoreCase, fi return false; } - // The same check as in String.regionMatches(): - if (Character.toUpperCase(c1) != Character.toUpperCase(c2) - && Character.toLowerCase(c1) != Character.toLowerCase(c2)) { + // The real same check as in String.regionMatches(): + char u1 = Character.toUpperCase(c1); + char u2 = Character.toUpperCase(c2); + if (u1 != u2 && Character.toLowerCase(u1) != Character.toLowerCase(u2)) { return false; } } diff --git a/src/test/java/org/apache/commons/lang3/StringUtilsTest.java b/src/test/java/org/apache/commons/lang3/StringUtilsTest.java index 30263de6b33..cea53a2632a 100644 --- a/src/test/java/org/apache/commons/lang3/StringUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/StringUtilsTest.java @@ -3305,4 +3305,31 @@ public void testToRootUpperCase() { Locale.setDefault(defaultLocales); } } + + @Test + public void testGeorgianSample() { + char[] arrayI = new char[]{ + //Latin Small Letter dotless I + (char) 0x0131, + //Greek Capital Letter Theta + (char) 0x03F4 + }; + char[] arrayJ = new char[]{ + //Latin Capital Letter I with dot above + (char) 0x0130, + //Greek Theta Symbol + (char) 0x03D1 + }; + for (char i : arrayI) { + for (char j : arrayJ) { + String si = "" + i; + String sj = "" + j; + boolean res1 = si.equalsIgnoreCase(sj); + CharSequence ci = new StringBuilder(si); + CharSequence cj = new StringBuilder(sj); + boolean res2 = StringUtils.startsWithIgnoreCase(ci, cj); + assertEquals(res1, res2, "si : " + si + " sj : " + sj); + } + } + } } From 71ee021ca5fa4ca5a6f414c05666aedc79bde78d Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Mon, 25 May 2020 09:48:20 -0400 Subject: [PATCH 0085/3230] [LANG-1545] CharSequenceUtils.regionMatches is wrong dealing with Georgian. --- src/changes/changes.xml | 1 + .../org/apache/commons/lang3/StringUtilsTest.java | 12 ++++++++++-- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index bc55ac28fb7..1df43f20b99 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -58,6 +58,7 @@ The type attribute can be add,update,fix,remove. Replace some usages of the ternary operator with calls to Math.max() and Math.min() #512. (Javadoc) Fix return tag for throwableOf*() methods #518. Add ArrayUtils.isSameLength() to compare more array types #430. + CharSequenceUtils.regionMatches is wrong dealing with Georgian. diff --git a/src/test/java/org/apache/commons/lang3/StringUtilsTest.java b/src/test/java/org/apache/commons/lang3/StringUtilsTest.java index cea53a2632a..a1eb66a579c 100644 --- a/src/test/java/org/apache/commons/lang3/StringUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/StringUtilsTest.java @@ -3322,13 +3322,21 @@ public void testGeorgianSample() { }; for (char i : arrayI) { for (char j : arrayJ) { - String si = "" + i; - String sj = "" + j; + String si = String.valueOf(i); + String sj = String.valueOf(j); boolean res1 = si.equalsIgnoreCase(sj); CharSequence ci = new StringBuilder(si); CharSequence cj = new StringBuilder(sj); boolean res2 = StringUtils.startsWithIgnoreCase(ci, cj); assertEquals(res1, res2, "si : " + si + " sj : " + sj); + res2 = StringUtils.endsWithIgnoreCase(ci, cj); + assertEquals(res1, res2, "si : " + si + " sj : " + sj); + res2 = StringUtils.compareIgnoreCase(ci.toString(), cj.toString()) == 0; + assertEquals(res1, res2, "si : " + si + " sj : " + sj); + res2 = StringUtils.indexOfIgnoreCase(ci.toString(), cj.toString()) == 0; + assertEquals(res1, res2, "si : " + si + " sj : " + sj); + res2 = StringUtils.lastIndexOfIgnoreCase(ci.toString(), cj.toString()) == 0; + assertEquals(res1, res2, "si : " + si + " sj : " + sj); } } } From c141bc961cb5cb84c47a21c3a5b0f15ab0035728 Mon Sep 17 00:00:00 2001 From: Jochen Wiedmann Date: Thu, 28 May 2020 22:52:46 +0200 Subject: [PATCH 0086/3230] Adding the Locks class. --- src/changes/changes.xml | 5 +- .../java/org/apache/commons/lang3/Locks.java | 116 ++++++++++++++++++ .../org/apache/commons/lang3/LocksTest.java | 73 +++++++++++ 3 files changed, 192 insertions(+), 2 deletions(-) create mode 100644 src/main/java/org/apache/commons/lang3/Locks.java create mode 100644 src/test/java/org/apache/commons/lang3/LocksTest.java diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 1df43f20b99..2204f329ff1 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -46,7 +46,7 @@ The type attribute can be add,update,fix,remove. - Fix Javdoc for StringUtils.appendIfMissingIgnoreCase() #507. + Fix Javadoc for StringUtils.appendIfMissingIgnoreCase() #507. org.junit-pioneer:junit-pioneer 0.5.4 -> 0.6.0. org.junit.jupiter:junit-jupiter 5.6.0 -> 5.6.1. com.github.spotbugs:spotbugs 4.0.0 -> 4.0.3. @@ -59,6 +59,7 @@ The type attribute can be add,update,fix,remove. (Javadoc) Fix return tag for throwableOf*() methods #518. Add ArrayUtils.isSameLength() to compare more array types #430. CharSequenceUtils.regionMatches is wrong dealing with Georgian. + Added the Locks class as a convenient possibility to deal with locked objects. @@ -275,7 +276,7 @@ The type attribute can be add,update,fix,remove. Enhance MethodUtils to allow invocation of private methods Fix implementation of StringUtils.getJaroWinklerDistance() Fix dead links in StringUtils.getLevenshteinDistance() javadoc - "\u2284":"⊄" mapping missing from EntityArrays#HTML40_EXTENDED_ESCAPE + "\u2284":"nsub" mapping missing from EntityArrays#HTML40_EXTENDED_ESCAPE Simplify ArrayUtils removeElements by using new decrementAndGet() method Add getAndIncrement/getAndDecrement/getAndAdd/incrementAndGet/decrementAndGet/addAndGet in Mutable* classes Optimize BitField constructor implementation diff --git a/src/main/java/org/apache/commons/lang3/Locks.java b/src/main/java/org/apache/commons/lang3/Locks.java new file mode 100644 index 00000000000..60b4f6aa164 --- /dev/null +++ b/src/main/java/org/apache/commons/lang3/Locks.java @@ -0,0 +1,116 @@ +/* + * 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.Objects; +import java.util.concurrent.locks.StampedLock; + +import org.apache.commons.lang3.Functions.FailableConsumer; +import org.apache.commons.lang3.Functions.FailableFunction; + + +/** Utility class for working with {@link java.util.concurrent.locks.Lock locked objects}. Locked objects are an + * alternative to synchronization. + * + * Locking is preferable, if there is a distinction between read access (multiple threads may have read + * access concurrently), and write access (only one thread may have write access at any given time. + * In comparison, synchronization doesn't support read access, because synchronized access is exclusive. + * + * Using this class is fairly straightforward: + *
      + *
    1. While still in single thread mode, create an instance of {@link Locks.Lock} by calling + * {@link #lock(Object)}, passing the object, which needs to be locked. Discard all + * references to the locked object. Instead, use references to the lock.
    2. + *
    3. If you want to access the locked object, create a {@link FailableConsumer}. The consumer + * will receive the locked object as a parameter. For convenience, the consumer may be + * implemented as a Lamba. Then invoke {@link Locks.Lock#runReadLocked(FailableConsumer)}, + * or {@link Locks.Lock#runWriteLocked(FailableConsumer)}, passing the consumer.
    4. + *
    5. As an alternative, if you need to produce a result object, you may use a + * {@link FailableFunction}. This function may also be implemented as a Lambda. To + * have the function executed, invoke {@link Locks.Lock#callReadLocked(FailableFunction)}, or + * {@link Locks.Lock#callWriteLocked(FailableFunction)}.
    6. + *
    + * + * Example: A thread safe logger class. + *
    + *   public class SimpleLogger {
    + *     private final Lock<PrintStream> lock;
    + *
    + *     public SimpleLogger(OutputStream out) {
    + *         PrintStream ps = new Printstream(out);
    + *         lock = Locks.lock(ps);
    + *     }
    + * 
    + *     public void log(String message) {
    + *         lock.runWriteLocked((ps) -> ps.println(message));
    + *     }
    + *
    + *     public void log(byte[] buffer) {
    + *         lock.runWriteLocked((ps) -> { ps.write(buffer); ps.println(); });
    + *     }
    + * 
    + */ +public class Locks { + public static class Lock { + private final O lockedObject; + private final StampedLock lock = new StampedLock(); + + public Lock(O lockedObject) { + this.lockedObject = Objects.requireNonNull(lockedObject, "Locked Object"); + } + + public void runReadLocked(FailableConsumer consumer) { + runLocked(lock.readLock(), consumer); + } + + public void runWriteLocked(FailableConsumer consumer) { + runLocked(lock.writeLock(), consumer); + } + + public T callReadLocked(FailableFunction function) { + return callLocked(lock.readLock(), function); + } + + public T callWriteLocked(FailableFunction function) { + return callLocked(lock.writeLock(), function); + } + + protected void runLocked(long stamp, FailableConsumer consumer) { + try { + consumer.accept(lockedObject); + } catch (Throwable t) { + throw Functions.rethrow(t); + } finally { + lock.unlock(stamp); + } + } + + protected T callLocked(long stamp, FailableFunction function) { + try { + return function.apply(lockedObject); + } catch (Throwable t) { + throw Functions.rethrow(t); + } finally { + lock.unlock(stamp); + } + } + } + + public static Locks.Lock lock(O object) { + return new Locks.Lock(object); + } +} diff --git a/src/test/java/org/apache/commons/lang3/LocksTest.java b/src/test/java/org/apache/commons/lang3/LocksTest.java new file mode 100644 index 00000000000..e2dd6b0b8aa --- /dev/null +++ b/src/test/java/org/apache/commons/lang3/LocksTest.java @@ -0,0 +1,73 @@ +/* + * 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 static org.junit.jupiter.api.Assertions.*; + +import org.apache.commons.lang3.Functions.FailableConsumer; +import org.apache.commons.lang3.Locks.Lock; +import org.junit.jupiter.api.Test; + +class LocksTest { + @Test + void testReadLock() throws Exception { + final long DELAY=3000; + final boolean[] booleanValues = new boolean[10]; + final Lock lock = Locks.lock(booleanValues); + final boolean[] runningValues = new boolean[10]; + + final long startTime = System.currentTimeMillis(); + for (int i = 0; i < booleanValues.length; i++) { + final int index = i; + final FailableConsumer consumer = (b) -> { + b[index] = false; + Thread.sleep(DELAY); + b[index] = true; + modify(runningValues, index, false); + }; + final Thread t = new Thread(() -> lock.runReadLocked(consumer)); + modify(runningValues, i, true); + t.start(); + } + while (someValueIsTrue(runningValues)) { + Thread.sleep(100); + } + final long endTime = System.currentTimeMillis(); + for (int i = 0; i < booleanValues.length; i++) { + assertTrue(booleanValues[i]); + } + // If our threads would be running in exclusive mode, then we'd need + // at least DELAY milliseconds for each. + assertTrue((endTime-startTime) < booleanValues.length*DELAY); + } + + protected void modify(boolean[] booleanArray, int offset, boolean value) { + synchronized(booleanArray) { + booleanArray[offset] = value; + } + } + protected boolean someValueIsTrue(boolean[] booleanArray) { + synchronized(booleanArray) { + for (int i = 0; i < booleanArray.length; i++) { + if (booleanArray[i]) { + return true; + } + } + return false; + } + } +} From f544897e49fc6c3e3970bf06ff74940bcd6d3505 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sat, 30 May 2020 11:00:18 -0400 Subject: [PATCH 0087/3230] Test major Java versions with GitHub actions as documented on https://github.com/actions/setup-java # WARNING: head commit changed in the meantime @Deprecated --- .github/workflows/maven.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml index 798263d1dd0..055919f1458 100644 --- a/.github/workflows/maven.yml +++ b/.github/workflows/maven.yml @@ -23,7 +23,7 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - java: [ '1.8', '11', '14' ] + java: [ 8, 11, 12, 13, 14 ] steps: - uses: actions/checkout@v1 From 3d4ed4a8ac63db1e51601ffc31fed44dccbb276c Mon Sep 17 00:00:00 2001 From: Jochen Wiedmann Date: Sun, 31 May 2020 22:18:02 +0200 Subject: [PATCH 0088/3230] Fixing Checkstyle warnings. Closes #532. --- .../java/org/apache/commons/lang3/Locks.java | 88 +++++++------- .../org/apache/commons/lang3/LocksTest.java | 115 +++++++++++------- 2 files changed, 113 insertions(+), 90 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/Locks.java b/src/main/java/org/apache/commons/lang3/Locks.java index 60b4f6aa164..6bb800b5cfe 100644 --- a/src/main/java/org/apache/commons/lang3/Locks.java +++ b/src/main/java/org/apache/commons/lang3/Locks.java @@ -25,11 +25,11 @@ /** Utility class for working with {@link java.util.concurrent.locks.Lock locked objects}. Locked objects are an * alternative to synchronization. - * + * * Locking is preferable, if there is a distinction between read access (multiple threads may have read * access concurrently), and write access (only one thread may have write access at any given time. * In comparison, synchronization doesn't support read access, because synchronized access is exclusive. - * + * * Using this class is fairly straightforward: *
      *
    1. While still in single thread mode, create an instance of {@link Locks.Lock} by calling @@ -54,7 +54,7 @@ * PrintStream ps = new Printstream(out); * lock = Locks.lock(ps); * } - * + * * public void log(String message) { * lock.runWriteLocked((ps) -> ps.println(message)); * } @@ -62,55 +62,55 @@ * public void log(byte[] buffer) { * lock.runWriteLocked((ps) -> { ps.write(buffer); ps.println(); }); * } - * + * */ public class Locks { - public static class Lock { - private final O lockedObject; - private final StampedLock lock = new StampedLock(); + public static class Lock { + private final O lockedObject; + private final StampedLock lock = new StampedLock(); - public Lock(O lockedObject) { - this.lockedObject = Objects.requireNonNull(lockedObject, "Locked Object"); - } + public Lock(O lockedObject) { + this.lockedObject = Objects.requireNonNull(lockedObject, "Locked Object"); + } - public void runReadLocked(FailableConsumer consumer) { - runLocked(lock.readLock(), consumer); - } + public void runReadLocked(FailableConsumer consumer) { + runLocked(lock.readLock(), consumer); + } - public void runWriteLocked(FailableConsumer consumer) { - runLocked(lock.writeLock(), consumer); - } + public void runWriteLocked(FailableConsumer consumer) { + runLocked(lock.writeLock(), consumer); + } - public T callReadLocked(FailableFunction function) { - return callLocked(lock.readLock(), function); - } + public T callReadLocked(FailableFunction function) { + return callLocked(lock.readLock(), function); + } - public T callWriteLocked(FailableFunction function) { - return callLocked(lock.writeLock(), function); - } + public T callWriteLocked(FailableFunction function) { + return callLocked(lock.writeLock(), function); + } - protected void runLocked(long stamp, FailableConsumer consumer) { - try { - consumer.accept(lockedObject); - } catch (Throwable t) { - throw Functions.rethrow(t); - } finally { - lock.unlock(stamp); - } - } + protected void runLocked(long stamp, FailableConsumer consumer) { + try { + consumer.accept(lockedObject); + } catch (Throwable t) { + throw Functions.rethrow(t); + } finally { + lock.unlock(stamp); + } + } - protected T callLocked(long stamp, FailableFunction function) { - try { - return function.apply(lockedObject); - } catch (Throwable t) { - throw Functions.rethrow(t); - } finally { - lock.unlock(stamp); - } - } - } + protected T callLocked(long stamp, FailableFunction function) { + try { + return function.apply(lockedObject); + } catch (Throwable t) { + throw Functions.rethrow(t); + } finally { + lock.unlock(stamp); + } + } + } - public static Locks.Lock lock(O object) { - return new Locks.Lock(object); - } + public static Locks.Lock lock(O object) { + return new Locks.Lock(object); + } } diff --git a/src/test/java/org/apache/commons/lang3/LocksTest.java b/src/test/java/org/apache/commons/lang3/LocksTest.java index e2dd6b0b8aa..5b08013957c 100644 --- a/src/test/java/org/apache/commons/lang3/LocksTest.java +++ b/src/test/java/org/apache/commons/lang3/LocksTest.java @@ -16,58 +16,81 @@ */ package org.apache.commons.lang3; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.function.LongConsumer; import org.apache.commons.lang3.Functions.FailableConsumer; import org.apache.commons.lang3.Locks.Lock; import org.junit.jupiter.api.Test; class LocksTest { - @Test - void testReadLock() throws Exception { - final long DELAY=3000; - final boolean[] booleanValues = new boolean[10]; - final Lock lock = Locks.lock(booleanValues); - final boolean[] runningValues = new boolean[10]; + private static final int NUMBER_OF_THREADS = 10; + + @Test + void testReadLock() throws Exception { + final long DELAY=3000; + /** If our threads are running concurrently, then we expect to be faster + * than running one after the other. + */ + runTest(DELAY, false, (l) -> assertTrue(l < NUMBER_OF_THREADS*DELAY)); + } + + void testWriteLock() throws Exception { + final long DELAY = 100; + /** If our threads are running concurrently, then we expect to be no faster + * than running one after the other. + */ + runTest(DELAY, true, (l) -> assertTrue(l >= NUMBER_OF_THREADS*DELAY)); + } + + private void runTest(long delay, boolean exclusiveLock, LongConsumer runTimeCheck) throws InterruptedException { + final boolean[] booleanValues = new boolean[10]; + final Lock lock = Locks.lock(booleanValues); + final boolean[] runningValues = new boolean[10]; - final long startTime = System.currentTimeMillis(); - for (int i = 0; i < booleanValues.length; i++) { - final int index = i; - final FailableConsumer consumer = (b) -> { - b[index] = false; - Thread.sleep(DELAY); - b[index] = true; - modify(runningValues, index, false); - }; - final Thread t = new Thread(() -> lock.runReadLocked(consumer)); - modify(runningValues, i, true); - t.start(); - } - while (someValueIsTrue(runningValues)) { - Thread.sleep(100); - } - final long endTime = System.currentTimeMillis(); - for (int i = 0; i < booleanValues.length; i++) { - assertTrue(booleanValues[i]); - } - // If our threads would be running in exclusive mode, then we'd need - // at least DELAY milliseconds for each. - assertTrue((endTime-startTime) < booleanValues.length*DELAY); - } + final long startTime = System.currentTimeMillis(); + for (int i = 0; i < booleanValues.length; i++) { + final int index = i; + final FailableConsumer consumer = (b) -> { + b[index] = false; + Thread.sleep(delay); + b[index] = true; + modify(runningValues, index, false); + }; + final Thread t = new Thread(() -> { + if (exclusiveLock) { + lock.runWriteLocked(consumer); + } else { + lock.runReadLocked(consumer); + } + }); + modify(runningValues, i, true); + t.start(); + } + while (someValueIsTrue(runningValues)) { + Thread.sleep(100); + } + final long endTime = System.currentTimeMillis(); + for (int i = 0; i < booleanValues.length; i++) { + assertTrue(booleanValues[i]); + } + runTimeCheck.accept(endTime-startTime); + } - protected void modify(boolean[] booleanArray, int offset, boolean value) { - synchronized(booleanArray) { - booleanArray[offset] = value; - } - } - protected boolean someValueIsTrue(boolean[] booleanArray) { - synchronized(booleanArray) { - for (int i = 0; i < booleanArray.length; i++) { - if (booleanArray[i]) { - return true; - } - } - return false; - } - } + protected void modify(boolean[] booleanArray, int offset, boolean value) { + synchronized(booleanArray) { + booleanArray[offset] = value; + } + } + protected boolean someValueIsTrue(boolean[] booleanArray) { + synchronized(booleanArray) { + for (int i = 0; i < booleanArray.length; i++) { + if (booleanArray[i]) { + return true; + } + } + return false; + } + } } From 115a6c64bc6dad12edaf3c5deaac7bffa0fa3b86 Mon Sep 17 00:00:00 2001 From: John Patrick <142304+nhojpatrick@users.noreply.github.com> Date: Sun, 1 Mar 2020 20:30:03 +0000 Subject: [PATCH 0089/3230] StreamsTest junit-jupiter --- .../org/apache/commons/lang3/StreamsTest.java | 170 ++++++++++-------- 1 file changed, 92 insertions(+), 78 deletions(-) diff --git a/src/test/java/org/apache/commons/lang3/StreamsTest.java b/src/test/java/org/apache/commons/lang3/StreamsTest.java index 0f618b63463..a5985aad31e 100644 --- a/src/test/java/org/apache/commons/lang3/StreamsTest.java +++ b/src/test/java/org/apache/commons/lang3/StreamsTest.java @@ -16,27 +16,37 @@ */ package org.apache.commons.lang3; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.Is.is; +import static org.hamcrest.core.IsEqual.equalTo; +import static org.hamcrest.core.IsNull.nullValue; +import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.fail; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.DynamicTest.dynamicTest; import java.lang.reflect.UndeclaredThrowableException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; +import java.util.stream.Stream; import org.apache.commons.lang3.Functions.FailableConsumer; import org.apache.commons.lang3.Functions.FailablePredicate; +import org.junit.jupiter.api.DynamicTest; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestFactory; +import org.junit.jupiter.api.function.Executable; import org.xml.sax.SAXException; class StreamsTest { + @Test void testSimpleStreamMap() { final List input = Arrays.asList("1", "2", "3", "4", "5", "6"); - final List output = Functions.stream(input).map(s -> Integer.valueOf(s)).collect(Collectors.toList()); + final List output = Functions.stream(input).map((s) -> Integer.valueOf(s)).collect(Collectors.toList()); assertEquals(6, output.size()); for (int i = 0; i < 6; i++) { assertEquals(i+1, output.get(i).intValue()); @@ -46,19 +56,16 @@ void testSimpleStreamMap() { @Test void testSimpleStreamMapFailing() { final List input = Arrays.asList("1", "2", "3", "4 ", "5", "6"); - try { - Functions.stream(input).map(s -> Integer.valueOf(s)).collect(Collectors.toList()); - fail("Expected Exception"); - } catch (final NumberFormatException nfe) { - assertEquals("For input string: \"4 \"", nfe.getMessage()); - } + final Executable testMethod = () -> Functions.stream(input).map((s) -> Integer.valueOf(s)).collect(Collectors.toList()); + final NumberFormatException thrown = assertThrows(NumberFormatException.class, testMethod); + assertEquals("For input string: \"4 \"", thrown.getMessage()); } @Test void testSimpleStreamForEach() { final List input = Arrays.asList("1", "2", "3", "4", "5", "6"); final List output = new ArrayList<>(); - Functions.stream(input).forEach(s -> output.add(Integer.valueOf(s))); + Functions.stream(input).forEach((s) -> output.add(Integer.valueOf(s))); assertEquals(6, output.size()); for (int i = 0; i < 6; i++) { assertEquals(i+1, output.get(i).intValue()); @@ -76,7 +83,7 @@ void testToArray() { } protected FailableConsumer asIntConsumer(final T pThrowable) { - return s -> { + return (s) -> { final Integer i = Integer.valueOf(s); if (i.intValue() == 4) { throw pThrowable; @@ -84,41 +91,47 @@ protected FailableConsumer asIntConsumer(final }; } - @Test - void testSimpleStreamForEachFailing() { + @TestFactory + Stream simpleStreamForEachFailing() { final List input = Arrays.asList("1", "2", "3", "4", "5", "6"); - final List output = new ArrayList<>(); - final IllegalArgumentException ise = new IllegalArgumentException("Invalid argument: 4"); - try { - Functions.stream(input).forEach(asIntConsumer(ise)); - fail("Expected Exception"); - } catch (final IllegalArgumentException e) { - assertSame(ise, e); - } - output.clear(); - final OutOfMemoryError oome = new OutOfMemoryError(); - try { - Functions.stream(input).forEach(asIntConsumer(oome)); - fail("Expected Exception"); - } catch (final Throwable t) { - assertSame(oome, t); - } - output.clear(); - final SAXException se = new SAXException(); - try { - Functions.stream(input).forEach(asIntConsumer(se)); - fail("Expected Exception"); - } catch (final UndeclaredThrowableException ute) { - assertSame(se, ute.getCause()); - } + + return Stream.of( + + dynamicTest("IllegalArgumentException", () -> { + final IllegalArgumentException ise = new IllegalArgumentException(); + final Executable testMethod = () -> Functions.stream(input) + .forEach(asIntConsumer(ise)); + final IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, testMethod); + assertThat(thrown.getMessage(), is(nullValue())); + }), + + dynamicTest("OutOfMemoryError", () -> { + final OutOfMemoryError oome = new OutOfMemoryError(); + final Executable oomeTestMethod = () -> Functions.stream(input) + .forEach(asIntConsumer(oome)); + final OutOfMemoryError oomeThrown = assertThrows(OutOfMemoryError.class, oomeTestMethod); + assertThat(oomeThrown.getMessage(), is(nullValue())); + }), + + dynamicTest("SAXException", () -> { + final SAXException se = new SAXException(); + final Executable seTestMethod = () -> Functions.stream(input) + .forEach(asIntConsumer(se)); + final UndeclaredThrowableException seThrown = assertThrows(UndeclaredThrowableException.class, seTestMethod); + assertAll( + () -> assertThat(seThrown.getMessage(), is(nullValue())), + () -> assertThat(seThrown.getCause(), is(equalTo(se))) + ); + }) + ); } @Test void testSimpleStreamFilter() { final List input = Arrays.asList("1", "2", "3", "4", "5", "6"); final List output = Functions.stream(input) - .map(s -> Integer.valueOf(s)) - .filter(i -> { + .map((s) -> Integer.valueOf(s)) + .filter((i) -> { return i.intValue() %2 == 0; }) .collect(Collectors.toList()); @@ -133,7 +146,7 @@ private void assertEvenNumbers(final List output) { } protected FailablePredicate asIntPredicate(final T pThrowable) { - return i -> { + return (i) -> { if (i.intValue() == 5) { if (pThrowable != null) { throw pThrowable; @@ -143,49 +156,50 @@ protected FailablePredicate asIntPredicate(fin }; } - @Test - void testSimpleStreamFilterFailing() { + @TestFactory + Stream simpleStreamFilterFailing() { final List input = Arrays.asList("1", "2", "3", "4", "5", "6"); final List output = Functions.stream(input) - .map(s -> Integer.valueOf(s)) + .map((s) -> Integer.valueOf(s)) .filter(asIntPredicate(null)) .collect(Collectors.toList()); assertEvenNumbers(output); - output.clear(); - final IllegalArgumentException iae = new IllegalArgumentException("Invalid argument: " + 5); - try { - Functions.stream(input) - .map(s -> Integer.valueOf(s)) - .filter(asIntPredicate(iae)) - .collect(Collectors.toList()); - fail("Expected Exception"); - } catch (final IllegalArgumentException e) { - assertSame(iae, e); - } - - output.clear(); - final OutOfMemoryError oome = new OutOfMemoryError(); - try { - Functions.stream(input) - .map(s -> Integer.valueOf(s)) - .filter(asIntPredicate(oome)) - .collect(Collectors.toList()); - fail("Expected Exception"); - } catch (final Throwable t) { - assertSame(oome, t); - } - - output.clear(); - final SAXException se = new SAXException(); - try { - Functions.stream(input) - .map(s -> Integer.valueOf(s)) - .filter(asIntPredicate(se)) - .collect(Collectors.toList()); - fail("Expected Exception"); - } catch (final UndeclaredThrowableException t) { - assertSame(se, t.getCause()); - } + return Stream.of( + + dynamicTest("IllegalArgumentException", () -> { + final IllegalArgumentException iae = new IllegalArgumentException("Invalid argument: " + 5); + final Executable testMethod = () -> Functions.stream(input) + .map((s) -> Integer.valueOf(s)) + .filter(asIntPredicate(iae)) + .collect(Collectors.toList()); + final IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, testMethod); + assertThat(thrown.getMessage(), is(equalTo("Invalid argument: " + 5))); + }), + + dynamicTest("OutOfMemoryError", () -> { + final OutOfMemoryError oome = new OutOfMemoryError(); + final Executable testMethod = () -> Functions.stream(input) + .map((s) -> Integer.valueOf(s)) + .filter(asIntPredicate(oome)) + .collect(Collectors.toList()); + final OutOfMemoryError thrown = assertThrows(OutOfMemoryError.class, testMethod); + assertThat(thrown.getMessage(), is(nullValue())); + }), + + dynamicTest("SAXException", () -> { + final SAXException se = new SAXException(); + final Executable testMethod = () -> Functions.stream(input) + .map((s) -> Integer.valueOf(s)) + .filter(asIntPredicate(se)) + .collect(Collectors.toList()); + final UndeclaredThrowableException thrown = assertThrows(UndeclaredThrowableException.class, testMethod); + assertAll( + () -> assertThat(thrown.getMessage(), is(nullValue())), + () -> assertThat(thrown.getCause(), is(equalTo(se))) + ); + }) + ); } + } From 598e8bd51e1e900d58b9ce21f2c806da447888fb Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Wed, 10 Jun 2020 09:07:59 -0400 Subject: [PATCH 0090/3230] Javadoc. --- src/main/java/org/apache/commons/lang3/Functions.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/Functions.java b/src/main/java/org/apache/commons/lang3/Functions.java index 4f580b792cb..2029b2e1195 100644 --- a/src/main/java/org/apache/commons/lang3/Functions.java +++ b/src/main/java/org/apache/commons/lang3/Functions.java @@ -103,7 +103,7 @@ public interface FailableBiConsumer { @FunctionalInterface public interface FailableFunction { /** - * Apply the function. + * Applies this function. * @param input the input for the function * @return the result of the function * @throws T if the function fails @@ -114,7 +114,7 @@ public interface FailableFunction { @FunctionalInterface public interface FailableBiFunction { /** - * Apply the function. + * Applies this function. * @param input1 the first input for the function * @param input2 the second input for the function * @return the result of the function From e968ad5a3f42f9eb7b3bd9ed95f827918d884e77 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Thu, 11 Jun 2020 09:43:11 -0400 Subject: [PATCH 0091/3230] Add missing @since 3.9 and 3.10 Javadoc tags. Clean up formatting. Clean up Javadocs. Sort methods in AB order. --- .../org/apache/commons/lang3/Functions.java | 575 ++++++++++-------- 1 file changed, 312 insertions(+), 263 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/Functions.java b/src/main/java/org/apache/commons/lang3/Functions.java index 2029b2e1195..896c93a29ab 100644 --- a/src/main/java/org/apache/commons/lang3/Functions.java +++ b/src/main/java/org/apache/commons/lang3/Functions.java @@ -33,46 +33,89 @@ import org.apache.commons.lang3.Streams.FailableStream; - -/** This class provides utility functions, and classes for working with the - * {@code java.util.function} package, or more generally, with Java 8 - * lambdas. - * More specifically, it attempts to address the fact that lambdas are supposed - * not to throw Exceptions, at least not checked Exceptions, aka instances of - * {@link Exception}. This enforces the use of constructs like - *
      {@code
      - *   Consumer consumer = (m) -> {
      - *       try {
      - *           m.invoke(o, args);
      - *       } catch (Throwable t) {
      - *           throw Functions.rethrow(t);
      - *       }
      - *   };
      +/**
      + * This class provides utility functions, and classes for working with the {@code java.util.function} package, or more
      + * generally, with Java 8 lambdas. More specifically, it attempts to address the fact that lambdas are supposed not to
      + * throw Exceptions, at least not checked Exceptions, AKA instances of {@link Exception}. This enforces the use of
      + * constructs like:
      + *
      + * 
      + * {
      + *     @code
      + *     Consumer consumer = (m) -> {
      + *         try {
      + *             m.invoke(o, args);
      + *         } catch (Throwable t) {
      + *             throw Functions.rethrow(t);
      + *         }
      + *     };
        * }
      - * By replacing a {@link java.util.function.Consumer Consumer<O>} with a - * {@link FailableConsumer FailableConsumer<O,? extends Throwable>}, this can be - * written like follows: - *
      {@code
      + *
      + * 

      + * By replacing a {@link java.util.function.Consumer Consumer<O>} with a {@link FailableConsumer + * FailableConsumer<O,? extends Throwable>}, this can be written like follows: + *

      + * + *
      + * {@code
        *   Functions.accept((m) -> m.invoke(o,args));
        * }
      - * Obviously, the second version is much more concise and the spirit of - * Lambda expressions is met better than the second version. + * + *

      + * Obviously, the second version is much more concise and the spirit of Lambda expressions is met better than the second + * version. + *

      + * @since 3.9 */ public class Functions { @FunctionalInterface - public interface FailableRunnable { + public interface FailableBiConsumer { + /** - * Runs the function. + * Accepts the consumer. + * + * @param object1 the first parameter for the consumable to accept + * @param object2 the second parameter for the consumable to accept + * @throws T if the consumer fails + */ + void accept(O1 object1, O2 object2) throws T; + } + + @FunctionalInterface + public interface FailableBiFunction { + + /** + * Applies this function. + * + * @param input1 the first input for the function + * @param input2 the second input for the function + * @return the result of the function * @throws T if the function fails */ - void run() throws T; + O apply(I1 input1, I2 input2) throws T; + } + + @FunctionalInterface + public interface FailableBiPredicate { + + /** + * Test the predicate. + * + * @param object1 the first object to test the predicate on + * @param object2 the second object to test the predicate on + * @return the predicate's evaluation + * @throws T if the predicate fails + */ + boolean test(O1 object1, O2 object2) throws T; } @FunctionalInterface public interface FailableCallable { + /** * Calls the callable. + * * @return The value returned from the callable * @throws T if the callable fails */ @@ -81,29 +124,23 @@ public interface FailableCallable { @FunctionalInterface public interface FailableConsumer { + + /** * Accepts the consumer. + * * @param object the parameter for the consumable to accept * @throws T if the consumer fails */ void accept(O object) throws T; } - @FunctionalInterface - public interface FailableBiConsumer { - /** - * Accepts the consumer. - * @param object1 the first parameter for the consumable to accept - * @param object2 the second parameter for the consumable to accept - * @throws T if the consumer fails - */ - void accept(O1 object1, O2 object2) throws T; - } - @FunctionalInterface public interface FailableFunction { + /** * Applies this function. + * * @param input the input for the function * @return the result of the function * @throws T if the function fails @@ -111,22 +148,12 @@ public interface FailableFunction { O apply(I input) throws T; } - @FunctionalInterface - public interface FailableBiFunction { - /** - * Applies this function. - * @param input1 the first input for the function - * @param input2 the second input for the function - * @return the result of the function - * @throws T if the function fails - */ - O apply(I1 input1, I2 input2) throws T; - } - @FunctionalInterface public interface FailablePredicate { + /** * Test the predicate. + * * @param object the object to test the predicate on * @return the predicate's evaluation * @throws T if the predicate fails @@ -135,21 +162,22 @@ public interface FailablePredicate { } @FunctionalInterface - public interface FailableBiPredicate { + public interface FailableRunnable { + /** - * Test the predicate. - * @param object1 the first object to test the predicate on - * @param object2 the second object to test the predicate on - * @return the predicate's evaluation - * @throws T if the predicate fails + * Runs the function. + * + * @throws T if the function fails */ - boolean test(O1 object1, O2 object2) throws T; + void run() throws T; } @FunctionalInterface public interface FailableSupplier { + /** * Supplies an object + * * @return the suppliers result * @throws T if the supplier fails */ @@ -157,35 +185,61 @@ public interface FailableSupplier { } /** - * Converts the given {@link FailableRunnable} into a standard {@link Runnable}. + * Consumes a consumer and rethrows any exception as a {@link RuntimeException}. * - * @param runnable a {@code FailableRunnable} - * @return a standard {@code Runnable} + * @param consumer the consumer to consume + * @param object1 the first object to consume by {@code consumer} + * @param object2 the second object to consume by {@code consumer} + * @param the type of the first argument the consumer accepts + * @param the type of the second argument the consumer accepts + * @param the type of checked exception the consumer may throw */ - public static Runnable asRunnable(final FailableRunnable runnable) { - return () -> run(runnable); + public static void accept(final FailableBiConsumer consumer, + final O1 object1, final O2 object2) { + run(() -> consumer.accept(object1, object2)); } /** - * Converts the given {@link FailableConsumer} into a standard {@link Consumer}. + * Consumes a consumer and rethrows any exception as a {@link RuntimeException}. * - * @param the type used by the consumers - * @param consumer a {@code FailableConsumer} - * @return a standard {@code Consumer} + * @param consumer the consumer to consume + * @param object the object to consume by {@code consumer} + * @param the type the consumer accepts + * @param the type of checked exception the consumer may throw */ - public static Consumer asConsumer(final FailableConsumer consumer) { - return input -> accept(consumer, input); + public static void accept(final FailableConsumer consumer, final O object) { + run(() -> consumer.accept(object)); } /** - * Converts the given {@link FailableCallable} into a standard {@link Callable}. + * Applies a function and rethrows any exception as a {@link RuntimeException}. * - * @param the type used by the callables - * @param callable a {@code FailableCallable} - * @return a standard {@code Callable} + * @param function the function to apply + * @param input1 the first input to apply {@code function} on + * @param input2 the second input to apply {@code function} on + * @param the type of the first argument the function accepts + * @param the type of the second argument the function accepts + * @param the return type of the function + * @param the type of checked exception the function may throw + * @return the value returned from the function */ - public static Callable asCallable(final FailableCallable callable) { - return () -> call(callable); + public static O apply(final FailableBiFunction function, + final I1 input1, final I2 input2) { + return get(() -> function.apply(input1, input2)); + } + + /** + * Applies a function and rethrows any exception as a {@link RuntimeException}. + * + * @param function the function to apply + * @param input the input to apply {@code function} on + * @param the type of the argument the function accepts + * @param the return type of the function + * @param the type of checked exception the function may throw + * @return the value returned from the function + */ + public static O apply(final FailableFunction function, final I input) { + return get(() -> function.apply(input)); } /** @@ -195,23 +249,12 @@ public static Callable asCallable(final FailableCallable callable) * @param the type of the second argument of the consumers * @param consumer a failable {@code BiConsumer} * @return a standard {@code BiConsumer} + * @since 3.10 */ public static BiConsumer asBiConsumer(final FailableBiConsumer consumer) { return (input1, input2) -> accept(consumer, input1, input2); } - /** - * Converts the given {@link FailableFunction} into a standard {@link Function}. - * - * @param the type of the input of the functions - * @param the type of the output of the functions - * @param function a {code FailableFunction} - * @return a standard {@code Function} - */ - public static Function asFunction(final FailableFunction function) { - return input -> apply(function, input); - } - /** * Converts the given {@link FailableBiFunction} into a standard {@link BiFunction}. * @@ -220,32 +263,83 @@ public static Function asFunction(final FailableFunction f * @param the type of the output of the functions * @param function a {@code FailableBiFunction} * @return a standard {@code BiFunction} + * @since 3.10 */ public static BiFunction asBiFunction(final FailableBiFunction function) { return (input1, input2) -> apply(function, input1, input2); } + /** + * Converts the given {@link FailableBiPredicate} into a standard {@link BiPredicate}. + * + * @param the type of the first argument used by the predicates + * @param the type of the second argument used by the predicates + * @param predicate a {@code FailableBiPredicate} + * @return a standard {@code BiPredicate} + * @since 3.10 + */ + public static BiPredicate asBiPredicate(final FailableBiPredicate predicate) { + return (input1, input2) -> test(predicate, input1, input2); + } + + /** + * Converts the given {@link FailableCallable} into a standard {@link Callable}. + * + * @param the type used by the callables + * @param callable a {@code FailableCallable} + * @return a standard {@code Callable} + * @since 3.10 + */ + public static Callable asCallable(final FailableCallable callable) { + return () -> call(callable); + } + + /** + * Converts the given {@link FailableConsumer} into a standard {@link Consumer}. + * + * @param the type used by the consumers + * @param consumer a {@code FailableConsumer} + * @return a standard {@code Consumer} + * @since 3.10 + */ + public static Consumer asConsumer(final FailableConsumer consumer) { + return input -> accept(consumer, input); + } + + /** + * Converts the given {@link FailableFunction} into a standard {@link Function}. + * + * @param the type of the input of the functions + * @param the type of the output of the functions + * @param function a {code FailableFunction} + * @return a standard {@code Function} + * @since 3.10 + */ + public static Function asFunction(final FailableFunction function) { + return input -> apply(function, input); + } + /** * Converts the given {@link FailablePredicate} into a standard {@link Predicate}. * * @param the type used by the predicates * @param predicate a {@code FailablePredicate} * @return a standard {@code Predicate} + * @since 3.10 */ public static Predicate asPredicate(final FailablePredicate predicate) { return input -> test(predicate, input); } /** - * Converts the given {@link FailableBiPredicate} into a standard {@link BiPredicate}. + * Converts the given {@link FailableRunnable} into a standard {@link Runnable}. * - * @param the type of the first argument used by the predicates - * @param the type of the second argument used by the predicates - * @param predicate a {@code FailableBiPredicate} - * @return a standard {@code BiPredicate} + * @param runnable a {@code FailableRunnable} + * @return a standard {@code Runnable} + * @since 3.10 */ - public static BiPredicate asBiPredicate(final FailableBiPredicate predicate) { - return (input1, input2) -> test(predicate, input1, input2); + public static Runnable asRunnable(final FailableRunnable runnable) { + return () -> run(runnable); } /** @@ -254,26 +348,15 @@ public static BiPredicate asBiPredicate(final FailableBiPredica * @param the type supplied by the suppliers * @param supplier a {@code FailableSupplier} * @return a standard {@code Supplier} + * @since 3.10 */ public static Supplier asSupplier(final FailableSupplier supplier) { return () -> get(supplier); } - /** - * Runs a runnable and rethrows any exception as a {@link RuntimeException}. - * @param runnable The runnable to run - * @param the type of checked exception the runnable may throw - */ - public static void run(final FailableRunnable runnable) { - try { - runnable.run(); - } catch (final Throwable t) { - throw rethrow(t); - } - } - /** * Calls a callable and rethrows any exception as a {@link RuntimeException}. + * * @param callable the callable to call * @param the return type of the callable * @param the type of checked exception the callable may throw @@ -284,71 +367,109 @@ public static O call(final FailableCallable calla } /** - * Consumes a consumer and rethrows any exception as a {@link RuntimeException}. - * @param consumer the consumer to consume - * @param object the object to consume by {@code consumer} - * @param the type the consumer accepts - * @param the type of checked exception the consumer may throw + * Invokes the supplier, and returns the result. + * + * @param supplier The supplier to invoke. + * @param The suppliers output type. + * @param The type of checked exception, which the supplier can throw. + * @return The object, which has been created by the supplier + * @since 3.10 */ - public static void accept(final FailableConsumer consumer, final O object) { - run(() -> consumer.accept(object)); + public static O get(final FailableSupplier supplier) { + try { + return supplier.get(); + } catch (final Throwable t) { + throw rethrow(t); + } } /** - * Consumes a consumer and rethrows any exception as a {@link RuntimeException}. - * @param consumer the consumer to consume - * @param object1 the first object to consume by {@code consumer} - * @param object2 the second object to consume by {@code consumer} - * @param the type of the first argument the consumer accepts - * @param the type of the second argument the consumer accepts - * @param the type of checked exception the consumer may throw + *

      + * Rethrows a {@link Throwable} as an unchecked exception. If the argument is already unchecked, namely a + * {@code RuntimeException} or {@code Error} then the argument will be rethrown without modification. If the + * exception is {@code IOException} then it will be wrapped into a {@code UncheckedIOException}. In every other + * cases the exception will be wrapped into a {@code + * UndeclaredThrowableException} + *

      + * + *

      + * Note that there is a declared return type for this method, even though it never returns. The reason for that is + * to support the usual pattern: + *

      + * + *
      +     * throw rethrow(myUncheckedException);
      + * + *

      + * instead of just calling the method. This pattern may help the Java compiler to recognize that at that point an + * exception will be thrown and the code flow analysis will not demand otherwise mandatory commands that could + * follow the method call, like a {@code return} statement from a value returning method. + *

      + * + * @param throwable The throwable to rethrow ossibly wrapped into an unchecked exception + * @return Never returns anything, this method never terminates normally. */ - public static void accept(final FailableBiConsumer consumer, final O1 object1, final O2 object2) { - run(() -> consumer.accept(object1, object2)); + public static RuntimeException rethrow(final Throwable throwable) { + Objects.requireNonNull(throwable, "throwable"); + if (throwable instanceof RuntimeException) { + throw (RuntimeException) throwable; + } else if (throwable instanceof Error) { + throw (Error) throwable; + } else if (throwable instanceof IOException) { + throw new UncheckedIOException((IOException) throwable); + } else { + throw new UndeclaredThrowableException(throwable); + } } /** - * Applies a function and rethrows any exception as a {@link RuntimeException}. - * @param function the function to apply - * @param input the input to apply {@code function} on - * @param the type of the argument the function accepts - * @param the return type of the function - * @param the type of checked exception the function may throw - * @return the value returned from the function + * Runs a runnable and rethrows any exception as a {@link RuntimeException}. + * + * @param runnable The runnable to run + * @param the type of checked exception the runnable may throw */ - public static O apply(final FailableFunction function, final I input) { - return get(() -> function.apply(input)); + public static void run(final FailableRunnable runnable) { + try { + runnable.run(); + } catch (final Throwable t) { + throw rethrow(t); + } } /** - * Applies a function and rethrows any exception as a {@link RuntimeException}. - * @param function the function to apply - * @param input1 the first input to apply {@code function} on - * @param input2 the second input to apply {@code function} on - * @param the type of the first argument the function accepts - * @param the type of the second argument the function accepts - * @param the return type of the function - * @param the type of checked exception the function may throw - * @return the value returned from the function + * Converts the given collection into a {@link FailableStream}. The {@link FailableStream} consists of the + * collections elements. Shortcut for + * + *
      +     * Functions.stream(collection.stream());
      + * + * @param collection The collection, which is being converted into a {@link FailableStream}. + * @param The collections element type. (In turn, the result streams element type.) + * @return The created {@link FailableStream}. + * @since 3.10 */ - public static O apply(final FailableBiFunction function, final I1 input1, final I2 input2) { - return get(() -> function.apply(input1, input2)); + public static FailableStream stream(final Collection collection) { + return new FailableStream<>(collection.stream()); } /** - * Tests a predicate and rethrows any exception as a {@link RuntimeException}. - * @param predicate the predicate to test - * @param object the input to test by {@code predicate} - * @param the type of argument the predicate tests - * @param the type of checked exception the predicate may throw - * @return the boolean value returned by the predicate + * Converts the given stream into a {@link FailableStream}. The {@link FailableStream} consists of the same + * elements, than the input stream. However, failable lambdas, like {@link FailablePredicate}, + * {@link FailableFunction}, and {@link FailableConsumer} may be applied, rather than {@link Predicate}, + * {@link Function}, {@link Consumer}, etc. + * + * @param stream The stream, which is being converted into a {@link FailableStream}. + * @param The streams element type. + * @return The created {@link FailableStream}. + * @since 3.10 */ - public static boolean test(final FailablePredicate predicate, final O object) { - return get(() -> predicate.test(object)); + public static FailableStream stream(final Stream stream) { + return new FailableStream<>(stream); } /** * Tests a predicate and rethrows any exception as a {@link RuntimeException}. + * * @param predicate the predicate to test * @param object1 the first input to test by {@code predicate} * @param object2 the second input to test by {@code predicate} @@ -357,85 +478,49 @@ public static boolean test(final FailablePredicate the type of checked exception the predicate may throw * @return the boolean value returned by the predicate */ - public static boolean test(final FailableBiPredicate predicate, final O1 object1, final O2 object2) { + public static boolean test(final FailableBiPredicate predicate, + final O1 object1, final O2 object2) { return get(() -> predicate.test(object1, object2)); } /** - * Invokes the supplier, and returns the result. - * @param supplier The supplier to invoke. - * @param The suppliers output type. - * @param The type of checked exception, which the supplier can throw. - * @return The object, which has been created by the supplier - */ - public static O get(final FailableSupplier supplier) { - try { - return supplier.get(); - } catch (final Throwable t) { - throw rethrow(t); - } - } - - /** - * Converts the given stream into a {@link FailableStream}. The - * {@link FailableStream} consists of the same elements, than the - * input stream. However, failable lambdas, like - * {@link FailablePredicate}, {@link FailableFunction}, and - * {@link FailableConsumer} may be applied, rather than - * {@link Predicate}, {@link Function}, {@link Consumer}, etc. - * @param stream The stream, which is being converted into a - * {@link FailableStream}. - * @param The streams element type. - * @return The created {@link FailableStream}. - */ - public static FailableStream stream(final Stream stream) { - return new FailableStream<>(stream); - } - - /** - * Converts the given collection into a {@link FailableStream}. - * The {@link FailableStream} consists of the collections - * elements. Shortcut for - *
      -     *   Functions.stream(collection.stream());
      -     * 
      - * @param collection The collection, which is being converted into a - * {@link FailableStream}. - * @param The collections element type. (In turn, the result - * streams element type.) - * @return The created {@link FailableStream}. + * Tests a predicate and rethrows any exception as a {@link RuntimeException}. + * + * @param predicate the predicate to test + * @param object the input to test by {@code predicate} + * @param the type of argument the predicate tests + * @param the type of checked exception the predicate may throw + * @return the boolean value returned by the predicate */ - public static FailableStream stream(final Collection collection) { - return new FailableStream<>(collection.stream()); + public static boolean test(final FailablePredicate predicate, final O object) { + return get(() -> predicate.test(object)); } - /** - * A simple try-with-resources implementation, that can be used, if your - * objects do not implement the {@link AutoCloseable} interface. The method - * executes the {@code action}. The method guarantees, that all - * the {@code resources} are being executed, in the given order, afterwards, - * and regardless of success, or failure. If either the original action, or - * any of the resource action fails, then the first failure (aka + * A simple try-with-resources implementation, that can be used, if your objects do not implement the + * {@link AutoCloseable} interface. The method executes the {@code action}. The method guarantees, that all + * the {@code resources} are being executed, in the given order, afterwards, and regardless of success, or failure. + * If either the original action, or any of the resource action fails, then the first failure (AKA * {@link Throwable} is rethrown. Example use: - *
      {@code
      -     *   final FileInputStream fis = new FileInputStream("my.file");
      -     *   Functions.tryWithResources(useInputStream(fis), null, () -> fis.close());
      +     *
      +     * 
      +     * {
      +     *     @code
      +     *     final FileInputStream fis = new FileInputStream("my.file");
      +     *     Functions.tryWithResources(useInputStream(fis), null, () -> fis.close());
            * }
      - * @param action The action to execute. This object will always - * be invoked. - * @param errorHandler An optional error handler, which will be invoked finally, - * if any error occurred. The error handler will receive the first - * error, aka {@link Throwable}. - * @param resources The resource actions to execute. All resource - * actions will be invoked, in the given order. A resource action is an - * instance of {@link FailableRunnable}, which will be executed. + * + * @param action The action to execute. This object will always be invoked. + * @param errorHandler An optional error handler, which will be invoked finally, if any error occurred. The error + * handler will receive the first error, AKA {@link Throwable}. + * @param resources The resource actions to execute. All resource actions will be invoked, in the given + * order. A resource action is an instance of {@link FailableRunnable}, which will be executed. * @see #tryWithResources(FailableRunnable, FailableRunnable...) */ @SafeVarargs public static void tryWithResources(final FailableRunnable action, - final FailableConsumer errorHandler, - final FailableRunnable... resources) { + final FailableConsumer errorHandler, + final FailableRunnable... resources) { final FailableConsumer actualErrorHandler; if (errorHandler == null) { actualErrorHandler = Functions::rethrow; @@ -474,63 +559,27 @@ public static void tryWithResources(final FailableRunnable } /** - * A simple try-with-resources implementation, that can be used, if your - * objects do not implement the {@link AutoCloseable} interface. The method - * executes the {@code action}. The method guarantees, that all - * the {@code resources} are being executed, in the given order, afterwards, - * and regardless of success, or failure. If either the original action, or - * any of the resource action fails, then the first failure (aka + * A simple try-with-resources implementation, that can be used, if your objects do not implement the + * {@link AutoCloseable} interface. The method executes the {@code action}. The method guarantees, that all + * the {@code resources} are being executed, in the given order, afterwards, and regardless of success, or failure. + * If either the original action, or any of the resource action fails, then the first failure (AKA * {@link Throwable} is rethrown. Example use: - *
      {@code
      -     *   final FileInputStream fis = new FileInputStream("my.file");
      -     *   Functions.tryWithResources(useInputStream(fis), () -> fis.close());
      +     *
      +     * 
      +     * {
      +     *     @code
      +     *     final FileInputStream fis = new FileInputStream("my.file");
      +     *     Functions.tryWithResources(useInputStream(fis), () -> fis.close());
            * }
      - * @param action The action to execute. This object will always - * be invoked. - * @param resources The resource actions to execute. All resource - * actions will be invoked, in the given order. A resource action is an - * instance of {@link FailableRunnable}, which will be executed. + * + * @param action The action to execute. This object will always be invoked. + * @param resources The resource actions to execute. All resource actions will be invoked, in the given + * order. A resource action is an instance of {@link FailableRunnable}, which will be executed. * @see #tryWithResources(FailableRunnable, FailableConsumer, FailableRunnable...) */ @SafeVarargs public static void tryWithResources(final FailableRunnable action, - final FailableRunnable... resources) { + final FailableRunnable... resources) { tryWithResources(action, null, resources); } - - /** - *

      Rethrows a {@link Throwable} as an unchecked exception. If the argument is - * already unchecked, namely a {@code RuntimeException} or {@code Error} then - * the argument will be rethrown without modification. If the exception is - * {@code IOException} then it will be wrapped into a {@code UncheckedIOException}. - * In every other cases the exception will be wrapped into a {@code - * UndeclaredThrowableException}

      - * - *

      Note that there is a declared return type for this method, even though it - * never returns. The reason for that is to support the usual pattern:

      - * - *
      -     *      throw rethrow(myUncheckedException);
      -     * 
      - * - *

      instead of just calling the method. This pattern may help the Java compiler to - * recognize that at that point an exception will be thrown and the code flow - * analysis will not demand otherwise mandatory commands that could follow the - * method call, like a {@code return} statement from a value returning method.

      - * - * @param throwable The throwable to rethrow ossibly wrapped into an unchecked exception - * @return Never returns anything, this method never terminates normally. - */ - public static RuntimeException rethrow(final Throwable throwable) { - Objects.requireNonNull(throwable, "throwable"); - if (throwable instanceof RuntimeException) { - throw (RuntimeException) throwable; - } else if (throwable instanceof Error) { - throw (Error) throwable; - } else if (throwable instanceof IOException) { - throw new UncheckedIOException((IOException) throwable); - } else { - throw new UndeclaredThrowableException(throwable); - } - } } From 8f7eb6ce207f354c83157b95bdf9848d59944650 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Thu, 11 Jun 2020 09:55:02 -0400 Subject: [PATCH 0092/3230] Simplify lambads. Fix Javadoc. --- .../org/apache/commons/lang3/Functions.java | 9 +++----- .../apache/commons/lang3/FunctionsTest.java | 4 ++-- .../org/apache/commons/lang3/LocksTest.java | 6 ++--- .../org/apache/commons/lang3/StreamsTest.java | 22 +++++++++---------- 4 files changed, 19 insertions(+), 22 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/Functions.java b/src/main/java/org/apache/commons/lang3/Functions.java index 896c93a29ab..9bbffa7dac8 100644 --- a/src/main/java/org/apache/commons/lang3/Functions.java +++ b/src/main/java/org/apache/commons/lang3/Functions.java @@ -40,8 +40,7 @@ * constructs like: * *
      - * {
      - *     @code
      + * {@code
        *     Consumer consumer = (m) -> {
        *         try {
        *             m.invoke(o, args);
      @@ -504,8 +503,7 @@ public static  boolean test(final FailablePredicate
      -     * {
      -     *     @code
      +     * {@code
            *     final FileInputStream fis = new FileInputStream("my.file");
            *     Functions.tryWithResources(useInputStream(fis), null, () -> fis.close());
            * }
      @@ -566,8 +564,7 @@ public static void tryWithResources(final FailableRunnable * {@link Throwable} is rethrown. Example use: * *
      -     * {
      -     *     @code
      +     * {@code
            *     final FileInputStream fis = new FileInputStream("my.file");
            *     Functions.tryWithResources(useInputStream(fis), () -> fis.close());
            * }
      diff --git a/src/test/java/org/apache/commons/lang3/FunctionsTest.java b/src/test/java/org/apache/commons/lang3/FunctionsTest.java index 50c3e184772..4180829f4c5 100644 --- a/src/test/java/org/apache/commons/lang3/FunctionsTest.java +++ b/src/test/java/org/apache/commons/lang3/FunctionsTest.java @@ -178,7 +178,7 @@ void testCallable() { @Test void testAsCallable() { FailureOnOddInvocations.invocation = 0; - final FailableCallable failableCallable = () -> new FailureOnOddInvocations(); + final FailableCallable failableCallable = FailureOnOddInvocations::new; final Callable callable = Functions.asCallable(failableCallable); final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, () -> callable.call()); final Throwable cause = e.getCause(); @@ -221,7 +221,7 @@ void testAcceptConsumer() { void testAsConsumer() { final IllegalStateException ise = new IllegalStateException(); final Testable testable = new Testable(ise); - final Consumer consumer = Functions.asConsumer(t -> t.test()); + final Consumer consumer = Functions.asConsumer(Testable::test); Throwable e = assertThrows(IllegalStateException.class, () -> consumer.accept(testable)); assertSame(ise, e); diff --git a/src/test/java/org/apache/commons/lang3/LocksTest.java b/src/test/java/org/apache/commons/lang3/LocksTest.java index 5b08013957c..18a81d9dbff 100644 --- a/src/test/java/org/apache/commons/lang3/LocksTest.java +++ b/src/test/java/org/apache/commons/lang3/LocksTest.java @@ -33,7 +33,7 @@ void testReadLock() throws Exception { /** If our threads are running concurrently, then we expect to be faster * than running one after the other. */ - runTest(DELAY, false, (l) -> assertTrue(l < NUMBER_OF_THREADS*DELAY)); + runTest(DELAY, false, l -> assertTrue(l < NUMBER_OF_THREADS*DELAY)); } void testWriteLock() throws Exception { @@ -41,7 +41,7 @@ void testWriteLock() throws Exception { /** If our threads are running concurrently, then we expect to be no faster * than running one after the other. */ - runTest(DELAY, true, (l) -> assertTrue(l >= NUMBER_OF_THREADS*DELAY)); + runTest(DELAY, true, l -> assertTrue(l >= NUMBER_OF_THREADS*DELAY)); } private void runTest(long delay, boolean exclusiveLock, LongConsumer runTimeCheck) throws InterruptedException { @@ -52,7 +52,7 @@ private void runTest(long delay, boolean exclusiveLock, LongConsumer runTimeChec final long startTime = System.currentTimeMillis(); for (int i = 0; i < booleanValues.length; i++) { final int index = i; - final FailableConsumer consumer = (b) -> { + final FailableConsumer consumer = b -> { b[index] = false; Thread.sleep(delay); b[index] = true; diff --git a/src/test/java/org/apache/commons/lang3/StreamsTest.java b/src/test/java/org/apache/commons/lang3/StreamsTest.java index a5985aad31e..3e17ed1bdc4 100644 --- a/src/test/java/org/apache/commons/lang3/StreamsTest.java +++ b/src/test/java/org/apache/commons/lang3/StreamsTest.java @@ -46,7 +46,7 @@ class StreamsTest { @Test void testSimpleStreamMap() { final List input = Arrays.asList("1", "2", "3", "4", "5", "6"); - final List output = Functions.stream(input).map((s) -> Integer.valueOf(s)).collect(Collectors.toList()); + final List output = Functions.stream(input).map(s -> Integer.valueOf(s)).collect(Collectors.toList()); assertEquals(6, output.size()); for (int i = 0; i < 6; i++) { assertEquals(i+1, output.get(i).intValue()); @@ -56,7 +56,7 @@ void testSimpleStreamMap() { @Test void testSimpleStreamMapFailing() { final List input = Arrays.asList("1", "2", "3", "4 ", "5", "6"); - final Executable testMethod = () -> Functions.stream(input).map((s) -> Integer.valueOf(s)).collect(Collectors.toList()); + final Executable testMethod = () -> Functions.stream(input).map(s -> Integer.valueOf(s)).collect(Collectors.toList()); final NumberFormatException thrown = assertThrows(NumberFormatException.class, testMethod); assertEquals("For input string: \"4 \"", thrown.getMessage()); } @@ -65,7 +65,7 @@ void testSimpleStreamMapFailing() { void testSimpleStreamForEach() { final List input = Arrays.asList("1", "2", "3", "4", "5", "6"); final List output = new ArrayList<>(); - Functions.stream(input).forEach((s) -> output.add(Integer.valueOf(s))); + Functions.stream(input).forEach(s -> output.add(Integer.valueOf(s))); assertEquals(6, output.size()); for (int i = 0; i < 6; i++) { assertEquals(i+1, output.get(i).intValue()); @@ -83,7 +83,7 @@ void testToArray() { } protected FailableConsumer asIntConsumer(final T pThrowable) { - return (s) -> { + return s -> { final Integer i = Integer.valueOf(s); if (i.intValue() == 4) { throw pThrowable; @@ -130,8 +130,8 @@ Stream simpleStreamForEachFailing() { void testSimpleStreamFilter() { final List input = Arrays.asList("1", "2", "3", "4", "5", "6"); final List output = Functions.stream(input) - .map((s) -> Integer.valueOf(s)) - .filter((i) -> { + .map(s -> Integer.valueOf(s)) + .filter(i -> { return i.intValue() %2 == 0; }) .collect(Collectors.toList()); @@ -146,7 +146,7 @@ private void assertEvenNumbers(final List output) { } protected FailablePredicate asIntPredicate(final T pThrowable) { - return (i) -> { + return i -> { if (i.intValue() == 5) { if (pThrowable != null) { throw pThrowable; @@ -160,7 +160,7 @@ protected FailablePredicate asIntPredicate(fin Stream simpleStreamFilterFailing() { final List input = Arrays.asList("1", "2", "3", "4", "5", "6"); final List output = Functions.stream(input) - .map((s) -> Integer.valueOf(s)) + .map(s -> Integer.valueOf(s)) .filter(asIntPredicate(null)) .collect(Collectors.toList()); assertEvenNumbers(output); @@ -170,7 +170,7 @@ Stream simpleStreamFilterFailing() { dynamicTest("IllegalArgumentException", () -> { final IllegalArgumentException iae = new IllegalArgumentException("Invalid argument: " + 5); final Executable testMethod = () -> Functions.stream(input) - .map((s) -> Integer.valueOf(s)) + .map(s -> Integer.valueOf(s)) .filter(asIntPredicate(iae)) .collect(Collectors.toList()); final IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, testMethod); @@ -180,7 +180,7 @@ Stream simpleStreamFilterFailing() { dynamicTest("OutOfMemoryError", () -> { final OutOfMemoryError oome = new OutOfMemoryError(); final Executable testMethod = () -> Functions.stream(input) - .map((s) -> Integer.valueOf(s)) + .map(s -> Integer.valueOf(s)) .filter(asIntPredicate(oome)) .collect(Collectors.toList()); final OutOfMemoryError thrown = assertThrows(OutOfMemoryError.class, testMethod); @@ -190,7 +190,7 @@ Stream simpleStreamFilterFailing() { dynamicTest("SAXException", () -> { final SAXException se = new SAXException(); final Executable testMethod = () -> Functions.stream(input) - .map((s) -> Integer.valueOf(s)) + .map(s -> Integer.valueOf(s)) .filter(asIntPredicate(se)) .collect(Collectors.toList()); final UndeclaredThrowableException thrown = assertThrows(UndeclaredThrowableException.class, testMethod); From 42a73e149913176417fad0d98d4cce3765a7cc50 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Fri, 12 Jun 2020 09:01:16 -0400 Subject: [PATCH 0093/3230] Add missing Javadoc. --- .../org/apache/commons/lang3/Functions.java | 86 ++++++++++++++++--- 1 file changed, 72 insertions(+), 14 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/Functions.java b/src/main/java/org/apache/commons/lang3/Functions.java index 9bbffa7dac8..12749ea86f5 100644 --- a/src/main/java/org/apache/commons/lang3/Functions.java +++ b/src/main/java/org/apache/commons/lang3/Functions.java @@ -68,6 +68,13 @@ */ public class Functions { + /** + * A functional interface like {@link BiConsumer} that declares a Throwable. + * + * @param Consumed type 1. + * @param Consumed type 2. + * @param Thrown exception. + */ @FunctionalInterface public interface FailableBiConsumer { @@ -81,8 +88,16 @@ public interface FailableBiConsumer { void accept(O1 object1, O2 object2) throws T; } + /** + * A functional interface like {@link BiFunction} that declares a Throwable. + * + * @param Input type 1. + * @param Input type 2. + * @param Return type. + * @param Thrown exception. + */ @FunctionalInterface - public interface FailableBiFunction { + public interface FailableBiFunction { /** * Applies this function. @@ -92,25 +107,38 @@ public interface FailableBiFunction { * @return the result of the function * @throws T if the function fails */ - O apply(I1 input1, I2 input2) throws T; + R apply(I1 input1, I2 input2) throws T; } + /** + * A functional interface like {@link BiPredicate} that declares a Throwable. + * + * @param Predicate type 1. + * @param Predicate type 2. + * @param Thrown exception. + */ @FunctionalInterface - public interface FailableBiPredicate { + public interface FailableBiPredicate { /** - * Test the predicate. + * Tests the predicate. * * @param object1 the first object to test the predicate on * @param object2 the second object to test the predicate on * @return the predicate's evaluation * @throws T if the predicate fails */ - boolean test(O1 object1, O2 object2) throws T; + boolean test(I1 object1, I2 object2) throws T; } + /** + * A functional interface like {@link java.util.concurrent.Callable} that declares a Throwable. + * + * @param Return type. + * @param Thrown exception. + */ @FunctionalInterface - public interface FailableCallable { + public interface FailableCallable { /** * Calls the callable. @@ -118,9 +146,15 @@ public interface FailableCallable { * @return The value returned from the callable * @throws T if the callable fails */ - O call() throws T; + R call() throws T; } + /** + * A functional interface like {@link Consumer} that declares a Throwable. + * + * @param Consumed type 1. + * @param Thrown exception. + */ @FunctionalInterface public interface FailableConsumer { @@ -134,8 +168,15 @@ public interface FailableConsumer { void accept(O object) throws T; } + /** + * A functional interface like {@link Function} that declares a Throwable. + * + * @param Input type 1. + * @param Return type. + * @param Thrown exception. + */ @FunctionalInterface - public interface FailableFunction { + public interface FailableFunction { /** * Applies this function. @@ -144,22 +185,33 @@ public interface FailableFunction { * @return the result of the function * @throws T if the function fails */ - O apply(I input) throws T; + R apply(I input) throws T; } + /** + * A functional interface like {@link Predicate} that declares a Throwable. + * + * @param Predicate type 1. + * @param Thrown exception. + */ @FunctionalInterface - public interface FailablePredicate { + public interface FailablePredicate { /** - * Test the predicate. + * Tests the predicate. * * @param object the object to test the predicate on * @return the predicate's evaluation * @throws T if the predicate fails */ - boolean test(O object) throws T; + boolean test(I object) throws T; } + /** + * A functional interface like {@link Runnable} that declares a Throwable. + * + * @param Thrown exception. + */ @FunctionalInterface public interface FailableRunnable { @@ -171,8 +223,14 @@ public interface FailableRunnable { void run() throws T; } + /** + * A functional interface like {@link Supplier} that declares a Throwable. + * + * @param Return type. + * @param Thrown exception. + */ @FunctionalInterface - public interface FailableSupplier { + public interface FailableSupplier { /** * Supplies an object @@ -180,7 +238,7 @@ public interface FailableSupplier { * @return the suppliers result * @throws T if the supplier fails */ - O get() throws T; + R get() throws T; } /** From 53aa7a2e9a4d0e186139dc72ddc9709595c2183a Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Fri, 12 Jun 2020 09:48:06 -0400 Subject: [PATCH 0094/3230] Fix build on Java 15-ea. --- pom.xml | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 871571c2e95..82223df21ff 100644 --- a/pom.xml +++ b/pom.xml @@ -772,8 +772,18 @@ ${basedir}/spotbugs-exclude-filter.xml + + org.apache.felix + maven-bundle-plugin + + + biz.aQute.bnd + biz.aQute.bndlib + 5.1.0 + + + - From d88f70e8ff3e73981809ddc530c19288c1f092c5 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Fri, 12 Jun 2020 11:35:37 -0400 Subject: [PATCH 0095/3230] [LANG-1568] FailableBooleanSupplier, FailableIntSupplier, FailableLongSupplier, FailableDoubleSupplier. --- src/changes/changes.xml | 1 + .../org/apache/commons/lang3/Functions.java | 144 ++++++++- .../apache/commons/lang3/FunctionsTest.java | 275 ++++++++++++++---- 3 files changed, 367 insertions(+), 53 deletions(-) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 2204f329ff1..a51e645f943 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -60,6 +60,7 @@ The type attribute can be add,update,fix,remove. Add ArrayUtils.isSameLength() to compare more array types #430. CharSequenceUtils.regionMatches is wrong dealing with Georgian. Added the Locks class as a convenient possibility to deal with locked objects. + Add to Functions: FailableBooleanSupplier, FailableIntSupplier, FailableLongSupplier, FailableDoubleSupplier. diff --git a/src/main/java/org/apache/commons/lang3/Functions.java b/src/main/java/org/apache/commons/lang3/Functions.java index 12749ea86f5..ae03211a9ae 100644 --- a/src/main/java/org/apache/commons/lang3/Functions.java +++ b/src/main/java/org/apache/commons/lang3/Functions.java @@ -25,8 +25,12 @@ import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.BiPredicate; +import java.util.function.BooleanSupplier; import java.util.function.Consumer; +import java.util.function.DoubleSupplier; import java.util.function.Function; +import java.util.function.IntSupplier; +import java.util.function.LongSupplier; import java.util.function.Predicate; import java.util.function.Supplier; import java.util.stream.Stream; @@ -235,12 +239,84 @@ public interface FailableSupplier { /** * Supplies an object * - * @return the suppliers result + * @return a result * @throws T if the supplier fails */ R get() throws T; } + /** + * A functional interface like {@link BooleanSupplier} that declares a Throwable. + * + * @param Thrown exception. + * @since 3.11 + */ + @FunctionalInterface + public interface FailableBooleanSupplier { + + /** + * Supplies a boolean. + * + * @return a result + * @throws T if the supplier fails + */ + boolean getAsBoolean() throws T; + } + + /** + * A functional interface like {@link DoubleSupplier} that declares a Throwable. + * + * @param Thrown exception. + * @since 3.11 + */ + @FunctionalInterface + public interface FailableDoubleSupplier { + + /** + * Supplies a double. + * + * @return a result + * @throws T if the supplier fails + */ + double getAsDouble() throws T; + } + + /** + * A functional interface like {@link IntSupplier} that declares a Throwable. + * + * @param Thrown exception. + * @since 3.11 + */ + @FunctionalInterface + public interface FailableIntSupplier { + + /** + * Supplies an int. + * + * @return a result + * @throws T if the supplier fails + */ + int getAsInt() throws T; + } + + /** + * A functional interface like {@link LongSupplier} that declares a Throwable. + * + * @param Thrown exception. + * @since 3.11 + */ + @FunctionalInterface + public interface FailableLongSupplier { + + /** + * Supplies a long. + * + * @return a result + * @throws T if the supplier fails + */ + long getAsLong() throws T; + } + /** * Consumes a consumer and rethrows any exception as a {@link RuntimeException}. * @@ -424,7 +500,7 @@ public static O call(final FailableCallable calla } /** - * Invokes the supplier, and returns the result. + * Invokes a supplier, and returns the result. * * @param supplier The supplier to invoke. * @param The suppliers output type. @@ -440,6 +516,70 @@ public static O get(final FailableSupplier suppli } } + /** + * Invokes a boolean supplier, and returns the result. + * + * @param supplier The boolean supplier to invoke. + * @param The type of checked exception, which the supplier can throw. + * @return The boolean, which has been created by the supplier + * @since 3.11 + */ + public static boolean getAsBoolean(final FailableBooleanSupplier supplier) { + try { + return supplier.getAsBoolean(); + } catch (final Throwable t) { + throw rethrow(t); + } + } + + /** + * Invokes a double supplier, and returns the result. + * + * @param supplier The double supplier to invoke. + * @param The type of checked exception, which the supplier can throw. + * @return The boolean, which has been created by the supplier + * @since 3.11 + */ + public static double getAsDouble(final FailableDoubleSupplier supplier) { + try { + return supplier.getAsDouble(); + } catch (final Throwable t) { + throw rethrow(t); + } + } + + /** + * Invokes an int supplier, and returns the result. + * + * @param supplier The int supplier to invoke. + * @param The type of checked exception, which the supplier can throw. + * @return The boolean, which has been created by the supplier + * @since 3.11 + */ + public static int getAsInt(final FailableIntSupplier supplier) { + try { + return supplier.getAsInt(); + } catch (final Throwable t) { + throw rethrow(t); + } + } + + /** + * Invokes a long supplier, and returns the result. + * + * @param supplier The long supplier to invoke. + * @param The type of checked exception, which the supplier can throw. + * @return The boolean, which has been created by the supplier + * @since 3.11 + */ + public static long getAsLong(final FailableLongSupplier supplier) { + try { + return supplier.getAsLong(); + } catch (final Throwable t) { + throw rethrow(t); + } + } + /** *

      * Rethrows a {@link Throwable} as an unchecked exception. If the argument is already unchecked, namely a diff --git a/src/test/java/org/apache/commons/lang3/FunctionsTest.java b/src/test/java/org/apache/commons/lang3/FunctionsTest.java index 4180829f4c5..63375cd0197 100644 --- a/src/test/java/org/apache/commons/lang3/FunctionsTest.java +++ b/src/test/java/org/apache/commons/lang3/FunctionsTest.java @@ -16,14 +16,12 @@ */ package org.apache.commons.lang3; -import org.apache.commons.lang3.Functions.FailableBiConsumer; -import org.apache.commons.lang3.Functions.FailableBiFunction; -import org.apache.commons.lang3.Functions.FailableCallable; -import org.apache.commons.lang3.Functions.FailableConsumer; -import org.apache.commons.lang3.Functions.FailableFunction; -import org.apache.commons.lang3.Functions.FailableSupplier; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.io.UncheckedIOException; @@ -37,24 +35,29 @@ import java.util.function.Predicate; import java.util.function.Supplier; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; +import org.apache.commons.lang3.Functions.FailableBiConsumer; +import org.apache.commons.lang3.Functions.FailableBiFunction; +import org.apache.commons.lang3.Functions.FailableCallable; +import org.apache.commons.lang3.Functions.FailableConsumer; +import org.apache.commons.lang3.Functions.FailableFunction; +import org.apache.commons.lang3.Functions.FailableSupplier; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; class FunctionsTest { + public static class SomeException extends Exception { + private static final long serialVersionUID = -4965704778119283411L; private Throwable t; - SomeException(final String pMsg) { - super(pMsg); + SomeException(final String message) { + super(message); } - public void setThrowable(final Throwable pThrowable) { - t = pThrowable; + public void setThrowable(final Throwable throwable) { + t = throwable; } public void test() throws Throwable { @@ -63,6 +66,7 @@ public void test() throws Throwable { } } } + public static class Testable { private Throwable t; @@ -70,48 +74,99 @@ public static class Testable { t = pTh; } - public void setThrowable(final Throwable pThrowable) { - t = pThrowable; + public void setThrowable(final Throwable throwable) { + t = throwable; } public void test() throws Throwable { test(t); } - public void test(final Throwable pThrowable) throws Throwable { - if (pThrowable != null) { - throw pThrowable; + public void test(final Throwable throwable) throws Throwable { + if (throwable != null) { + throw throwable; + } + } + + public Integer testInteger() throws Throwable { + return testInteger(t); + } + + public int testIntPrimitive() throws Throwable { + return testIntPrimitive(t); + } + + public long testLongPrimitive() throws Throwable { + return testLongPrimitive(t); + } + + public boolean testBooleanPrimitive() throws Throwable { + return testBooleanPrimitive(t); + } + + public double testDoublePrimitive() throws Throwable { + return testDoublePrimitive(t); + } + + public Integer testInteger(final Throwable throwable) throws Throwable { + if (throwable != null) { + throw throwable; } + return 0; } - public Integer testInt() throws Throwable { - return testInt(t); + public int testIntPrimitive(final Throwable throwable) throws Throwable { + if (throwable != null) { + throw throwable; + } + return 0; } - public Integer testInt(final Throwable pThrowable) throws Throwable { - if (pThrowable != null) { - throw pThrowable; + public double testDoublePrimitive(final Throwable throwable) throws Throwable { + if (throwable != null) { + throw throwable; } return 0; } + + public long testLongPrimitive(final Throwable throwable) throws Throwable { + if (throwable != null) { + throw throwable; + } + return 0; + } + + public boolean testBooleanPrimitive(final Throwable throwable) throws Throwable { + if (throwable != null) { + throw throwable; + } + return false; + } } public static class FailureOnOddInvocations { - private static int invocation; + private static int invocations; private static void throwOnOdd() throws SomeException { - final int i = ++invocation; + final int i = ++invocations; if (i % 2 == 1) { throw new SomeException("Odd Invocation: " + i); } } + static boolean failingBool() throws SomeException { throwOnOdd(); return true; } + FailureOnOddInvocations() throws SomeException { throwOnOdd(); } + + boolean getAsBoolean() throws SomeException { + throwOnOdd(); + return true; + } } public static class CloseableObject { @@ -138,20 +193,20 @@ public boolean isClosed() { @Test void testRunnable() { - FailureOnOddInvocations.invocation = 0; + FailureOnOddInvocations.invocations = 0; final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, () -> Functions.run(FailureOnOddInvocations::new)); final Throwable cause = e.getCause(); assertNotNull(cause); assertTrue(cause instanceof SomeException); assertEquals("Odd Invocation: 1", cause.getMessage()); - // Even invocation, should not throw an exception + // Even invocations, should not throw an exception Functions.run(FailureOnOddInvocations::new); } @Test void testAsRunnable() { - FailureOnOddInvocations.invocation = 0; + FailureOnOddInvocations.invocations = 0; final Runnable runnable = Functions.asRunnable(FailureOnOddInvocations::new); final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, () -> runnable.run()); final Throwable cause = e.getCause(); @@ -159,13 +214,13 @@ void testAsRunnable() { assertTrue(cause instanceof SomeException); assertEquals("Odd Invocation: 1", cause.getMessage()); - // Even invocation, should not throw an exception + // Even invocations, should not throw an exception runnable.run(); } @Test void testCallable() { - FailureOnOddInvocations.invocation = 0; + FailureOnOddInvocations.invocations = 0; final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, () -> Functions.run(FailureOnOddInvocations::new)); final Throwable cause = e.getCause(); assertNotNull(cause); @@ -177,7 +232,7 @@ void testCallable() { @Test void testAsCallable() { - FailureOnOddInvocations.invocation = 0; + FailureOnOddInvocations.invocations = 0; final FailableCallable failableCallable = FailureOnOddInvocations::new; final Callable callable = Functions.asCallable(failableCallable); final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, () -> callable.call()); @@ -292,23 +347,23 @@ void testAsBiConsumer() { public void testApplyFunction() { final IllegalStateException ise = new IllegalStateException(); final Testable testable = new Testable(ise); - Throwable e = assertThrows(IllegalStateException.class, () -> Functions.apply(Testable::testInt, testable)); + Throwable e = assertThrows(IllegalStateException.class, () -> Functions.apply(Testable::testInteger, testable)); assertSame(ise, e); final Error error = new OutOfMemoryError(); testable.setThrowable(error); - e = assertThrows(OutOfMemoryError.class, () -> Functions.apply(Testable::testInt, testable)); + e = assertThrows(OutOfMemoryError.class, () -> Functions.apply(Testable::testInteger, testable)); assertSame(error, e); final IOException ioe = new IOException("Unknown I/O error"); testable.setThrowable(ioe); - e = assertThrows(UncheckedIOException.class, () -> Functions.apply(Testable::testInt, testable)); + e = assertThrows(UncheckedIOException.class, () -> Functions.apply(Testable::testInteger, testable)); final Throwable t = e.getCause(); assertNotNull(t); assertSame(ioe, t); testable.setThrowable(null); - final Integer i = Functions.apply(Testable::testInt, testable); + final Integer i = Functions.apply(Testable::testInteger, testable); assertNotNull(i); assertEquals(0, i.intValue()); } @@ -319,7 +374,7 @@ public void testAsFunction() { final Testable testable = new Testable(ise); final FailableFunction failableFunction = th -> { testable.setThrowable(th); - return Integer.valueOf(testable.testInt()); + return Integer.valueOf(testable.testInteger()); }; final Function function = Functions.asFunction(failableFunction); Throwable e = assertThrows(IllegalStateException.class, () -> function.apply(ise)); @@ -344,20 +399,20 @@ public void testAsFunction() { public void testApplyBiFunction() { final IllegalStateException ise = new IllegalStateException(); final Testable testable = new Testable(null); - Throwable e = assertThrows(IllegalStateException.class, () -> Functions.apply(Testable::testInt, testable, ise)); + Throwable e = assertThrows(IllegalStateException.class, () -> Functions.apply(Testable::testInteger, testable, ise)); assertSame(ise, e); final Error error = new OutOfMemoryError(); - e = assertThrows(OutOfMemoryError.class, () -> Functions.apply(Testable::testInt, testable, error)); + e = assertThrows(OutOfMemoryError.class, () -> Functions.apply(Testable::testInteger, testable, error)); assertSame(error, e); final IOException ioe = new IOException("Unknown I/O error"); - e = assertThrows(UncheckedIOException.class, () -> Functions.apply(Testable::testInt, testable, ioe)); + e = assertThrows(UncheckedIOException.class, () -> Functions.apply(Testable::testInteger, testable, ioe)); final Throwable t = e.getCause(); assertNotNull(t); assertSame(ioe, t); - final Integer i = Functions.apply(Testable::testInt, testable, (Throwable) null); + final Integer i = Functions.apply(Testable::testInteger, testable, (Throwable) null); assertNotNull(i); assertEquals(0, i.intValue()); } @@ -368,7 +423,7 @@ public void testAsBiFunction() { final Testable testable = new Testable(ise); final FailableBiFunction failableBiFunction = (t, th) -> { t.setThrowable(th); - return Integer.valueOf(t.testInt()); + return Integer.valueOf(t.testInteger()); }; final BiFunction biFunction = Functions.asBiFunction(failableBiFunction); Throwable e = assertThrows(IllegalStateException.class, () -> biFunction.apply(testable, ise)); @@ -391,7 +446,7 @@ public void testAsBiFunction() { @Test public void testGetFromSupplier() { - FailureOnOddInvocations.invocation = 0; + FailureOnOddInvocations.invocations = 0; final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, () -> Functions.run(FailureOnOddInvocations::new)); final Throwable cause = e.getCause(); assertNotNull(cause); @@ -401,10 +456,129 @@ public void testGetFromSupplier() { assertNotNull(instance); } + @Test + public void testGetSupplier() { + final IllegalStateException ise = new IllegalStateException(); + final Testable testable = new Testable(ise); + Throwable e = assertThrows(IllegalStateException.class, () -> Functions.get(testable::testInteger)); + assertSame(ise, e); + + final Error error = new OutOfMemoryError(); + testable.setThrowable(error); + e = assertThrows(OutOfMemoryError.class, () -> Functions.get(testable::testInteger)); + assertSame(error, e); + + final IOException ioe = new IOException("Unknown I/O error"); + testable.setThrowable(ioe); + e = assertThrows(UncheckedIOException.class, () -> Functions.get(testable::testInteger)); + final Throwable t = e.getCause(); + assertNotNull(t); + assertSame(ioe, t); + + testable.setThrowable(null); + final Integer i = Functions.apply(Testable::testInteger, testable); + assertNotNull(i); + assertEquals(0, i.intValue()); + } + + @Test + public void testGetAsBooleanSupplier() { + final IllegalStateException ise = new IllegalStateException(); + final Testable testable = new Testable(ise); + Throwable e = assertThrows(IllegalStateException.class, () -> Functions.getAsBoolean(testable::testBooleanPrimitive)); + assertSame(ise, e); + + final Error error = new OutOfMemoryError(); + testable.setThrowable(error); + e = assertThrows(OutOfMemoryError.class, () -> Functions.getAsBoolean(testable::testBooleanPrimitive)); + assertSame(error, e); + + final IOException ioe = new IOException("Unknown I/O error"); + testable.setThrowable(ioe); + e = assertThrows(UncheckedIOException.class, () -> Functions.getAsBoolean(testable::testBooleanPrimitive)); + final Throwable t = e.getCause(); + assertNotNull(t); + assertSame(ioe, t); + + testable.setThrowable(null); + assertFalse(Functions.getAsBoolean(testable::testBooleanPrimitive)); + } + + @Test + public void testGetAsDoubleSupplier() { + final IllegalStateException ise = new IllegalStateException(); + final Testable testable = new Testable(ise); + Throwable e = assertThrows(IllegalStateException.class, () -> Functions.getAsDouble(testable::testDoublePrimitive)); + assertSame(ise, e); + + final Error error = new OutOfMemoryError(); + testable.setThrowable(error); + e = assertThrows(OutOfMemoryError.class, () -> Functions.getAsDouble(testable::testDoublePrimitive)); + assertSame(error, e); + + final IOException ioe = new IOException("Unknown I/O error"); + testable.setThrowable(ioe); + e = assertThrows(UncheckedIOException.class, () -> Functions.getAsDouble(testable::testDoublePrimitive)); + final Throwable t = e.getCause(); + assertNotNull(t); + assertSame(ioe, t); + + testable.setThrowable(null); + assertEquals(0, Functions.getAsDouble(testable::testDoublePrimitive)); + } + + @Test + public void testGetAsIntSupplier() { + final IllegalStateException ise = new IllegalStateException(); + final Testable testable = new Testable(ise); + Throwable e = assertThrows(IllegalStateException.class, () -> Functions.getAsInt(testable::testIntPrimitive)); + assertSame(ise, e); + + final Error error = new OutOfMemoryError(); + testable.setThrowable(error); + e = assertThrows(OutOfMemoryError.class, () -> Functions.getAsInt(testable::testIntPrimitive)); + assertSame(error, e); + + final IOException ioe = new IOException("Unknown I/O error"); + testable.setThrowable(ioe); + e = assertThrows(UncheckedIOException.class, () -> Functions.getAsInt(testable::testIntPrimitive)); + final Throwable t = e.getCause(); + assertNotNull(t); + assertSame(ioe, t); + + testable.setThrowable(null); + final int i = Functions.getAsInt(testable::testInteger); + assertEquals(0, i); + } + + @Test + public void testGetAsLongSupplier() { + final IllegalStateException ise = new IllegalStateException(); + final Testable testable = new Testable(ise); + Throwable e = assertThrows(IllegalStateException.class, () -> Functions.getAsLong(testable::testLongPrimitive)); + assertSame(ise, e); + + final Error error = new OutOfMemoryError(); + testable.setThrowable(error); + e = assertThrows(OutOfMemoryError.class, () -> Functions.getAsLong(testable::testLongPrimitive)); + assertSame(error, e); + + final IOException ioe = new IOException("Unknown I/O error"); + testable.setThrowable(ioe); + e = assertThrows(UncheckedIOException.class, () -> Functions.getAsLong(testable::testLongPrimitive)); + final Throwable t = e.getCause(); + assertNotNull(t); + assertSame(ioe, t); + + testable.setThrowable(null); + final long i = Functions.getAsLong(testable::testLongPrimitive); + assertEquals(0, i); + } + @Test @DisplayName("Test that asPredicate(FailablePredicate) is converted to -> Predicate ") public void testAsPredicate() { - FailureOnOddInvocations.invocation = 0; + FailureOnOddInvocations.invocations = 0; final Functions.FailablePredicate failablePredicate = t -> FailureOnOddInvocations.failingBool(); final Predicate predicate = Functions.asPredicate(failablePredicate); final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, () -> predicate.test(null)); @@ -419,7 +593,7 @@ public void testAsPredicate() { @Test @DisplayName("Test that asPredicate(FailableBiPredicate) is converted to -> BiPredicate ") public void testAsBiPredicate() { - FailureOnOddInvocations.invocation = 0; + FailureOnOddInvocations.invocations = 0; final Functions.FailableBiPredicate failableBiPredicate = (t1, t2) -> FailureOnOddInvocations.failingBool(); final BiPredicate predicate = Functions.asBiPredicate(failableBiPredicate); final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, () -> predicate.test(null, null)); @@ -433,7 +607,7 @@ public void testAsBiPredicate() { @Test public void testAsSupplier() { - FailureOnOddInvocations.invocation = 0; + FailureOnOddInvocations.invocations = 0; final FailableSupplier failableSupplier = FailureOnOddInvocations::new; final Supplier supplier = Functions.asSupplier(failableSupplier); final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, () -> supplier.get()); @@ -441,8 +615,7 @@ public void testAsSupplier() { assertNotNull(cause); assertTrue(cause instanceof SomeException); assertEquals("Odd Invocation: 1", cause.getMessage()); - final FailureOnOddInvocations instance = supplier.get(); - assertNotNull(instance); + assertNotNull(supplier.get()); } @Test From 540ec09e25a3ec60fbe0a77dfc491475229caba7 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Fri, 12 Jun 2020 11:36:13 -0400 Subject: [PATCH 0096/3230] Sort members. --- .../org/apache/commons/lang3/Functions.java | 120 ++--- .../apache/commons/lang3/FunctionsTest.java | 458 +++++++++--------- 2 files changed, 289 insertions(+), 289 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/Functions.java b/src/main/java/org/apache/commons/lang3/Functions.java index ae03211a9ae..f854f02b7fd 100644 --- a/src/main/java/org/apache/commons/lang3/Functions.java +++ b/src/main/java/org/apache/commons/lang3/Functions.java @@ -135,6 +135,24 @@ public interface FailableBiPredicate { boolean test(I1 object1, I2 object2) throws T; } + /** + * A functional interface like {@link BooleanSupplier} that declares a Throwable. + * + * @param Thrown exception. + * @since 3.11 + */ + @FunctionalInterface + public interface FailableBooleanSupplier { + + /** + * Supplies a boolean. + * + * @return a result + * @throws T if the supplier fails + */ + boolean getAsBoolean() throws T; + } + /** * A functional interface like {@link java.util.concurrent.Callable} that declares a Throwable. * @@ -173,148 +191,130 @@ public interface FailableConsumer { } /** - * A functional interface like {@link Function} that declares a Throwable. - * - * @param Input type 1. - * @param Return type. - * @param Thrown exception. - */ - @FunctionalInterface - public interface FailableFunction { - - /** - * Applies this function. - * - * @param input the input for the function - * @return the result of the function - * @throws T if the function fails - */ - R apply(I input) throws T; - } - - /** - * A functional interface like {@link Predicate} that declares a Throwable. + * A functional interface like {@link DoubleSupplier} that declares a Throwable. * - * @param Predicate type 1. * @param Thrown exception. + * @since 3.11 */ @FunctionalInterface - public interface FailablePredicate { + public interface FailableDoubleSupplier { /** - * Tests the predicate. + * Supplies a double. * - * @param object the object to test the predicate on - * @return the predicate's evaluation - * @throws T if the predicate fails + * @return a result + * @throws T if the supplier fails */ - boolean test(I object) throws T; + double getAsDouble() throws T; } /** - * A functional interface like {@link Runnable} that declares a Throwable. + * A functional interface like {@link Function} that declares a Throwable. * + * @param Input type 1. + * @param Return type. * @param Thrown exception. */ @FunctionalInterface - public interface FailableRunnable { + public interface FailableFunction { /** - * Runs the function. + * Applies this function. * + * @param input the input for the function + * @return the result of the function * @throws T if the function fails */ - void run() throws T; + R apply(I input) throws T; } /** - * A functional interface like {@link Supplier} that declares a Throwable. + * A functional interface like {@link IntSupplier} that declares a Throwable. * - * @param Return type. * @param Thrown exception. + * @since 3.11 */ @FunctionalInterface - public interface FailableSupplier { + public interface FailableIntSupplier { /** - * Supplies an object + * Supplies an int. * * @return a result * @throws T if the supplier fails */ - R get() throws T; + int getAsInt() throws T; } /** - * A functional interface like {@link BooleanSupplier} that declares a Throwable. + * A functional interface like {@link LongSupplier} that declares a Throwable. * * @param Thrown exception. * @since 3.11 */ @FunctionalInterface - public interface FailableBooleanSupplier { + public interface FailableLongSupplier { /** - * Supplies a boolean. + * Supplies a long. * * @return a result * @throws T if the supplier fails */ - boolean getAsBoolean() throws T; + long getAsLong() throws T; } /** - * A functional interface like {@link DoubleSupplier} that declares a Throwable. + * A functional interface like {@link Predicate} that declares a Throwable. * + * @param Predicate type 1. * @param Thrown exception. - * @since 3.11 */ @FunctionalInterface - public interface FailableDoubleSupplier { + public interface FailablePredicate { /** - * Supplies a double. + * Tests the predicate. * - * @return a result - * @throws T if the supplier fails + * @param object the object to test the predicate on + * @return the predicate's evaluation + * @throws T if the predicate fails */ - double getAsDouble() throws T; + boolean test(I object) throws T; } /** - * A functional interface like {@link IntSupplier} that declares a Throwable. + * A functional interface like {@link Runnable} that declares a Throwable. * * @param Thrown exception. - * @since 3.11 */ @FunctionalInterface - public interface FailableIntSupplier { + public interface FailableRunnable { /** - * Supplies an int. + * Runs the function. * - * @return a result - * @throws T if the supplier fails + * @throws T if the function fails */ - int getAsInt() throws T; + void run() throws T; } /** - * A functional interface like {@link LongSupplier} that declares a Throwable. + * A functional interface like {@link Supplier} that declares a Throwable. * + * @param Return type. * @param Thrown exception. - * @since 3.11 */ @FunctionalInterface - public interface FailableLongSupplier { + public interface FailableSupplier { /** - * Supplies a long. + * Supplies an object * * @return a result * @throws T if the supplier fails */ - long getAsLong() throws T; + R get() throws T; } /** diff --git a/src/test/java/org/apache/commons/lang3/FunctionsTest.java b/src/test/java/org/apache/commons/lang3/FunctionsTest.java index 63375cd0197..c9e6acfda39 100644 --- a/src/test/java/org/apache/commons/lang3/FunctionsTest.java +++ b/src/test/java/org/apache/commons/lang3/FunctionsTest.java @@ -46,6 +46,53 @@ class FunctionsTest { + public static class CloseableObject { + private boolean closed; + + public void close() { + closed = true; + } + + public boolean isClosed() { + return closed; + } + + public void reset() { + closed = false; + } + + public void run(final Throwable pTh) throws Throwable { + if (pTh != null) { + throw pTh; + } + } + } + + public static class FailureOnOddInvocations { + private static int invocations; + + static boolean failingBool() throws SomeException { + throwOnOdd(); + return true; + } + + private static void throwOnOdd() throws SomeException { + final int i = ++invocations; + if (i % 2 == 1) { + throw new SomeException("Odd Invocation: " + i); + } + } + + FailureOnOddInvocations() throws SomeException { + throwOnOdd(); + } + + boolean getAsBoolean() throws SomeException { + throwOnOdd(); + return true; + } + } + public static class SomeException extends Exception { private static final long serialVersionUID = -4965704778119283411L; @@ -88,38 +135,19 @@ public void test(final Throwable throwable) throws Throwable { } } - public Integer testInteger() throws Throwable { - return testInteger(t); - } - - public int testIntPrimitive() throws Throwable { - return testIntPrimitive(t); - } - - public long testLongPrimitive() throws Throwable { - return testLongPrimitive(t); - } - public boolean testBooleanPrimitive() throws Throwable { return testBooleanPrimitive(t); } - public double testDoublePrimitive() throws Throwable { - return testDoublePrimitive(t); - } - - public Integer testInteger(final Throwable throwable) throws Throwable { + public boolean testBooleanPrimitive(final Throwable throwable) throws Throwable { if (throwable != null) { throw throwable; } - return 0; + return false; } - public int testIntPrimitive(final Throwable throwable) throws Throwable { - if (throwable != null) { - throw throwable; - } - return 0; + public double testDoublePrimitive() throws Throwable { + return testDoublePrimitive(t); } public double testDoublePrimitive(final Throwable throwable) throws Throwable { @@ -129,124 +157,60 @@ public double testDoublePrimitive(final Throwable throwable) throws Throwable { return 0; } - public long testLongPrimitive(final Throwable throwable) throws Throwable { - if (throwable != null) { - throw throwable; - } - return 0; + public Integer testInteger() throws Throwable { + return testInteger(t); } - public boolean testBooleanPrimitive(final Throwable throwable) throws Throwable { + public Integer testInteger(final Throwable throwable) throws Throwable { if (throwable != null) { throw throwable; } - return false; - } - } - - public static class FailureOnOddInvocations { - private static int invocations; - - private static void throwOnOdd() throws SomeException { - final int i = ++invocations; - if (i % 2 == 1) { - throw new SomeException("Odd Invocation: " + i); - } - } - - static boolean failingBool() throws SomeException { - throwOnOdd(); - return true; - } - - FailureOnOddInvocations() throws SomeException { - throwOnOdd(); + return 0; } - boolean getAsBoolean() throws SomeException { - throwOnOdd(); - return true; + public int testIntPrimitive() throws Throwable { + return testIntPrimitive(t); } - } - public static class CloseableObject { - private boolean closed; - - public void run(final Throwable pTh) throws Throwable { - if (pTh != null) { - throw pTh; + public int testIntPrimitive(final Throwable throwable) throws Throwable { + if (throwable != null) { + throw throwable; } + return 0; } - public void reset() { - closed = false; - } - - public void close() { - closed = true; + public long testLongPrimitive() throws Throwable { + return testLongPrimitive(t); } - public boolean isClosed() { - return closed; + public long testLongPrimitive(final Throwable throwable) throws Throwable { + if (throwable != null) { + throw throwable; + } + return 0; } } @Test - void testRunnable() { - FailureOnOddInvocations.invocations = 0; - final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, () -> Functions.run(FailureOnOddInvocations::new)); - final Throwable cause = e.getCause(); - assertNotNull(cause); - assertTrue(cause instanceof SomeException); - assertEquals("Odd Invocation: 1", cause.getMessage()); - - // Even invocations, should not throw an exception - Functions.run(FailureOnOddInvocations::new); - } - - @Test - void testAsRunnable() { - FailureOnOddInvocations.invocations = 0; - final Runnable runnable = Functions.asRunnable(FailureOnOddInvocations::new); - final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, () -> runnable.run()); - final Throwable cause = e.getCause(); - assertNotNull(cause); - assertTrue(cause instanceof SomeException); - assertEquals("Odd Invocation: 1", cause.getMessage()); + void testAcceptBiConsumer() { + final IllegalStateException ise = new IllegalStateException(); + final Testable testable = new Testable(null); + Throwable e = assertThrows(IllegalStateException.class, () -> Functions.accept(Testable::test, testable, ise)); + assertSame(ise, e); - // Even invocations, should not throw an exception - runnable.run(); - } + final Error error = new OutOfMemoryError(); + e = assertThrows(OutOfMemoryError.class, () -> Functions.accept(Testable::test, testable, error)); + assertSame(error, e); - @Test - void testCallable() { - FailureOnOddInvocations.invocations = 0; - final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, () -> Functions.run(FailureOnOddInvocations::new)); - final Throwable cause = e.getCause(); - assertNotNull(cause); - assertTrue(cause instanceof SomeException); - assertEquals("Odd Invocation: 1", cause.getMessage()); - final FailureOnOddInvocations instance = Functions.call(FailureOnOddInvocations::new); - assertNotNull(instance); - } + final IOException ioe = new IOException("Unknown I/O error"); + testable.setThrowable(ioe); + e = assertThrows(UncheckedIOException.class, () -> Functions.accept(Testable::test, testable, ioe)); + final Throwable t = e.getCause(); + assertNotNull(t); + assertSame(ioe, t); - @Test - void testAsCallable() { - FailureOnOddInvocations.invocations = 0; - final FailableCallable failableCallable = FailureOnOddInvocations::new; - final Callable callable = Functions.asCallable(failableCallable); - final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, () -> callable.call()); - final Throwable cause = e.getCause(); - assertNotNull(cause); - assertTrue(cause instanceof SomeException); - assertEquals("Odd Invocation: 1", cause.getMessage()); - final FailureOnOddInvocations instance; - try { - instance = callable.call(); - } catch (final Exception ex) { - throw Functions.rethrow(ex); - } - assertNotNull(instance); + testable.setThrowable(null); + Functions.accept(Testable::test, testable, (Throwable) null); } @Test @@ -273,49 +237,50 @@ void testAcceptConsumer() { } @Test - void testAsConsumer() { + public void testApplyBiFunction() { final IllegalStateException ise = new IllegalStateException(); - final Testable testable = new Testable(ise); - final Consumer consumer = Functions.asConsumer(Testable::test); - Throwable e = assertThrows(IllegalStateException.class, () -> consumer.accept(testable)); + final Testable testable = new Testable(null); + Throwable e = assertThrows(IllegalStateException.class, () -> Functions.apply(Testable::testInteger, testable, ise)); assertSame(ise, e); final Error error = new OutOfMemoryError(); - testable.setThrowable(error); - e = assertThrows(OutOfMemoryError.class, () -> consumer.accept(testable)); + e = assertThrows(OutOfMemoryError.class, () -> Functions.apply(Testable::testInteger, testable, error)); assertSame(error, e); final IOException ioe = new IOException("Unknown I/O error"); - testable.setThrowable(ioe); - e = assertThrows(UncheckedIOException.class, () -> consumer.accept(testable)); + e = assertThrows(UncheckedIOException.class, () -> Functions.apply(Testable::testInteger, testable, ioe)); final Throwable t = e.getCause(); assertNotNull(t); assertSame(ioe, t); - testable.setThrowable(null); - Functions.accept(Testable::test, testable); + final Integer i = Functions.apply(Testable::testInteger, testable, (Throwable) null); + assertNotNull(i); + assertEquals(0, i.intValue()); } @Test - void testAcceptBiConsumer() { + public void testApplyFunction() { final IllegalStateException ise = new IllegalStateException(); - final Testable testable = new Testable(null); - Throwable e = assertThrows(IllegalStateException.class, () -> Functions.accept(Testable::test, testable, ise)); + final Testable testable = new Testable(ise); + Throwable e = assertThrows(IllegalStateException.class, () -> Functions.apply(Testable::testInteger, testable)); assertSame(ise, e); final Error error = new OutOfMemoryError(); - e = assertThrows(OutOfMemoryError.class, () -> Functions.accept(Testable::test, testable, error)); + testable.setThrowable(error); + e = assertThrows(OutOfMemoryError.class, () -> Functions.apply(Testable::testInteger, testable)); assertSame(error, e); final IOException ioe = new IOException("Unknown I/O error"); testable.setThrowable(ioe); - e = assertThrows(UncheckedIOException.class, () -> Functions.accept(Testable::test, testable, ioe)); + e = assertThrows(UncheckedIOException.class, () -> Functions.apply(Testable::testInteger, testable)); final Throwable t = e.getCause(); assertNotNull(t); assertSame(ioe, t); testable.setThrowable(null); - Functions.accept(Testable::test, testable, (Throwable) null); + final Integer i = Functions.apply(Testable::testInteger, testable); + assertNotNull(i); + assertEquals(0, i.intValue()); } @Test @@ -344,141 +309,169 @@ void testAsBiConsumer() { } @Test - public void testApplyFunction() { + public void testAsBiFunction() { final IllegalStateException ise = new IllegalStateException(); final Testable testable = new Testable(ise); - Throwable e = assertThrows(IllegalStateException.class, () -> Functions.apply(Testable::testInteger, testable)); + final FailableBiFunction failableBiFunction = (t, th) -> { + t.setThrowable(th); + return Integer.valueOf(t.testInteger()); + }; + final BiFunction biFunction = Functions.asBiFunction(failableBiFunction); + Throwable e = assertThrows(IllegalStateException.class, () -> biFunction.apply(testable, ise)); assertSame(ise, e); final Error error = new OutOfMemoryError(); testable.setThrowable(error); - e = assertThrows(OutOfMemoryError.class, () -> Functions.apply(Testable::testInteger, testable)); + e = assertThrows(OutOfMemoryError.class, () -> biFunction.apply(testable, error)); assertSame(error, e); final IOException ioe = new IOException("Unknown I/O error"); testable.setThrowable(ioe); - e = assertThrows(UncheckedIOException.class, () -> Functions.apply(Testable::testInteger, testable)); + e = assertThrows(UncheckedIOException.class, () -> biFunction.apply(testable, ioe)); final Throwable t = e.getCause(); assertNotNull(t); assertSame(ioe, t); - testable.setThrowable(null); - final Integer i = Functions.apply(Testable::testInteger, testable); - assertNotNull(i); - assertEquals(0, i.intValue()); + assertEquals(0, biFunction.apply(testable, null).intValue()); } @Test - public void testAsFunction() { - final IllegalStateException ise = new IllegalStateException(); - final Testable testable = new Testable(ise); - final FailableFunction failableFunction = th -> { - testable.setThrowable(th); - return Integer.valueOf(testable.testInteger()); - }; - final Function function = Functions.asFunction(failableFunction); - Throwable e = assertThrows(IllegalStateException.class, () -> function.apply(ise)); - assertSame(ise, e); - - final Error error = new OutOfMemoryError(); - testable.setThrowable(error); - e = assertThrows(OutOfMemoryError.class, () -> function.apply(error)); - assertSame(error, e); - - final IOException ioe = new IOException("Unknown I/O error"); - testable.setThrowable(ioe); - e = assertThrows(UncheckedIOException.class, () -> function.apply(ioe)); - final Throwable t = e.getCause(); - assertNotNull(t); - assertSame(ioe, t); + @DisplayName("Test that asPredicate(FailableBiPredicate) is converted to -> BiPredicate ") + public void testAsBiPredicate() { + FailureOnOddInvocations.invocations = 0; + final Functions.FailableBiPredicate failableBiPredicate = (t1, t2) -> FailureOnOddInvocations.failingBool(); + final BiPredicate predicate = Functions.asBiPredicate(failableBiPredicate); + final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, () -> predicate.test(null, null)); + final Throwable cause = e.getCause(); + assertNotNull(cause); + assertTrue(cause instanceof SomeException); + assertEquals("Odd Invocation: 1", cause.getMessage()); + final boolean instance = predicate.test(null, null); + assertNotNull(instance); + } - assertEquals(0, function.apply(null).intValue()); + @Test + void testAsCallable() { + FailureOnOddInvocations.invocations = 0; + final FailableCallable failableCallable = FailureOnOddInvocations::new; + final Callable callable = Functions.asCallable(failableCallable); + final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, () -> callable.call()); + final Throwable cause = e.getCause(); + assertNotNull(cause); + assertTrue(cause instanceof SomeException); + assertEquals("Odd Invocation: 1", cause.getMessage()); + final FailureOnOddInvocations instance; + try { + instance = callable.call(); + } catch (final Exception ex) { + throw Functions.rethrow(ex); + } + assertNotNull(instance); } @Test - public void testApplyBiFunction() { + void testAsConsumer() { final IllegalStateException ise = new IllegalStateException(); - final Testable testable = new Testable(null); - Throwable e = assertThrows(IllegalStateException.class, () -> Functions.apply(Testable::testInteger, testable, ise)); + final Testable testable = new Testable(ise); + final Consumer consumer = Functions.asConsumer(Testable::test); + Throwable e = assertThrows(IllegalStateException.class, () -> consumer.accept(testable)); assertSame(ise, e); final Error error = new OutOfMemoryError(); - e = assertThrows(OutOfMemoryError.class, () -> Functions.apply(Testable::testInteger, testable, error)); + testable.setThrowable(error); + e = assertThrows(OutOfMemoryError.class, () -> consumer.accept(testable)); assertSame(error, e); final IOException ioe = new IOException("Unknown I/O error"); - e = assertThrows(UncheckedIOException.class, () -> Functions.apply(Testable::testInteger, testable, ioe)); + testable.setThrowable(ioe); + e = assertThrows(UncheckedIOException.class, () -> consumer.accept(testable)); final Throwable t = e.getCause(); assertNotNull(t); assertSame(ioe, t); - final Integer i = Functions.apply(Testable::testInteger, testable, (Throwable) null); - assertNotNull(i); - assertEquals(0, i.intValue()); + testable.setThrowable(null); + Functions.accept(Testable::test, testable); } @Test - public void testAsBiFunction() { + public void testAsFunction() { final IllegalStateException ise = new IllegalStateException(); final Testable testable = new Testable(ise); - final FailableBiFunction failableBiFunction = (t, th) -> { - t.setThrowable(th); - return Integer.valueOf(t.testInteger()); + final FailableFunction failableFunction = th -> { + testable.setThrowable(th); + return Integer.valueOf(testable.testInteger()); }; - final BiFunction biFunction = Functions.asBiFunction(failableBiFunction); - Throwable e = assertThrows(IllegalStateException.class, () -> biFunction.apply(testable, ise)); + final Function function = Functions.asFunction(failableFunction); + Throwable e = assertThrows(IllegalStateException.class, () -> function.apply(ise)); assertSame(ise, e); final Error error = new OutOfMemoryError(); testable.setThrowable(error); - e = assertThrows(OutOfMemoryError.class, () -> biFunction.apply(testable, error)); + e = assertThrows(OutOfMemoryError.class, () -> function.apply(error)); assertSame(error, e); final IOException ioe = new IOException("Unknown I/O error"); testable.setThrowable(ioe); - e = assertThrows(UncheckedIOException.class, () -> biFunction.apply(testable, ioe)); + e = assertThrows(UncheckedIOException.class, () -> function.apply(ioe)); final Throwable t = e.getCause(); assertNotNull(t); assertSame(ioe, t); - assertEquals(0, biFunction.apply(testable, null).intValue()); + assertEquals(0, function.apply(null).intValue()); } @Test - public void testGetFromSupplier() { + @DisplayName("Test that asPredicate(FailablePredicate) is converted to -> Predicate ") + public void testAsPredicate() { FailureOnOddInvocations.invocations = 0; - final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, () -> Functions.run(FailureOnOddInvocations::new)); + final Functions.FailablePredicate failablePredicate = t -> FailureOnOddInvocations.failingBool(); + final Predicate predicate = Functions.asPredicate(failablePredicate); + final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, () -> predicate.test(null)); final Throwable cause = e.getCause(); assertNotNull(cause); assertTrue(cause instanceof SomeException); assertEquals("Odd Invocation: 1", cause.getMessage()); - final FailureOnOddInvocations instance = Functions.call(FailureOnOddInvocations::new); + final boolean instance = predicate.test(null); assertNotNull(instance); } @Test - public void testGetSupplier() { - final IllegalStateException ise = new IllegalStateException(); - final Testable testable = new Testable(ise); - Throwable e = assertThrows(IllegalStateException.class, () -> Functions.get(testable::testInteger)); - assertSame(ise, e); + void testAsRunnable() { + FailureOnOddInvocations.invocations = 0; + final Runnable runnable = Functions.asRunnable(FailureOnOddInvocations::new); + final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, () -> runnable.run()); + final Throwable cause = e.getCause(); + assertNotNull(cause); + assertTrue(cause instanceof SomeException); + assertEquals("Odd Invocation: 1", cause.getMessage()); - final Error error = new OutOfMemoryError(); - testable.setThrowable(error); - e = assertThrows(OutOfMemoryError.class, () -> Functions.get(testable::testInteger)); - assertSame(error, e); + // Even invocations, should not throw an exception + runnable.run(); + } - final IOException ioe = new IOException("Unknown I/O error"); - testable.setThrowable(ioe); - e = assertThrows(UncheckedIOException.class, () -> Functions.get(testable::testInteger)); - final Throwable t = e.getCause(); - assertNotNull(t); - assertSame(ioe, t); + @Test + public void testAsSupplier() { + FailureOnOddInvocations.invocations = 0; + final FailableSupplier failableSupplier = FailureOnOddInvocations::new; + final Supplier supplier = Functions.asSupplier(failableSupplier); + final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, () -> supplier.get()); + final Throwable cause = e.getCause(); + assertNotNull(cause); + assertTrue(cause instanceof SomeException); + assertEquals("Odd Invocation: 1", cause.getMessage()); + assertNotNull(supplier.get()); + } - testable.setThrowable(null); - final Integer i = Functions.apply(Testable::testInteger, testable); - assertNotNull(i); - assertEquals(0, i.intValue()); + @Test + void testCallable() { + FailureOnOddInvocations.invocations = 0; + final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, () -> Functions.run(FailureOnOddInvocations::new)); + final Throwable cause = e.getCause(); + assertNotNull(cause); + assertTrue(cause instanceof SomeException); + assertEquals("Odd Invocation: 1", cause.getMessage()); + final FailureOnOddInvocations instance = Functions.call(FailureOnOddInvocations::new); + assertNotNull(instance); } @Test @@ -576,46 +569,53 @@ public void testGetAsLongSupplier() { } @Test - @DisplayName("Test that asPredicate(FailablePredicate) is converted to -> Predicate ") - public void testAsPredicate() { + public void testGetFromSupplier() { FailureOnOddInvocations.invocations = 0; - final Functions.FailablePredicate failablePredicate = t -> FailureOnOddInvocations.failingBool(); - final Predicate predicate = Functions.asPredicate(failablePredicate); - final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, () -> predicate.test(null)); + final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, () -> Functions.run(FailureOnOddInvocations::new)); final Throwable cause = e.getCause(); assertNotNull(cause); assertTrue(cause instanceof SomeException); assertEquals("Odd Invocation: 1", cause.getMessage()); - final boolean instance = predicate.test(null); + final FailureOnOddInvocations instance = Functions.call(FailureOnOddInvocations::new); assertNotNull(instance); } @Test - @DisplayName("Test that asPredicate(FailableBiPredicate) is converted to -> BiPredicate ") - public void testAsBiPredicate() { - FailureOnOddInvocations.invocations = 0; - final Functions.FailableBiPredicate failableBiPredicate = (t1, t2) -> FailureOnOddInvocations.failingBool(); - final BiPredicate predicate = Functions.asBiPredicate(failableBiPredicate); - final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, () -> predicate.test(null, null)); - final Throwable cause = e.getCause(); - assertNotNull(cause); - assertTrue(cause instanceof SomeException); - assertEquals("Odd Invocation: 1", cause.getMessage()); - final boolean instance = predicate.test(null, null); - assertNotNull(instance); + public void testGetSupplier() { + final IllegalStateException ise = new IllegalStateException(); + final Testable testable = new Testable(ise); + Throwable e = assertThrows(IllegalStateException.class, () -> Functions.get(testable::testInteger)); + assertSame(ise, e); + + final Error error = new OutOfMemoryError(); + testable.setThrowable(error); + e = assertThrows(OutOfMemoryError.class, () -> Functions.get(testable::testInteger)); + assertSame(error, e); + + final IOException ioe = new IOException("Unknown I/O error"); + testable.setThrowable(ioe); + e = assertThrows(UncheckedIOException.class, () -> Functions.get(testable::testInteger)); + final Throwable t = e.getCause(); + assertNotNull(t); + assertSame(ioe, t); + + testable.setThrowable(null); + final Integer i = Functions.apply(Testable::testInteger, testable); + assertNotNull(i); + assertEquals(0, i.intValue()); } @Test - public void testAsSupplier() { + void testRunnable() { FailureOnOddInvocations.invocations = 0; - final FailableSupplier failableSupplier = FailureOnOddInvocations::new; - final Supplier supplier = Functions.asSupplier(failableSupplier); - final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, () -> supplier.get()); + final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, () -> Functions.run(FailureOnOddInvocations::new)); final Throwable cause = e.getCause(); assertNotNull(cause); assertTrue(cause instanceof SomeException); assertEquals("Odd Invocation: 1", cause.getMessage()); - assertNotNull(supplier.get()); + + // Even invocations, should not throw an exception + Functions.run(FailureOnOddInvocations::new); } @Test From 62393bd601d62b96c741e797fc3302bb30f644c5 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Fri, 12 Jun 2020 11:37:06 -0400 Subject: [PATCH 0097/3230] commons.bc.version 3.9 -> 3.10 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 82223df21ff..c3ecae7626c 100644 --- a/pom.xml +++ b/pom.xml @@ -619,7 +619,7 @@ 0.14.3 - 3.9 + 3.10 RC1 true scm:svn:https://dist.apache.org/repos/dist/dev/commons/lang From f5e9f55283788fc15a38191baea2cf765a227f4e Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Fri, 12 Jun 2020 15:25:14 -0400 Subject: [PATCH 0098/3230] [LANG-1568] Add more failable Consumers to match JRE stock Consumers. --- .../org/apache/commons/lang3/Functions.java | 157 ++++++++++- .../apache/commons/lang3/FunctionsTest.java | 266 ++++++++++++++++-- 2 files changed, 398 insertions(+), 25 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/Functions.java b/src/main/java/org/apache/commons/lang3/Functions.java index f854f02b7fd..e52b749ed8a 100644 --- a/src/main/java/org/apache/commons/lang3/Functions.java +++ b/src/main/java/org/apache/commons/lang3/Functions.java @@ -27,10 +27,16 @@ import java.util.function.BiPredicate; import java.util.function.BooleanSupplier; import java.util.function.Consumer; +import java.util.function.DoubleConsumer; import java.util.function.DoubleSupplier; import java.util.function.Function; +import java.util.function.IntConsumer; import java.util.function.IntSupplier; +import java.util.function.LongConsumer; import java.util.function.LongSupplier; +import java.util.function.ObjDoubleConsumer; +import java.util.function.ObjIntConsumer; +import java.util.function.ObjLongConsumer; import java.util.function.Predicate; import java.util.function.Supplier; import java.util.stream.Stream; @@ -180,7 +186,6 @@ public interface FailableCallable { @FunctionalInterface public interface FailableConsumer { - /** * Accepts the consumer. * @@ -190,6 +195,24 @@ public interface FailableConsumer { void accept(O object) throws T; } + /** + * A functional interface like {@link DoubleConsumer} that declares a Throwable. + * + * @param Thrown exception. + * @since 3.11 + */ + @FunctionalInterface + public interface FailableDoubleConsumer { + + /** + * Accepts the consumer. + * + * @param value the parameter for the consumable to accept + * @throws T if the consumer fails + */ + void accept(double value) throws T; + } + /** * A functional interface like {@link DoubleSupplier} that declares a Throwable. * @@ -228,6 +251,24 @@ public interface FailableFunction { R apply(I input) throws T; } + /** + * A functional interface like {@link IntConsumer} that declares a Throwable. + * + * @param Thrown exception. + * @since 3.11 + */ + @FunctionalInterface + public interface FailableIntConsumer { + + /** + * Accepts the consumer. + * + * @param value the parameter for the consumable to accept + * @throws T if the consumer fails + */ + void accept(int value) throws T; + } + /** * A functional interface like {@link IntSupplier} that declares a Throwable. * @@ -246,6 +287,24 @@ public interface FailableIntSupplier { int getAsInt() throws T; } + /** + * A functional interface like {@link LongConsumer} that declares a Throwable. + * + * @param Thrown exception. + * @since 3.11 + */ + @FunctionalInterface + public interface FailableLongConsumer { + + /** + * Accepts the consumer. + * + * @param object the parameter for the consumable to accept + * @throws T if the consumer fails + */ + void accept(long object) throws T; + } + /** * A functional interface like {@link LongSupplier} that declares a Throwable. * @@ -264,6 +323,66 @@ public interface FailableLongSupplier { long getAsLong() throws T; } + /** + * A functional interface like {@link ObjDoubleConsumer} that declares a Throwable. + * + * @param the type of the object argument to the operation. + * @param Thrown exception. + * @since 3.11 + */ + @FunctionalInterface + public interface FailableObjDoubleConsumer { + + /** + * Accepts the consumer. + * + * @param object the object parameter for the consumable to accept. + * @param value the double parameter for the consumable to accept. + * @throws T if the consumer fails + */ + void accept(O object, double value) throws T; + } + + /** + * A functional interface like {@link ObjIntConsumer} that declares a Throwable. + * + * @param the type of the object argument to the operation. + * @param Thrown exception. + * @since 3.11 + */ + @FunctionalInterface + public interface FailableObjIntConsumer { + + /** + * Accepts the consumer. + * + * @param object the object parameter for the consumable to accept. + * @param value the int parameter for the consumable to accept. + * @throws T if the consumer fails + */ + void accept(O object, int value) throws T; + } + + /** + * A functional interface like {@link ObjLongConsumer} that declares a Throwable. + * + * @param the type of the object argument to the operation. + * @param Thrown exception. + * @since 3.11 + */ + @FunctionalInterface + public interface FailableObjLongConsumer { + + /** + * Accepts the consumer. + * + * @param object the object parameter for the consumable to accept. + * @param value the long parameter for the consumable to accept. + * @throws T if the consumer fails + */ + void accept(O object, long value) throws T; + } + /** * A functional interface like {@link Predicate} that declares a Throwable. * @@ -344,6 +463,42 @@ public static void accept(final FailableConsumer run(() -> consumer.accept(object)); } + /** + * Consumes a consumer and rethrows any exception as a {@link RuntimeException}. + * + * @param consumer the consumer to consume + * @param value the value to consume by {@code consumer} + * @param the type of checked exception the consumer may throw + * @since 3.11 + */ + public static void accept(final FailableDoubleConsumer consumer, final double value) { + run(() -> consumer.accept(value)); + } + + /** + * Consumes a consumer and rethrows any exception as a {@link RuntimeException}. + * + * @param consumer the consumer to consume + * @param value the value to consume by {@code consumer} + * @param the type of checked exception the consumer may throw + * @since 3.11 + */ + public static void accept(final FailableIntConsumer consumer, final int value) { + run(() -> consumer.accept(value)); + } + + /** + * Consumes a consumer and rethrows any exception as a {@link RuntimeException}. + * + * @param consumer the consumer to consume + * @param value the value to consume by {@code consumer} + * @param the type of checked exception the consumer may throw + * @since 3.11 + */ + public static void accept(final FailableLongConsumer consumer, final long value) { + run(() -> consumer.accept(value)); + } + /** * Applies a function and rethrows any exception as a {@link RuntimeException}. * diff --git a/src/test/java/org/apache/commons/lang3/FunctionsTest.java b/src/test/java/org/apache/commons/lang3/FunctionsTest.java index c9e6acfda39..3c462f83e33 100644 --- a/src/test/java/org/apache/commons/lang3/FunctionsTest.java +++ b/src/test/java/org/apache/commons/lang3/FunctionsTest.java @@ -19,6 +19,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -114,19 +115,29 @@ public void test() throws Throwable { } } - public static class Testable { - private Throwable t; + public static class Testable { + private Throwable throwable; + private P acceptedPrimitiveObject; + private T acceptedObject; + + Testable(final Throwable throwable) { + this.throwable = throwable; + } + + public T getAcceptedObject() { + return acceptedObject; + } - Testable(final Throwable pTh) { - t = pTh; + public P getAcceptedPrimitiveObject() { + return acceptedPrimitiveObject; } public void setThrowable(final Throwable throwable) { - t = throwable; + this.throwable = throwable; } public void test() throws Throwable { - test(t); + test(throwable); } public void test(final Throwable throwable) throws Throwable { @@ -136,7 +147,7 @@ public void test(final Throwable throwable) throws Throwable { } public boolean testBooleanPrimitive() throws Throwable { - return testBooleanPrimitive(t); + return testBooleanPrimitive(throwable); } public boolean testBooleanPrimitive(final Throwable throwable) throws Throwable { @@ -146,8 +157,13 @@ public boolean testBooleanPrimitive(final Throwable throwable) throws Throwable return false; } + public void testDouble(double i) throws Throwable { + test(throwable); + acceptedPrimitiveObject = (P) ((Double) i); + } + public double testDoublePrimitive() throws Throwable { - return testDoublePrimitive(t); + return testDoublePrimitive(throwable); } public double testDoublePrimitive(final Throwable throwable) throws Throwable { @@ -157,8 +173,13 @@ public double testDoublePrimitive(final Throwable throwable) throws Throwable { return 0; } + public void testInt(int i) throws Throwable { + test(throwable); + acceptedPrimitiveObject = (P) ((Integer) i); + } + public Integer testInteger() throws Throwable { - return testInteger(t); + return testInteger(throwable); } public Integer testInteger(final Throwable throwable) throws Throwable { @@ -169,7 +190,7 @@ public Integer testInteger(final Throwable throwable) throws Throwable { } public int testIntPrimitive() throws Throwable { - return testIntPrimitive(t); + return testIntPrimitive(throwable); } public int testIntPrimitive(final Throwable throwable) throws Throwable { @@ -179,8 +200,13 @@ public int testIntPrimitive(final Throwable throwable) throws Throwable { return 0; } + public void testLong(long i) throws Throwable { + test(throwable); + acceptedPrimitiveObject = (P) ((Long) i); + } + public long testLongPrimitive() throws Throwable { - return testLongPrimitive(t); + return testLongPrimitive(throwable); } public long testLongPrimitive(final Throwable throwable) throws Throwable { @@ -189,12 +215,30 @@ public long testLongPrimitive(final Throwable throwable) throws Throwable { } return 0; } + + public void testObjDouble(T object, double i) throws Throwable { + test(throwable); + acceptedObject = object; + acceptedPrimitiveObject = (P) ((Double) i); + } + + public void testObjInt(T object, int i) throws Throwable { + test(throwable); + acceptedObject = object; + acceptedPrimitiveObject = (P) ((Integer) i); + } + + public void testObjLong(T object, long i) throws Throwable { + test(throwable); + acceptedObject = object; + acceptedPrimitiveObject = (P) ((Long) i); + } } @Test void testAcceptBiConsumer() { final IllegalStateException ise = new IllegalStateException(); - final Testable testable = new Testable(null); + final Testable testable = new Testable(null); Throwable e = assertThrows(IllegalStateException.class, () -> Functions.accept(Testable::test, testable, ise)); assertSame(ise, e); @@ -216,7 +260,7 @@ void testAcceptBiConsumer() { @Test void testAcceptConsumer() { final IllegalStateException ise = new IllegalStateException(); - final Testable testable = new Testable(ise); + final Testable testable = new Testable<>(ise); Throwable e = assertThrows(IllegalStateException.class, () -> Functions.accept(Testable::test, testable)); assertSame(ise, e); @@ -236,10 +280,184 @@ void testAcceptConsumer() { Functions.accept(Testable::test, testable); } + @Test + void testAcceptDoubleConsumer() { + final IllegalStateException ise = new IllegalStateException(); + final Testable testable = new Testable<>(ise); + Throwable e = assertThrows(IllegalStateException.class, () -> Functions.accept(testable::testDouble, 1d)); + assertSame(ise, e); + assertNull(testable.getAcceptedPrimitiveObject()); + + final Error error = new OutOfMemoryError(); + testable.setThrowable(error); + e = assertThrows(OutOfMemoryError.class, () -> Functions.accept(testable::testDouble, 1d)); + assertSame(error, e); + assertNull(testable.getAcceptedPrimitiveObject()); + + final IOException ioe = new IOException("Unknown I/O error"); + testable.setThrowable(ioe); + e = assertThrows(UncheckedIOException.class, () -> Functions.accept(testable::testDouble, 1d)); + final Throwable t = e.getCause(); + assertNotNull(t); + assertSame(ioe, t); + assertNull(testable.getAcceptedPrimitiveObject()); + + testable.setThrowable(null); + Functions.accept(testable::testDouble, 1d); + assertEquals(1, testable.getAcceptedPrimitiveObject()); + } + + @Test + void testAcceptIntConsumer() { + final IllegalStateException ise = new IllegalStateException(); + final Testable testable = new Testable<>(ise); + Throwable e = assertThrows(IllegalStateException.class, () -> Functions.accept(testable::testInt, 1)); + assertSame(ise, e); + assertNull(testable.getAcceptedPrimitiveObject()); + + final Error error = new OutOfMemoryError(); + testable.setThrowable(error); + e = assertThrows(OutOfMemoryError.class, () -> Functions.accept(testable::testInt, 1)); + assertSame(error, e); + assertNull(testable.getAcceptedPrimitiveObject()); + + final IOException ioe = new IOException("Unknown I/O error"); + testable.setThrowable(ioe); + e = assertThrows(UncheckedIOException.class, () -> Functions.accept(testable::testInt, 1)); + final Throwable t = e.getCause(); + assertNotNull(t); + assertSame(ioe, t); + assertNull(testable.getAcceptedPrimitiveObject()); + + testable.setThrowable(null); + Functions.accept(testable::testInt, 1); + assertEquals(1, testable.getAcceptedPrimitiveObject()); + } + + @Test + void testAcceptLongConsumer() { + final IllegalStateException ise = new IllegalStateException(); + final Testable testable = new Testable<>(ise); + Throwable e = assertThrows(IllegalStateException.class, () -> Functions.accept(testable::testLong, 1L)); + assertSame(ise, e); + assertNull(testable.getAcceptedPrimitiveObject()); + + final Error error = new OutOfMemoryError(); + testable.setThrowable(error); + e = assertThrows(OutOfMemoryError.class, () -> Functions.accept(testable::testLong, 1L)); + assertSame(error, e); + assertNull(testable.getAcceptedPrimitiveObject()); + + final IOException ioe = new IOException("Unknown I/O error"); + testable.setThrowable(ioe); + e = assertThrows(UncheckedIOException.class, () -> Functions.accept(testable::testLong, 1L)); + final Throwable t = e.getCause(); + assertNotNull(t); + assertSame(ioe, t); + assertNull(testable.getAcceptedPrimitiveObject()); + + testable.setThrowable(null); + Functions.accept(testable::testLong, 1L); + assertEquals(1, testable.getAcceptedPrimitiveObject()); + } + + @Test + void testAcceptObjDoubleConsumer() { + final IllegalStateException ise = new IllegalStateException(); + final Testable testable = new Testable<>(ise); + Throwable e = assertThrows(IllegalStateException.class, () -> Functions.accept(testable::testObjDouble, "X", 1d)); + assertSame(ise, e); + assertNull(testable.getAcceptedObject()); + assertNull(testable.getAcceptedPrimitiveObject()); + + final Error error = new OutOfMemoryError(); + testable.setThrowable(error); + e = assertThrows(OutOfMemoryError.class, () -> Functions.accept(testable::testObjDouble, "X", 1d)); + assertSame(error, e); + assertNull(testable.getAcceptedObject()); + assertNull(testable.getAcceptedPrimitiveObject()); + + final IOException ioe = new IOException("Unknown I/O error"); + testable.setThrowable(ioe); + e = assertThrows(UncheckedIOException.class, () -> Functions.accept(testable::testObjDouble, "X", 1d)); + final Throwable t = e.getCause(); + assertNotNull(t); + assertSame(ioe, t); + assertNull(testable.getAcceptedObject()); + assertNull(testable.getAcceptedPrimitiveObject()); + + testable.setThrowable(null); + Functions.accept(testable::testObjDouble, "X", 1d); + assertEquals("X", testable.getAcceptedObject()); + assertEquals(1d, testable.getAcceptedPrimitiveObject()); + } + + @Test + void testAcceptObjIntConsumer() { + final IllegalStateException ise = new IllegalStateException(); + final Testable testable = new Testable<>(ise); + Throwable e = assertThrows(IllegalStateException.class, () -> Functions.accept(testable::testObjInt, "X", 1)); + assertSame(ise, e); + assertNull(testable.getAcceptedObject()); + assertNull(testable.getAcceptedPrimitiveObject()); + + final Error error = new OutOfMemoryError(); + testable.setThrowable(error); + e = assertThrows(OutOfMemoryError.class, () -> Functions.accept(testable::testObjInt, "X", 1)); + assertSame(error, e); + assertNull(testable.getAcceptedObject()); + assertNull(testable.getAcceptedPrimitiveObject()); + + final IOException ioe = new IOException("Unknown I/O error"); + testable.setThrowable(ioe); + e = assertThrows(UncheckedIOException.class, () -> Functions.accept(testable::testObjInt, "X", 1)); + final Throwable t = e.getCause(); + assertNotNull(t); + assertSame(ioe, t); + assertNull(testable.getAcceptedObject()); + assertNull(testable.getAcceptedPrimitiveObject()); + + testable.setThrowable(null); + Functions.accept(testable::testObjInt, "X", 1); + assertEquals("X", testable.getAcceptedObject()); + assertEquals(1, testable.getAcceptedPrimitiveObject()); + } + + @Test + void testAcceptObjLongConsumer() { + final IllegalStateException ise = new IllegalStateException(); + final Testable testable = new Testable<>(ise); + Throwable e = assertThrows(IllegalStateException.class, () -> Functions.accept(testable::testObjLong, "X", 1L)); + assertSame(ise, e); + assertNull(testable.getAcceptedObject()); + assertNull(testable.getAcceptedPrimitiveObject()); + + final Error error = new OutOfMemoryError(); + testable.setThrowable(error); + e = assertThrows(OutOfMemoryError.class, () -> Functions.accept(testable::testObjLong, "X", 1L)); + assertSame(error, e); + assertNull(testable.getAcceptedObject()); + assertNull(testable.getAcceptedPrimitiveObject()); + + final IOException ioe = new IOException("Unknown I/O error"); + testable.setThrowable(ioe); + e = assertThrows(UncheckedIOException.class, () -> Functions.accept(testable::testObjLong, "X", 1L)); + final Throwable t = e.getCause(); + assertNotNull(t); + assertSame(ioe, t); + assertNull(testable.getAcceptedObject()); + assertNull(testable.getAcceptedPrimitiveObject()); + + testable.setThrowable(null); + Functions.accept(testable::testObjLong, "X", 1L); + assertEquals("X", testable.getAcceptedObject()); + assertEquals(1L, testable.getAcceptedPrimitiveObject()); + } + @Test public void testApplyBiFunction() { final IllegalStateException ise = new IllegalStateException(); - final Testable testable = new Testable(null); + final Testable testable = new Testable(null); Throwable e = assertThrows(IllegalStateException.class, () -> Functions.apply(Testable::testInteger, testable, ise)); assertSame(ise, e); @@ -261,7 +479,7 @@ public void testApplyBiFunction() { @Test public void testApplyFunction() { final IllegalStateException ise = new IllegalStateException(); - final Testable testable = new Testable(ise); + final Testable testable = new Testable<>(ise); Throwable e = assertThrows(IllegalStateException.class, () -> Functions.apply(Testable::testInteger, testable)); assertSame(ise, e); @@ -286,7 +504,7 @@ public void testApplyFunction() { @Test void testAsBiConsumer() { final IllegalStateException ise = new IllegalStateException(); - final Testable testable = new Testable(null); + final Testable testable = new Testable(null); final FailableBiConsumer failableBiConsumer = (t, th) -> { t.setThrowable(th); t.test(); }; @@ -311,7 +529,7 @@ void testAsBiConsumer() { @Test public void testAsBiFunction() { final IllegalStateException ise = new IllegalStateException(); - final Testable testable = new Testable(ise); + final Testable testable = new Testable<>(ise); final FailableBiFunction failableBiFunction = (t, th) -> { t.setThrowable(th); return Integer.valueOf(t.testInteger()); @@ -372,7 +590,7 @@ void testAsCallable() { @Test void testAsConsumer() { final IllegalStateException ise = new IllegalStateException(); - final Testable testable = new Testable(ise); + final Testable testable = new Testable<>(ise); final Consumer consumer = Functions.asConsumer(Testable::test); Throwable e = assertThrows(IllegalStateException.class, () -> consumer.accept(testable)); assertSame(ise, e); @@ -396,7 +614,7 @@ void testAsConsumer() { @Test public void testAsFunction() { final IllegalStateException ise = new IllegalStateException(); - final Testable testable = new Testable(ise); + final Testable testable = new Testable<>(ise); final FailableFunction failableFunction = th -> { testable.setThrowable(th); return Integer.valueOf(testable.testInteger()); @@ -477,7 +695,7 @@ void testCallable() { @Test public void testGetAsBooleanSupplier() { final IllegalStateException ise = new IllegalStateException(); - final Testable testable = new Testable(ise); + final Testable testable = new Testable<>(ise); Throwable e = assertThrows(IllegalStateException.class, () -> Functions.getAsBoolean(testable::testBooleanPrimitive)); assertSame(ise, e); @@ -500,7 +718,7 @@ public void testGetAsBooleanSupplier() { @Test public void testGetAsDoubleSupplier() { final IllegalStateException ise = new IllegalStateException(); - final Testable testable = new Testable(ise); + final Testable testable = new Testable<>(ise); Throwable e = assertThrows(IllegalStateException.class, () -> Functions.getAsDouble(testable::testDoublePrimitive)); assertSame(ise, e); @@ -523,7 +741,7 @@ public void testGetAsDoubleSupplier() { @Test public void testGetAsIntSupplier() { final IllegalStateException ise = new IllegalStateException(); - final Testable testable = new Testable(ise); + final Testable testable = new Testable<>(ise); Throwable e = assertThrows(IllegalStateException.class, () -> Functions.getAsInt(testable::testIntPrimitive)); assertSame(ise, e); @@ -547,7 +765,7 @@ public void testGetAsIntSupplier() { @Test public void testGetAsLongSupplier() { final IllegalStateException ise = new IllegalStateException(); - final Testable testable = new Testable(ise); + final Testable testable = new Testable<>(ise); Throwable e = assertThrows(IllegalStateException.class, () -> Functions.getAsLong(testable::testLongPrimitive)); assertSame(ise, e); @@ -583,7 +801,7 @@ public void testGetFromSupplier() { @Test public void testGetSupplier() { final IllegalStateException ise = new IllegalStateException(); - final Testable testable = new Testable(ise); + final Testable testable = new Testable<>(ise); Throwable e = assertThrows(IllegalStateException.class, () -> Functions.get(testable::testInteger)); assertSame(ise, e); From 67929942a58c16c877715a38861de724b488a81d Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Fri, 12 Jun 2020 15:35:28 -0400 Subject: [PATCH 0099/3230] - Update com.github.spotbugs:spotbugs 4.0.3 -> 4.0.4. - Update com.puppycrawl.tools:checkstyle 8.32 -> 8.33. --- pom.xml | 4 ++-- src/changes/changes.xml | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/pom.xml b/pom.xml index c3ecae7626c..d8f68a9f80a 100644 --- a/pom.xml +++ b/pom.xml @@ -600,7 +600,7 @@ utf-8 3.1.1 - 8.32 + 8.33 src/site/resources/checkstyle 4.0.0 @@ -765,7 +765,7 @@ com.github.spotbugs spotbugs - 4.0.3 + 4.0.4 diff --git a/src/changes/changes.xml b/src/changes/changes.xml index a51e645f943..c34b0f692ce 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -49,8 +49,8 @@ The type attribute can be add,update,fix,remove. Fix Javadoc for StringUtils.appendIfMissingIgnoreCase() #507. org.junit-pioneer:junit-pioneer 0.5.4 -> 0.6.0. org.junit.jupiter:junit-jupiter 5.6.0 -> 5.6.1. - com.github.spotbugs:spotbugs 4.0.0 -> 4.0.3. - com.puppycrawl.tools:checkstyle 8.29 -> 8.32. + com.github.spotbugs:spotbugs 4.0.0 -> 4.0.4. + com.puppycrawl.tools:checkstyle 8.29 -> 8.33. Simplify null checks in Pair.hashCode() using Objects.hashCode(). #517. Simplify null checks in Triple.hashCode() using Objects.hashCode(). #516. Simplify some if statements in StringUtils. #521. @@ -60,7 +60,7 @@ The type attribute can be add,update,fix,remove. Add ArrayUtils.isSameLength() to compare more array types #430. CharSequenceUtils.regionMatches is wrong dealing with Georgian. Added the Locks class as a convenient possibility to deal with locked objects. - Add to Functions: FailableBooleanSupplier, FailableIntSupplier, FailableLongSupplier, FailableDoubleSupplier. + Add to Functions: FailableBooleanSupplier, FailableIntSupplier, FailableLongSupplier, FailableDoubleSupplier, and so on. From 6094cf2237b89c1a02cc433659f874ebccd610dd Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Fri, 12 Jun 2020 16:15:01 -0400 Subject: [PATCH 0100/3230] Remove trailing white space. --- src/main/java/org/apache/commons/lang3/Functions.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/apache/commons/lang3/Functions.java b/src/main/java/org/apache/commons/lang3/Functions.java index e52b749ed8a..0f701f498bf 100644 --- a/src/main/java/org/apache/commons/lang3/Functions.java +++ b/src/main/java/org/apache/commons/lang3/Functions.java @@ -325,7 +325,7 @@ public interface FailableLongSupplier { /** * A functional interface like {@link ObjDoubleConsumer} that declares a Throwable. - * + * * @param the type of the object argument to the operation. * @param Thrown exception. * @since 3.11 From 40cb020e8da5564fb71aceda3cc3ed345bfa341f Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Fri, 12 Jun 2020 16:20:28 -0400 Subject: [PATCH 0101/3230] Sort members. --- .../java/org/apache/commons/lang3/ArrayUtils.java | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/ArrayUtils.java b/src/main/java/org/apache/commons/lang3/ArrayUtils.java index d8d7ff5c6f1..c620c7983a0 100644 --- a/src/main/java/org/apache/commons/lang3/ArrayUtils.java +++ b/src/main/java/org/apache/commons/lang3/ArrayUtils.java @@ -100,13 +100,6 @@ public class ArrayUtils { */ public static final Field[] EMPTY_FIELD_ARRAY = new Field[0]; - /** - * An empty immutable {@code Method} array. - * - * @since 3.10 - */ - public static final Method[] EMPTY_METHOD_ARRAY = new Method[0]; - /** * An empty immutable {@code float} array. */ @@ -137,6 +130,13 @@ public class ArrayUtils { */ public static final Long[] EMPTY_LONG_OBJECT_ARRAY = new Long[0]; + /** + * An empty immutable {@code Method} array. + * + * @since 3.10 + */ + public static final Method[] EMPTY_METHOD_ARRAY = new Method[0]; + /** * An empty immutable {@code Object} array. */ From 495167a3922826b19b381c3151634d66ac85b9b4 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Fri, 12 Jun 2020 16:25:35 -0400 Subject: [PATCH 0102/3230] Sort members. --- .../commons/lang3/ArrayUtilsInsertTest.java | 50 +- .../lang3/ArrayUtilsRemoveMultipleTest.java | 480 +- .../apache/commons/lang3/ArrayUtilsTest.java | 10258 ++++++++-------- 3 files changed, 5394 insertions(+), 5394 deletions(-) diff --git a/src/test/java/org/apache/commons/lang3/ArrayUtilsInsertTest.java b/src/test/java/org/apache/commons/lang3/ArrayUtilsInsertTest.java index 134982cf158..a924f7a5e69 100644 --- a/src/test/java/org/apache/commons/lang3/ArrayUtilsInsertTest.java +++ b/src/test/java/org/apache/commons/lang3/ArrayUtilsInsertTest.java @@ -152,6 +152,31 @@ public void testInsertFloats() { assertArrayEquals(new float[]{1, 2, 3, 4, 5, 6}, ArrayUtils.insert(array.length, array, values), delta); } + @Test + public void testInsertGenericArray() { + final String[] array = {"a", "b", "c"}; + final String[] values = {"d", "e", "f"}; + + final String[] result = ArrayUtils.insert(42, array, (String[]) null); + assertArrayEquals(array, result); + assertNotSame(array, result); + + assertNull(ArrayUtils.insert(42, null, array)); + assertArrayEquals(new String[0], ArrayUtils.insert(0, new String[0], (String[]) null)); + assertNull(ArrayUtils.insert(42, null, (String[]) null)); + + assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.insert(-1, array, array)); + assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.insert(array.length + 1, array, array)); + + assertArrayEquals(new String[]{"z", "a", "b", "c"}, ArrayUtils.insert(0, array, "z")); + assertArrayEquals(new String[]{"a", "z", "b", "c"}, ArrayUtils.insert(1, array, "z")); + assertArrayEquals(new String[]{"a", "b", "c", "z"}, ArrayUtils.insert(array.length, array, "z")); + assertArrayEquals(new String[]{"d", "e", "f", "a", "b", "c"}, ArrayUtils.insert(0, array, values)); + assertArrayEquals(new String[]{"a", "d", "e", "f", "b", "c"}, ArrayUtils.insert(1, array, values)); + assertArrayEquals(new String[]{"a", "b", "c", "d", "e", "f"}, ArrayUtils.insert(array.length, array, values)); + } + + @Test public void testInsertInts() { final int[] array = {1, 2, 3}; @@ -225,29 +250,4 @@ public void testInsertShorts() { assertArrayEquals(new short[]{1, 4, 5, 6, 2, 3}, ArrayUtils.insert(1, array, values)); assertArrayEquals(new short[]{1, 2, 3, 4, 5, 6}, ArrayUtils.insert(array.length, array, values)); } - - - @Test - public void testInsertGenericArray() { - final String[] array = {"a", "b", "c"}; - final String[] values = {"d", "e", "f"}; - - final String[] result = ArrayUtils.insert(42, array, (String[]) null); - assertArrayEquals(array, result); - assertNotSame(array, result); - - assertNull(ArrayUtils.insert(42, null, array)); - assertArrayEquals(new String[0], ArrayUtils.insert(0, new String[0], (String[]) null)); - assertNull(ArrayUtils.insert(42, null, (String[]) null)); - - assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.insert(-1, array, array)); - assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.insert(array.length + 1, array, array)); - - assertArrayEquals(new String[]{"z", "a", "b", "c"}, ArrayUtils.insert(0, array, "z")); - assertArrayEquals(new String[]{"a", "z", "b", "c"}, ArrayUtils.insert(1, array, "z")); - assertArrayEquals(new String[]{"a", "b", "c", "z"}, ArrayUtils.insert(array.length, array, "z")); - assertArrayEquals(new String[]{"d", "e", "f", "a", "b", "c"}, ArrayUtils.insert(0, array, values)); - assertArrayEquals(new String[]{"a", "d", "e", "f", "b", "c"}, ArrayUtils.insert(1, array, values)); - assertArrayEquals(new String[]{"a", "b", "c", "d", "e", "f"}, ArrayUtils.insert(array.length, array, values)); - } } diff --git a/src/test/java/org/apache/commons/lang3/ArrayUtilsRemoveMultipleTest.java b/src/test/java/org/apache/commons/lang3/ArrayUtilsRemoveMultipleTest.java index 58d7681d0a9..b5d30aa793e 100644 --- a/src/test/java/org/apache/commons/lang3/ArrayUtilsRemoveMultipleTest.java +++ b/src/test/java/org/apache/commons/lang3/ArrayUtilsRemoveMultipleTest.java @@ -30,110 +30,6 @@ */ public class ArrayUtilsRemoveMultipleTest { - @Test - public void testRemoveAllObjectArray() { - Object[] array; - - array = ArrayUtils.removeAll(new Object[] { "a" }, 0); - assertArrayEquals(ArrayUtils.EMPTY_OBJECT_ARRAY, array); - assertEquals(Object.class, array.getClass().getComponentType()); - - array = ArrayUtils.removeAll(new Object[] { "a", "b" }, 0, 1); - assertArrayEquals(ArrayUtils.EMPTY_OBJECT_ARRAY, array); - assertEquals(Object.class, array.getClass().getComponentType()); - - array = ArrayUtils.removeAll(new Object[] { "a", "b", "c" }, 1, 2); - assertArrayEquals(new Object[] { "a" }, array); - assertEquals(Object.class, array.getClass().getComponentType()); - - array = ArrayUtils.removeAll(new Object[] { "a", "b", "c", "d" }, 1, 2); - assertArrayEquals(new Object[] { "a", "d" }, array); - assertEquals(Object.class, array.getClass().getComponentType()); - - array = ArrayUtils.removeAll(new Object[] { "a", "b", "c", "d" }, 0, 3); - assertArrayEquals(new Object[] { "b", "c" }, array); - assertEquals(Object.class, array.getClass().getComponentType()); - - array = ArrayUtils.removeAll(new Object[] { "a", "b", "c", "d" }, 0, 1, 3); - assertArrayEquals(new Object[] { "c" }, array); - assertEquals(Object.class, array.getClass().getComponentType()); - - array = ArrayUtils.removeAll(new Object[] { "a", "b", "c", "d", "e" }, 0, 1, 3); - assertArrayEquals(new Object[] { "c", "e" }, array); - assertEquals(Object.class, array.getClass().getComponentType()); - - array = ArrayUtils.removeAll(new Object[] { "a", "b", "c", "d", "e" }, 0, 2, 4); - assertArrayEquals(new Object[] { "b", "d" }, array); - assertEquals(Object.class, array.getClass().getComponentType()); - - array = ArrayUtils.removeAll(new Object[] { "a", "b", "c", "d" }, 0, 1, 3, 0, 1, 3); - assertArrayEquals(new Object[] { "c" }, array); - assertEquals(Object.class, array.getClass().getComponentType()); - - array = ArrayUtils.removeAll(new Object[] { "a", "b", "c", "d" }, 2, 1, 0, 3); - assertArrayEquals(ArrayUtils.EMPTY_OBJECT_ARRAY, array); - assertEquals(Object.class, array.getClass().getComponentType()); - - array = ArrayUtils.removeAll(new Object[] { "a", "b", "c", "d" }, 2, 0, 1, 3, 0, 2, 1, 3); - assertArrayEquals(ArrayUtils.EMPTY_OBJECT_ARRAY, array); - assertEquals(Object.class, array.getClass().getComponentType()); - } - - @Test - public void testRemoveAllObjectArrayRemoveNone() { - final Object[] array1 = new Object[] { "foo", "bar", "baz" }; - final Object[] array2 = ArrayUtils.removeAll(array1); - assertNotSame(array1, array2); - assertArrayEquals(array1, array2); - assertEquals(Object.class, array2.getClass().getComponentType()); - } - - @Test - public void testRemoveAllObjectArrayNegativeIndex() { - assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.removeAll(new Object[] { "a", "b" }, -1)); - } - - @Test - public void testRemoveAllObjectArrayOutOfBoundsIndex() { - assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.removeAll(new Object[] { "a", "b" }, 2)); - } - - @Test - public void testRemoveAllNullObjectArray() { - assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove((Object[]) null, 0)); - } - - @Test - public void testRemoveAllNumberArray() { - final Number[] inarray = { Integer.valueOf(1), Long.valueOf(2L), Byte.valueOf((byte) 3) }; - assertEquals(3, inarray.length); - Number[] outarray; - - outarray = ArrayUtils.removeAll(inarray, 1); - assertArrayEquals(new Number[] { Integer.valueOf(1), Byte.valueOf((byte) 3) }, outarray); - assertEquals(Number.class, outarray.getClass().getComponentType()); - - outarray = ArrayUtils.removeAll(outarray, 1); - assertArrayEquals(new Number[] { Integer.valueOf(1) }, outarray); - assertEquals(Number.class, outarray.getClass().getComponentType()); - - outarray = ArrayUtils.removeAll(outarray, 0); - assertEquals(0, outarray.length); - assertEquals(Number.class, outarray.getClass().getComponentType()); - - outarray = ArrayUtils.removeAll(inarray, 0, 1); - assertArrayEquals(new Number[] { Byte.valueOf((byte) 3) }, outarray); - assertEquals(Number.class, outarray.getClass().getComponentType()); - - outarray = ArrayUtils.removeAll(inarray, 0, 2); - assertArrayEquals(new Number[] { Long.valueOf(2L) }, outarray); - assertEquals(Number.class, outarray.getClass().getComponentType()); - - outarray = ArrayUtils.removeAll(inarray, 1, 2); - assertArrayEquals(new Number[] { Integer.valueOf(1) }, outarray); - assertEquals(Number.class, outarray.getClass().getComponentType()); - } - @Test public void testRemoveAllBooleanArray() { boolean[] array; @@ -195,15 +91,6 @@ public void testRemoveAllBooleanArray() { assertEquals(Boolean.TYPE, array.getClass().getComponentType()); } - @Test - public void testRemoveAllBooleanArrayRemoveNone() { - final boolean[] array1 = new boolean[] { true, false }; - final boolean[] array2 = ArrayUtils.removeAll(array1); - assertNotSame(array1, array2); - assertArrayEquals(array1, array2); - assertEquals(boolean.class, array2.getClass().getComponentType()); - } - @Test public void testRemoveAllBooleanArrayNegativeIndex() { assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.removeAll(new boolean[] { true, false }, -1)); @@ -215,8 +102,12 @@ public void testRemoveAllBooleanArrayOutOfBoundsIndex() { } @Test - public void testRemoveAllNullBooleanArray() { - assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.removeAll((boolean[]) null, 0)); + public void testRemoveAllBooleanArrayRemoveNone() { + final boolean[] array1 = new boolean[] { true, false }; + final boolean[] array2 = ArrayUtils.removeAll(array1); + assertNotSame(array1, array2); + assertArrayEquals(array1, array2); + assertEquals(boolean.class, array2.getClass().getComponentType()); } @Test @@ -272,15 +163,6 @@ public void testRemoveAllByteArray() { assertEquals(Byte.TYPE, array.getClass().getComponentType()); } - @Test - public void testRemoveAllByteArrayRemoveNone() { - final byte[] array1 = new byte[] { 1, 2 }; - final byte[] array2 = ArrayUtils.removeAll(array1); - assertNotSame(array1, array2); - assertArrayEquals(array1, array2); - assertEquals(byte.class, array2.getClass().getComponentType()); - } - @Test public void testRemoveAllByteArrayNegativeIndex() { assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.removeAll(new byte[] { 1, 2 }, -1)); @@ -292,8 +174,12 @@ public void testRemoveAllByteArrayOutOfBoundsIndex() { } @Test - public void testRemoveAllNullByteArray() { - assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.removeAll((byte[]) null, 0)); + public void testRemoveAllByteArrayRemoveNone() { + final byte[] array1 = new byte[] { 1, 2 }; + final byte[] array2 = ArrayUtils.removeAll(array1); + assertNotSame(array1, array2); + assertArrayEquals(array1, array2); + assertEquals(byte.class, array2.getClass().getComponentType()); } @Test @@ -349,15 +235,6 @@ public void testRemoveAllCharArray() { assertEquals(Character.TYPE, array.getClass().getComponentType()); } - @Test - public void testRemoveAllCharArrayRemoveNone() { - final char[] array1 = new char[] { 'a', 'b' }; - final char[] array2 = ArrayUtils.removeAll(array1); - assertNotSame(array1, array2); - assertArrayEquals(array1, array2); - assertEquals(char.class, array2.getClass().getComponentType()); - } - @Test public void testRemoveAllCharArrayNegativeIndex() { assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.removeAll(new char[] { 'a', 'b' }, -1)); @@ -369,8 +246,12 @@ public void testRemoveAllCharArrayOutOfBoundsIndex() { } @Test - public void testRemoveAllNullCharArray() { - assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.removeAll((char[]) null, 0)); + public void testRemoveAllCharArrayRemoveNone() { + final char[] array1 = new char[] { 'a', 'b' }; + final char[] array2 = ArrayUtils.removeAll(array1); + assertNotSame(array1, array2); + assertArrayEquals(array1, array2); + assertEquals(char.class, array2.getClass().getComponentType()); } @Test @@ -426,15 +307,6 @@ public void testRemoveAllDoubleArray() { assertEquals(Double.TYPE, array.getClass().getComponentType()); } - @Test - public void testRemoveAllDoubleArrayRemoveNone() { - final double[] array1 = new double[] { 1, 2 }; - final double[] array2 = ArrayUtils.removeAll(array1); - assertNotSame(array1, array2); - assertArrayEquals(array1, array2); - assertEquals(double.class, array2.getClass().getComponentType()); - } - @Test public void testRemoveAllDoubleArrayNegativeIndex() { assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.removeAll(new double[] { 1, 2 }, -1)); @@ -446,8 +318,12 @@ public void testRemoveAllDoubleArrayOutOfBoundsIndex() { } @Test - public void testRemoveAllNullDoubleArray() { - assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.removeAll((double[]) null, 0)); + public void testRemoveAllDoubleArrayRemoveNone() { + final double[] array1 = new double[] { 1, 2 }; + final double[] array2 = ArrayUtils.removeAll(array1); + assertNotSame(array1, array2); + assertArrayEquals(array1, array2); + assertEquals(double.class, array2.getClass().getComponentType()); } @Test @@ -503,15 +379,6 @@ public void testRemoveAllFloatArray() { assertEquals(Float.TYPE, array.getClass().getComponentType()); } - @Test - public void testRemoveAllFloatArrayRemoveNone() { - final float[] array1 = new float[] { 1, 2 }; - final float[] array2 = ArrayUtils.removeAll(array1); - assertNotSame(array1, array2); - assertArrayEquals(array1, array2); - assertEquals(float.class, array2.getClass().getComponentType()); - } - @Test public void testRemoveAllFloatArrayNegativeIndex() { assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.removeAll(new float[] { 1, 2 }, -1)); @@ -523,8 +390,12 @@ public void testRemoveAllFloatArrayOutOfBoundsIndex() { } @Test - public void testRemoveAllNullFloatArray() { - assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.removeAll((float[]) null, 0)); + public void testRemoveAllFloatArrayRemoveNone() { + final float[] array1 = new float[] { 1, 2 }; + final float[] array2 = ArrayUtils.removeAll(array1); + assertNotSame(array1, array2); + assertArrayEquals(array1, array2); + assertEquals(float.class, array2.getClass().getComponentType()); } @Test @@ -586,15 +457,6 @@ public void testRemoveAllIntArray() { assertEquals(Integer.TYPE, array.getClass().getComponentType()); } - @Test - public void testRemoveAllIntArrayRemoveNone() { - final int[] array1 = new int[] { 1, 2 }; - final int[] array2 = ArrayUtils.removeAll(array1); - assertNotSame(array1, array2); - assertArrayEquals(array1, array2); - assertEquals(int.class, array2.getClass().getComponentType()); - } - @Test public void testRemoveAllIntArrayNegativeIndex() { assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.removeAll(new int[] { 1, 2 }, -1)); @@ -606,8 +468,12 @@ public void testRemoveAllIntArrayOutOfBoundsIndex() { } @Test - public void testRemoveAllNullIntArray() { - assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.removeAll((int[]) null, 0)); + public void testRemoveAllIntArrayRemoveNone() { + final int[] array1 = new int[] { 1, 2 }; + final int[] array2 = ArrayUtils.removeAll(array1); + assertNotSame(array1, array2); + assertArrayEquals(array1, array2); + assertEquals(int.class, array2.getClass().getComponentType()); } @Test @@ -663,6 +529,16 @@ public void testRemoveAllLongArray() { assertEquals(Long.TYPE, array.getClass().getComponentType()); } + @Test + public void testRemoveAllLongArrayNegativeIndex() { + assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.removeAll(new long[] { 1, 2 }, -1)); + } + + @Test + public void testRemoveAllLongArrayOutOfBoundsIndex() { + assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.removeAll(new long[] { 1, 2 }, 2)); + } + @Test public void testRemoveAllLongArrayRemoveNone() { final long[] array1 = new long[] { 1, 2 }; @@ -673,13 +549,33 @@ public void testRemoveAllLongArrayRemoveNone() { } @Test - public void testRemoveAllLongArrayNegativeIndex() { - assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.removeAll(new long[] { 1, 2 }, -1)); + public void testRemoveAllNullBooleanArray() { + assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.removeAll((boolean[]) null, 0)); } @Test - public void testRemoveAllLongArrayOutOfBoundsIndex() { - assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.removeAll(new long[] { 1, 2 }, 2)); + public void testRemoveAllNullByteArray() { + assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.removeAll((byte[]) null, 0)); + } + + @Test + public void testRemoveAllNullCharArray() { + assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.removeAll((char[]) null, 0)); + } + + @Test + public void testRemoveAllNullDoubleArray() { + assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.removeAll((double[]) null, 0)); + } + + @Test + public void testRemoveAllNullFloatArray() { + assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.removeAll((float[]) null, 0)); + } + + @Test + public void testRemoveAllNullIntArray() { + assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.removeAll((int[]) null, 0)); } @Test @@ -687,6 +583,115 @@ public void testRemoveAllNullLongArray() { assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.removeAll((long[]) null, 0)); } + @Test + public void testRemoveAllNullObjectArray() { + assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove((Object[]) null, 0)); + } + + @Test + public void testRemoveAllNullShortArray() { + assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.removeAll((short[]) null, 0)); + } + + @Test + public void testRemoveAllNumberArray() { + final Number[] inarray = { Integer.valueOf(1), Long.valueOf(2L), Byte.valueOf((byte) 3) }; + assertEquals(3, inarray.length); + Number[] outarray; + + outarray = ArrayUtils.removeAll(inarray, 1); + assertArrayEquals(new Number[] { Integer.valueOf(1), Byte.valueOf((byte) 3) }, outarray); + assertEquals(Number.class, outarray.getClass().getComponentType()); + + outarray = ArrayUtils.removeAll(outarray, 1); + assertArrayEquals(new Number[] { Integer.valueOf(1) }, outarray); + assertEquals(Number.class, outarray.getClass().getComponentType()); + + outarray = ArrayUtils.removeAll(outarray, 0); + assertEquals(0, outarray.length); + assertEquals(Number.class, outarray.getClass().getComponentType()); + + outarray = ArrayUtils.removeAll(inarray, 0, 1); + assertArrayEquals(new Number[] { Byte.valueOf((byte) 3) }, outarray); + assertEquals(Number.class, outarray.getClass().getComponentType()); + + outarray = ArrayUtils.removeAll(inarray, 0, 2); + assertArrayEquals(new Number[] { Long.valueOf(2L) }, outarray); + assertEquals(Number.class, outarray.getClass().getComponentType()); + + outarray = ArrayUtils.removeAll(inarray, 1, 2); + assertArrayEquals(new Number[] { Integer.valueOf(1) }, outarray); + assertEquals(Number.class, outarray.getClass().getComponentType()); + } + + @Test + public void testRemoveAllObjectArray() { + Object[] array; + + array = ArrayUtils.removeAll(new Object[] { "a" }, 0); + assertArrayEquals(ArrayUtils.EMPTY_OBJECT_ARRAY, array); + assertEquals(Object.class, array.getClass().getComponentType()); + + array = ArrayUtils.removeAll(new Object[] { "a", "b" }, 0, 1); + assertArrayEquals(ArrayUtils.EMPTY_OBJECT_ARRAY, array); + assertEquals(Object.class, array.getClass().getComponentType()); + + array = ArrayUtils.removeAll(new Object[] { "a", "b", "c" }, 1, 2); + assertArrayEquals(new Object[] { "a" }, array); + assertEquals(Object.class, array.getClass().getComponentType()); + + array = ArrayUtils.removeAll(new Object[] { "a", "b", "c", "d" }, 1, 2); + assertArrayEquals(new Object[] { "a", "d" }, array); + assertEquals(Object.class, array.getClass().getComponentType()); + + array = ArrayUtils.removeAll(new Object[] { "a", "b", "c", "d" }, 0, 3); + assertArrayEquals(new Object[] { "b", "c" }, array); + assertEquals(Object.class, array.getClass().getComponentType()); + + array = ArrayUtils.removeAll(new Object[] { "a", "b", "c", "d" }, 0, 1, 3); + assertArrayEquals(new Object[] { "c" }, array); + assertEquals(Object.class, array.getClass().getComponentType()); + + array = ArrayUtils.removeAll(new Object[] { "a", "b", "c", "d", "e" }, 0, 1, 3); + assertArrayEquals(new Object[] { "c", "e" }, array); + assertEquals(Object.class, array.getClass().getComponentType()); + + array = ArrayUtils.removeAll(new Object[] { "a", "b", "c", "d", "e" }, 0, 2, 4); + assertArrayEquals(new Object[] { "b", "d" }, array); + assertEquals(Object.class, array.getClass().getComponentType()); + + array = ArrayUtils.removeAll(new Object[] { "a", "b", "c", "d" }, 0, 1, 3, 0, 1, 3); + assertArrayEquals(new Object[] { "c" }, array); + assertEquals(Object.class, array.getClass().getComponentType()); + + array = ArrayUtils.removeAll(new Object[] { "a", "b", "c", "d" }, 2, 1, 0, 3); + assertArrayEquals(ArrayUtils.EMPTY_OBJECT_ARRAY, array); + assertEquals(Object.class, array.getClass().getComponentType()); + + array = ArrayUtils.removeAll(new Object[] { "a", "b", "c", "d" }, 2, 0, 1, 3, 0, 2, 1, 3); + assertArrayEquals(ArrayUtils.EMPTY_OBJECT_ARRAY, array); + assertEquals(Object.class, array.getClass().getComponentType()); + } + + @Test + public void testRemoveAllObjectArrayNegativeIndex() { + assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.removeAll(new Object[] { "a", "b" }, -1)); + } + + @Test + public void testRemoveAllObjectArrayOutOfBoundsIndex() { + assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.removeAll(new Object[] { "a", "b" }, 2)); + } + + @Test + public void testRemoveAllObjectArrayRemoveNone() { + final Object[] array1 = new Object[] { "foo", "bar", "baz" }; + final Object[] array2 = ArrayUtils.removeAll(array1); + assertNotSame(array1, array2); + assertArrayEquals(array1, array2); + assertEquals(Object.class, array2.getClass().getComponentType()); + } + @Test public void testRemoveAllShortArray() { short[] array; @@ -740,15 +745,6 @@ public void testRemoveAllShortArray() { assertEquals(Short.TYPE, array.getClass().getComponentType()); } - @Test - public void testRemoveAllShortArrayRemoveNone() { - final short[] array1 = new short[] { 1, 2 }; - final short[] array2 = ArrayUtils.removeAll(array1); - assertNotSame(array1, array2); - assertArrayEquals(array1, array2); - assertEquals(short.class, array2.getClass().getComponentType()); - } - @Test public void testRemoveAllShortArrayNegativeIndex() { assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.removeAll(new short[] { 1, 2 }, -1, 0)); @@ -760,63 +756,12 @@ public void testRemoveAllShortArrayOutOfBoundsIndex() { } @Test - public void testRemoveAllNullShortArray() { - assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.removeAll((short[]) null, 0)); - } - - @Test - public void testRemoveElementsObjectArray() { - Object[] array; - - array = ArrayUtils.removeElements((Object[]) null, "a"); - assertNull(array); - - array = ArrayUtils.removeElements(ArrayUtils.EMPTY_OBJECT_ARRAY, "a"); - assertArrayEquals(ArrayUtils.EMPTY_OBJECT_ARRAY, array); - assertEquals(Object.class, array.getClass().getComponentType()); - - array = ArrayUtils.removeElements(new Object[] { "a" }, "a"); - assertArrayEquals(ArrayUtils.EMPTY_OBJECT_ARRAY, array); - assertEquals(Object.class, array.getClass().getComponentType()); - - array = ArrayUtils.removeElements(new Object[] { "a", "b" }, "a"); - assertArrayEquals(new Object[]{"b"}, array); - assertEquals(Object.class, array.getClass().getComponentType()); - - array = ArrayUtils.removeElements(new Object[] { "a", "b", "a" }, "a"); - assertArrayEquals(new Object[]{"b", "a"}, array); - assertEquals(Object.class, array.getClass().getComponentType()); - - array = ArrayUtils.removeElements((Object[]) null, "a", "b"); - assertNull(array); - - array = ArrayUtils.removeElements(ArrayUtils.EMPTY_OBJECT_ARRAY, "a", "b"); - assertArrayEquals(ArrayUtils.EMPTY_OBJECT_ARRAY, array); - assertEquals(Object.class, array.getClass().getComponentType()); - - array = ArrayUtils.removeElements(new Object[] { "a" }, "a", "b"); - assertArrayEquals(ArrayUtils.EMPTY_OBJECT_ARRAY, array); - assertEquals(Object.class, array.getClass().getComponentType()); - - array = ArrayUtils.removeElements(new Object[] { "a", "b" }, "a", "c"); - assertArrayEquals(new Object[]{"b"}, array); - assertEquals(Object.class, array.getClass().getComponentType()); - - array = ArrayUtils.removeElements(new Object[] { "a", "b", "a" }, "a"); - assertArrayEquals(new Object[]{"b", "a"}, array); - assertEquals(Object.class, array.getClass().getComponentType()); - - array = ArrayUtils.removeElements(new Object[] { "a", "b", "a" }, "a", "b"); - assertArrayEquals(new Object[]{"a"}, array); - assertEquals(Object.class, array.getClass().getComponentType()); - - array = ArrayUtils.removeElements(new Object[] { "a", "b", "a" }, "a", "a"); - assertArrayEquals(new Object[]{"b"}, array); - assertEquals(Object.class, array.getClass().getComponentType()); - - array = ArrayUtils.removeElements(new Object[] { "a", "b", "a" }, "a", "a", "a", "a"); - assertArrayEquals(new Object[]{"b"}, array); - assertEquals(Object.class, array.getClass().getComponentType()); + public void testRemoveAllShortArrayRemoveNone() { + final short[] array1 = new short[] { 1, 2 }; + final short[] array2 = ArrayUtils.removeAll(array1); + assertNotSame(array1, array2); + assertArrayEquals(array1, array2); + assertEquals(short.class, array2.getClass().getComponentType()); } @Test @@ -1262,4 +1207,59 @@ public void testRemoveElementShortArray() { assertEquals(Short.TYPE, array.getClass().getComponentType()); } + @Test + public void testRemoveElementsObjectArray() { + Object[] array; + + array = ArrayUtils.removeElements((Object[]) null, "a"); + assertNull(array); + + array = ArrayUtils.removeElements(ArrayUtils.EMPTY_OBJECT_ARRAY, "a"); + assertArrayEquals(ArrayUtils.EMPTY_OBJECT_ARRAY, array); + assertEquals(Object.class, array.getClass().getComponentType()); + + array = ArrayUtils.removeElements(new Object[] { "a" }, "a"); + assertArrayEquals(ArrayUtils.EMPTY_OBJECT_ARRAY, array); + assertEquals(Object.class, array.getClass().getComponentType()); + + array = ArrayUtils.removeElements(new Object[] { "a", "b" }, "a"); + assertArrayEquals(new Object[]{"b"}, array); + assertEquals(Object.class, array.getClass().getComponentType()); + + array = ArrayUtils.removeElements(new Object[] { "a", "b", "a" }, "a"); + assertArrayEquals(new Object[]{"b", "a"}, array); + assertEquals(Object.class, array.getClass().getComponentType()); + + array = ArrayUtils.removeElements((Object[]) null, "a", "b"); + assertNull(array); + + array = ArrayUtils.removeElements(ArrayUtils.EMPTY_OBJECT_ARRAY, "a", "b"); + assertArrayEquals(ArrayUtils.EMPTY_OBJECT_ARRAY, array); + assertEquals(Object.class, array.getClass().getComponentType()); + + array = ArrayUtils.removeElements(new Object[] { "a" }, "a", "b"); + assertArrayEquals(ArrayUtils.EMPTY_OBJECT_ARRAY, array); + assertEquals(Object.class, array.getClass().getComponentType()); + + array = ArrayUtils.removeElements(new Object[] { "a", "b" }, "a", "c"); + assertArrayEquals(new Object[]{"b"}, array); + assertEquals(Object.class, array.getClass().getComponentType()); + + array = ArrayUtils.removeElements(new Object[] { "a", "b", "a" }, "a"); + assertArrayEquals(new Object[]{"b", "a"}, array); + assertEquals(Object.class, array.getClass().getComponentType()); + + array = ArrayUtils.removeElements(new Object[] { "a", "b", "a" }, "a", "b"); + assertArrayEquals(new Object[]{"a"}, array); + assertEquals(Object.class, array.getClass().getComponentType()); + + array = ArrayUtils.removeElements(new Object[] { "a", "b", "a" }, "a", "a"); + assertArrayEquals(new Object[]{"b"}, array); + assertEquals(Object.class, array.getClass().getComponentType()); + + array = ArrayUtils.removeElements(new Object[] { "a", "b", "a" }, "a", "a", "a", "a"); + assertArrayEquals(new Object[]{"b"}, array); + assertEquals(Object.class, array.getClass().getComponentType()); + } + } diff --git a/src/test/java/org/apache/commons/lang3/ArrayUtilsTest.java b/src/test/java/org/apache/commons/lang3/ArrayUtilsTest.java index 66b4d277df7..686f4647266 100644 --- a/src/test/java/org/apache/commons/lang3/ArrayUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/ArrayUtilsTest.java @@ -45,52 +45,15 @@ @SuppressWarnings("deprecation") // deliberate use of deprecated code public class ArrayUtilsTest { - /** A predefined seed used to initialize {@link Random} in order to get predictable results */ - private static final long SEED = 16111981L; - - //----------------------------------------------------------------------- - @Test - public void testConstructor() { - assertNotNull(new ArrayUtils()); - final Constructor[] cons = ArrayUtils.class.getDeclaredConstructors(); - assertEquals(1, cons.length); - assertTrue(Modifier.isPublic(cons[0].getModifiers())); - assertTrue(Modifier.isPublic(ArrayUtils.class.getModifiers())); - assertFalse(Modifier.isFinal(ArrayUtils.class.getModifiers())); - } - - //----------------------------------------------------------------------- - @Test - public void testToString() { - assertEquals("{}", ArrayUtils.toString(null)); - assertEquals("{}", ArrayUtils.toString(new Object[0])); - assertEquals("{}", ArrayUtils.toString(new String[0])); - assertEquals("{}", ArrayUtils.toString(new String[]{null})); - assertEquals("{pink,blue}", ArrayUtils.toString(new String[]{"pink", "blue"})); - - assertEquals("", ArrayUtils.toString(null, "")); - assertEquals("{}", ArrayUtils.toString(new Object[0], "")); - assertEquals("{}", ArrayUtils.toString(new String[0], "")); - assertEquals("{}", ArrayUtils.toString(new String[]{null}, "")); - assertEquals("{pink,blue}", ArrayUtils.toString(new String[]{"pink", "blue"}, "")); + private class TestClass { } - //----------------------------------------------------------------------- - @Test - public void testHashCode() { - final long[][] array1 = new long[][]{{2, 5}, {4, 5}}; - final long[][] array2 = new long[][]{{2, 5}, {4, 6}}; - assertEquals(ArrayUtils.hashCode(array1), ArrayUtils.hashCode(array1)); - assertNotEquals(ArrayUtils.hashCode(array1), ArrayUtils.hashCode(array2)); - - final Object[] array3 = new Object[]{new String(new char[]{'A', 'B'})}; - final Object[] array4 = new Object[]{"AB"}; - assertEquals(ArrayUtils.hashCode(array3), ArrayUtils.hashCode(array3)); - assertEquals(ArrayUtils.hashCode(array3), ArrayUtils.hashCode(array4)); + /** A predefined seed used to initialize {@link Random} in order to get predictable results */ + private static final long SEED = 16111981L; - final Object[] arrayA = new Object[]{new boolean[]{true, false}, new int[]{6, 7}}; - final Object[] arrayB = new Object[]{new boolean[]{true, false}, new int[]{6, 7}}; - assertEquals(ArrayUtils.hashCode(arrayB), ArrayUtils.hashCode(arrayA)); + @SafeVarargs + private static T[] toArrayPropagatingType(final T... items) { + return ArrayUtils.toArray(items); } //----------------------------------------------------------------------- @@ -106,57 +69,6 @@ private void assertIsEquals(final Object array1, final Object array2, final Obje assertFalse(ArrayUtils.isEquals(array2, array1)); } - @Test - public void testIsEquals() { - final long[][] larray1 = new long[][]{{2, 5}, {4, 5}}; - final long[][] larray2 = new long[][]{{2, 5}, {4, 6}}; - final long[] larray3 = new long[]{2, 5}; - this.assertIsEquals(larray1, larray2, larray3); - - final int[][] iarray1 = new int[][]{{2, 5}, {4, 5}}; - final int[][] iarray2 = new int[][]{{2, 5}, {4, 6}}; - final int[] iarray3 = new int[]{2, 5}; - this.assertIsEquals(iarray1, iarray2, iarray3); - - final short[][] sarray1 = new short[][]{{2, 5}, {4, 5}}; - final short[][] sarray2 = new short[][]{{2, 5}, {4, 6}}; - final short[] sarray3 = new short[]{2, 5}; - this.assertIsEquals(sarray1, sarray2, sarray3); - - final float[][] farray1 = new float[][]{{2, 5}, {4, 5}}; - final float[][] farray2 = new float[][]{{2, 5}, {4, 6}}; - final float[] farray3 = new float[]{2, 5}; - this.assertIsEquals(farray1, farray2, farray3); - - final double[][] darray1 = new double[][]{{2, 5}, {4, 5}}; - final double[][] darray2 = new double[][]{{2, 5}, {4, 6}}; - final double[] darray3 = new double[]{2, 5}; - this.assertIsEquals(darray1, darray2, darray3); - - final byte[][] byteArray1 = new byte[][]{{2, 5}, {4, 5}}; - final byte[][] byteArray2 = new byte[][]{{2, 5}, {4, 6}}; - final byte[] byteArray3 = new byte[]{2, 5}; - this.assertIsEquals(byteArray1, byteArray2, byteArray3); - - final char[][] charArray1 = new char[][]{{2, 5}, {4, 5}}; - final char[][] charArray2 = new char[][]{{2, 5}, {4, 6}}; - final char[] charArray3 = new char[]{2, 5}; - this.assertIsEquals(charArray1, charArray2, charArray3); - - final boolean[][] barray1 = new boolean[][]{{true, false}, {true, true}}; - final boolean[][] barray2 = new boolean[][]{{true, false}, {true, false}}; - final boolean[] barray3 = new boolean[]{false, true}; - this.assertIsEquals(barray1, barray2, barray3); - - final Object[] array3 = new Object[]{new String(new char[]{'A', 'B'})}; - final Object[] array4 = new Object[]{"AB"}; - assertTrue(ArrayUtils.isEquals(array3, array3)); - assertTrue(ArrayUtils.isEquals(array3, array4)); - - assertTrue(ArrayUtils.isEquals(null, null)); - assertFalse(ArrayUtils.isEquals(null, array4)); - } - //----------------------------------------------------------------------- /** * Tests generic array creation with parameters of same type. @@ -169,15 +81,6 @@ public void testArrayCreation() { assertEquals("bar", array[1]); } - /** - * Tests generic array creation with general return type. - */ - @Test - public void testArrayCreationWithGeneralReturnType() { - final Object obj = ArrayUtils.toArray("foo", "bar"); - assertTrue(obj instanceof String[]); - } - /** * Tests generic array creation with parameters of common base type. */ @@ -190,93 +93,12 @@ public void testArrayCreationWithDifferentTypes() { } /** - * Tests generic array creation with generic type. - */ - @Test - public void testIndirectArrayCreation() { - final String[] array = toArrayPropagatingType("foo", "bar"); - assertEquals(2, array.length); - assertEquals("foo", array[0]); - assertEquals("bar", array[1]); - } - - /** - * Tests generic empty array creation with generic type. - */ - @Test - public void testEmptyArrayCreation() { - final String[] array = ArrayUtils.toArray(); - assertEquals(0, array.length); - } - - /** - * Tests indirect generic empty array creation with generic type. + * Tests generic array creation with general return type. */ @Test - public void testIndirectEmptyArrayCreation() { - final String[] array = ArrayUtilsTest.toArrayPropagatingType(); - assertEquals(0, array.length); - } - - @SafeVarargs - private static T[] toArrayPropagatingType(final T... items) { - return ArrayUtils.toArray(items); - } - - //----------------------------------------------------------------------- - @Test - public void testToMap() { - Map map = ArrayUtils.toMap(new String[][]{{"foo", "bar"}, {"hello", "world"}}); - - assertEquals("bar", map.get("foo")); - assertEquals("world", map.get("hello")); - - assertNull(ArrayUtils.toMap(null)); - assertThrows(IllegalArgumentException.class, () -> - ArrayUtils.toMap(new String[][]{{"foo", "bar"}, {"short"}})); - assertThrows(IllegalArgumentException.class, () -> - ArrayUtils.toMap(new Object[]{new Object[]{"foo", "bar"}, "illegal type"})); - assertThrows(IllegalArgumentException.class, () -> - ArrayUtils.toMap(new Object[]{new Object[]{"foo", "bar"}, null})); - - map = ArrayUtils.toMap(new Object[]{new Map.Entry() { - @Override - public Object getKey() { - return "foo"; - } - - @Override - public Object getValue() { - return "bar"; - } - - @Override - public Object setValue(final Object value) { - throw new UnsupportedOperationException(); - } - - @Override - public boolean equals(final Object o) { - throw new UnsupportedOperationException(); - } - - @Override - public int hashCode() { - throw new UnsupportedOperationException(); - } - }}); - assertEquals("bar", map.get("foo")); - - // Return empty map when got input array with length = 0 - assertEquals(Collections.emptyMap(), ArrayUtils.toMap(new Object[0])); - - // Test all null values - map = ArrayUtils.toMap(new Object[][] { {null, null}, {null, null} }); - assertEquals(Collections.singletonMap(null, null), map); - - // Test duplicate keys - map = ArrayUtils.toMap(new Object[][] { {"key", "value2"}, {"key", "value1"} }); - assertEquals(Collections.singletonMap("key", "value1"), map); + public void testArrayCreationWithGeneralReturnType() { + final Object obj = ArrayUtils.toArray("foo", "bar"); + assertTrue(obj instanceof String[]); } //----------------------------------------------------------------------- @@ -308,28 +130,10 @@ public void testCloneBoolean() { } @Test - public void testCloneLong() { - assertNull(ArrayUtils.clone((long[]) null)); - final long[] original = new long[]{0L, 1L}; - final long[] cloned = ArrayUtils.clone(original); - assertArrayEquals(original, cloned); - assertNotSame(original, cloned); - } - - @Test - public void testCloneInt() { - assertNull(ArrayUtils.clone((int[]) null)); - final int[] original = new int[]{5, 8}; - final int[] cloned = ArrayUtils.clone(original); - assertArrayEquals(original, cloned); - assertNotSame(original, cloned); - } - - @Test - public void testCloneShort() { - assertNull(ArrayUtils.clone((short[]) null)); - final short[] original = new short[]{1, 4}; - final short[] cloned = ArrayUtils.clone(original); + public void testCloneByte() { + assertNull(ArrayUtils.clone((byte[]) null)); + final byte[] original = new byte[]{1, 6}; + final byte[] cloned = ArrayUtils.clone(original); assertArrayEquals(original, cloned); assertNotSame(original, cloned); } @@ -343,15 +147,6 @@ public void testCloneChar() { assertNotSame(original, cloned); } - @Test - public void testCloneByte() { - assertNull(ArrayUtils.clone((byte[]) null)); - final byte[] original = new byte[]{1, 6}; - final byte[] cloned = ArrayUtils.clone(original); - assertArrayEquals(original, cloned); - assertNotSame(original, cloned); - } - @Test public void testCloneDouble() { assertNull(ArrayUtils.clone((double[]) null)); @@ -370,2506 +165,2114 @@ public void testCloneFloat() { assertNotSame(original, cloned); } - //----------------------------------------------------------------------- - - private class TestClass { + @Test + public void testCloneInt() { + assertNull(ArrayUtils.clone((int[]) null)); + final int[] original = new int[]{5, 8}; + final int[] cloned = ArrayUtils.clone(original); + assertArrayEquals(original, cloned); + assertNotSame(original, cloned); } @Test - public void testNullToEmptyGenericNull() { - final TestClass[] output = ArrayUtils.nullToEmpty(null, TestClass[].class); - - assertNotNull(output); - assertEquals(0, output.length); + public void testCloneLong() { + assertNull(ArrayUtils.clone((long[]) null)); + final long[] original = new long[]{0L, 1L}; + final long[] cloned = ArrayUtils.clone(original); + assertArrayEquals(original, cloned); + assertNotSame(original, cloned); } @Test - public void testNullToEmptyGenericEmpty() { - final TestClass[] input = new TestClass[]{}; - final TestClass[] output = ArrayUtils.nullToEmpty(input, TestClass[].class); - - assertSame(input, output); - } - - @Test - public void testNullToEmptyGeneric() { - final TestClass[] input = new TestClass[]{new TestClass(), new TestClass()}; - final TestClass[] output = ArrayUtils.nullToEmpty(input, TestClass[].class); - - assertSame(input, output); + public void testCloneShort() { + assertNull(ArrayUtils.clone((short[]) null)); + final short[] original = new short[]{1, 4}; + final short[] cloned = ArrayUtils.clone(original); + assertArrayEquals(original, cloned); + assertNotSame(original, cloned); } + //----------------------------------------------------------------------- @Test - public void testNullToEmptyGenericNullType() { - final TestClass[] input = new TestClass[]{}; - assertThrows(IllegalArgumentException.class, () -> ArrayUtils.nullToEmpty(input, null)); + public void testConstructor() { + assertNotNull(new ArrayUtils()); + final Constructor[] cons = ArrayUtils.class.getDeclaredConstructors(); + assertEquals(1, cons.length); + assertTrue(Modifier.isPublic(cons[0].getModifiers())); + assertTrue(Modifier.isPublic(ArrayUtils.class.getModifiers())); + assertFalse(Modifier.isFinal(ArrayUtils.class.getModifiers())); } @Test - public void testNullToEmptyBooleanNull() { - assertEquals(ArrayUtils.EMPTY_BOOLEAN_ARRAY, ArrayUtils.nullToEmpty((boolean[]) null)); + public void testContains() { + final Object[] array = new Object[]{"0", "1", "2", "3", null, "0"}; + assertFalse(ArrayUtils.contains(null, null)); + assertFalse(ArrayUtils.contains(null, "1")); + assertTrue(ArrayUtils.contains(array, "0")); + assertTrue(ArrayUtils.contains(array, "1")); + assertTrue(ArrayUtils.contains(array, "2")); + assertTrue(ArrayUtils.contains(array, "3")); + assertTrue(ArrayUtils.contains(array, null)); + assertFalse(ArrayUtils.contains(array, "notInArray")); } @Test - public void testNullToEmptyBooleanEmptyArray() { - final boolean[] empty = new boolean[]{}; - final boolean[] result = ArrayUtils.nullToEmpty(empty); - assertEquals(ArrayUtils.EMPTY_BOOLEAN_ARRAY, result); - assertNotSame(empty, result); - } + public void testContains_LANG_1261() { + class LANG1261ParentObject { + @Override + public boolean equals(final Object o) { + return true; + } + } + class LANG1261ChildObject extends LANG1261ParentObject { + } - @Test - public void testNullToEmptyBoolean() { - final boolean[] original = new boolean[]{true, false}; - assertEquals(original, ArrayUtils.nullToEmpty(original)); - } + final Object[] array = new LANG1261ChildObject[]{new LANG1261ChildObject()}; - @Test - public void testNullToEmptyLongNull() { - assertEquals(ArrayUtils.EMPTY_LONG_ARRAY, ArrayUtils.nullToEmpty((long[]) null)); + assertTrue(ArrayUtils.contains(array, new LANG1261ParentObject())); } @Test - public void testNullToEmptyLongEmptyArray() { - final long[] empty = new long[]{}; - final long[] result = ArrayUtils.nullToEmpty(empty); - assertEquals(ArrayUtils.EMPTY_LONG_ARRAY, result); - assertNotSame(empty, result); + public void testContainsBoolean() { + boolean[] array = null; + assertFalse(ArrayUtils.contains(array, true)); + array = new boolean[]{true, false, true}; + assertTrue(ArrayUtils.contains(array, true)); + assertTrue(ArrayUtils.contains(array, false)); + array = new boolean[]{true, true}; + assertTrue(ArrayUtils.contains(array, true)); + assertFalse(ArrayUtils.contains(array, false)); } @Test - public void testNullToEmptyLong() { - final long[] original = new long[]{1L, 2L}; - assertEquals(original, ArrayUtils.nullToEmpty(original)); + public void testContainsByte() { + byte[] array = null; + assertFalse(ArrayUtils.contains(array, (byte) 1)); + array = new byte[]{0, 1, 2, 3, 0}; + assertTrue(ArrayUtils.contains(array, (byte) 0)); + assertTrue(ArrayUtils.contains(array, (byte) 1)); + assertTrue(ArrayUtils.contains(array, (byte) 2)); + assertTrue(ArrayUtils.contains(array, (byte) 3)); + assertFalse(ArrayUtils.contains(array, (byte) 99)); } @Test - public void testNullToEmptyIntNull() { - assertEquals(ArrayUtils.EMPTY_INT_ARRAY, ArrayUtils.nullToEmpty((int[]) null)); + public void testContainsChar() { + char[] array = null; + assertFalse(ArrayUtils.contains(array, 'b')); + array = new char[]{'a', 'b', 'c', 'd', 'a'}; + assertTrue(ArrayUtils.contains(array, 'a')); + assertTrue(ArrayUtils.contains(array, 'b')); + assertTrue(ArrayUtils.contains(array, 'c')); + assertTrue(ArrayUtils.contains(array, 'd')); + assertFalse(ArrayUtils.contains(array, 'e')); } + @SuppressWarnings("cast") @Test - public void testNullToEmptyIntEmptyArray() { - final int[] empty = new int[]{}; - final int[] result = ArrayUtils.nullToEmpty(empty); - assertEquals(ArrayUtils.EMPTY_INT_ARRAY, result); - assertNotSame(empty, result); + public void testContainsDouble() { + double[] array = null; + assertFalse(ArrayUtils.contains(array, (double) 1)); + array = new double[]{0, 1, 2, 3, 0}; + assertTrue(ArrayUtils.contains(array, (double) 0)); + assertTrue(ArrayUtils.contains(array, (double) 1)); + assertTrue(ArrayUtils.contains(array, (double) 2)); + assertTrue(ArrayUtils.contains(array, (double) 3)); + assertFalse(ArrayUtils.contains(array, (double) 99)); } - @Test - public void testNullToEmptyInt() { - final int[] original = new int[]{1, 2}; - assertEquals(original, ArrayUtils.nullToEmpty(original)); - } + //----------------------------------------------------------------------- + @SuppressWarnings("cast") @Test - public void testNullToEmptyShortNull() { - assertEquals(ArrayUtils.EMPTY_SHORT_ARRAY, ArrayUtils.nullToEmpty((short[]) null)); + public void testContainsDoubleTolerance() { + double[] array = null; + assertFalse(ArrayUtils.contains(array, (double) 1, (double) 0)); + array = new double[]{0, 1, 2, 3, 0}; + assertFalse(ArrayUtils.contains(array, 4.0, 0.33)); + assertFalse(ArrayUtils.contains(array, 2.5, 0.49)); + assertTrue(ArrayUtils.contains(array, 2.5, 0.50)); + assertTrue(ArrayUtils.contains(array, 2.5, 0.51)); } + @SuppressWarnings("cast") @Test - public void testNullToEmptyShortEmptyArray() { - final short[] empty = new short[]{}; - final short[] result = ArrayUtils.nullToEmpty(empty); - assertEquals(ArrayUtils.EMPTY_SHORT_ARRAY, result); - assertNotSame(empty, result); + public void testContainsFloat() { + float[] array = null; + assertFalse(ArrayUtils.contains(array, (float) 1)); + array = new float[]{0, 1, 2, 3, 0}; + assertTrue(ArrayUtils.contains(array, (float) 0)); + assertTrue(ArrayUtils.contains(array, (float) 1)); + assertTrue(ArrayUtils.contains(array, (float) 2)); + assertTrue(ArrayUtils.contains(array, (float) 3)); + assertFalse(ArrayUtils.contains(array, (float) 99)); } @Test - public void testNullToEmptyShort() { - final short[] original = new short[]{1, 2}; - assertEquals(original, ArrayUtils.nullToEmpty(original)); + public void testContainsInt() { + int[] array = null; + assertFalse(ArrayUtils.contains(array, 1)); + array = new int[]{0, 1, 2, 3, 0}; + assertTrue(ArrayUtils.contains(array, 0)); + assertTrue(ArrayUtils.contains(array, 1)); + assertTrue(ArrayUtils.contains(array, 2)); + assertTrue(ArrayUtils.contains(array, 3)); + assertFalse(ArrayUtils.contains(array, 99)); } @Test - public void testNullToEmptyCharNull() { - assertEquals(ArrayUtils.EMPTY_CHAR_ARRAY, ArrayUtils.nullToEmpty((char[]) null)); + public void testContainsLong() { + long[] array = null; + assertFalse(ArrayUtils.contains(array, 1)); + array = new long[]{0, 1, 2, 3, 0}; + assertTrue(ArrayUtils.contains(array, 0)); + assertTrue(ArrayUtils.contains(array, 1)); + assertTrue(ArrayUtils.contains(array, 2)); + assertTrue(ArrayUtils.contains(array, 3)); + assertFalse(ArrayUtils.contains(array, 99)); } @Test - public void testNullToEmptyCharEmptyArray() { - final char[] empty = new char[]{}; - final char[] result = ArrayUtils.nullToEmpty(empty); - assertEquals(ArrayUtils.EMPTY_CHAR_ARRAY, result); - assertNotSame(empty, result); + public void testContainsShort() { + short[] array = null; + assertFalse(ArrayUtils.contains(array, (short) 1)); + array = new short[]{0, 1, 2, 3, 0}; + assertTrue(ArrayUtils.contains(array, (short) 0)); + assertTrue(ArrayUtils.contains(array, (short) 1)); + assertTrue(ArrayUtils.contains(array, (short) 2)); + assertTrue(ArrayUtils.contains(array, (short) 3)); + assertFalse(ArrayUtils.contains(array, (short) 99)); } @Test - public void testNullToEmptyChar() { - final char[] original = new char[]{'a', 'b'}; - assertEquals(original, ArrayUtils.nullToEmpty(original)); + public void testCreatePrimitiveArray() { + assertNull(ArrayUtils.toPrimitive((Object[]) null)); + assertArrayEquals(new int[]{}, ArrayUtils.toPrimitive(new Integer[]{})); + assertArrayEquals(new short[]{2}, ArrayUtils.toPrimitive(new Short[]{2})); + assertArrayEquals(new long[]{2, 3}, ArrayUtils.toPrimitive(new Long[]{2L, 3L})); + assertArrayEquals(new float[]{3.14f}, ArrayUtils.toPrimitive(new Float[]{3.14f}), 0.1f); + assertArrayEquals(new double[]{2.718}, ArrayUtils.toPrimitive(new Double[]{2.718}), 0.1); } + /** + * Tests generic empty array creation with generic type. + */ @Test - public void testNullToEmptyByteNull() { - assertEquals(ArrayUtils.EMPTY_BYTE_ARRAY, ArrayUtils.nullToEmpty((byte[]) null)); + public void testEmptyArrayCreation() { + final String[] array = ArrayUtils.toArray(); + assertEquals(0, array.length); } + // ------------------------------------------------------------------------ @Test - public void testNullToEmptyByteEmptyArray() { - final byte[] empty = new byte[]{}; - final byte[] result = ArrayUtils.nullToEmpty(empty); - assertEquals(ArrayUtils.EMPTY_BYTE_ARRAY, result); - assertNotSame(empty, result); - } + public void testGetLength() { + assertEquals(0, ArrayUtils.getLength(null)); - @Test - public void testNullToEmptyByte() { - final byte[] original = new byte[]{0x0F, 0x0E}; - assertEquals(original, ArrayUtils.nullToEmpty(original)); - } + final Object[] emptyObjectArray = new Object[0]; + final Object[] notEmptyObjectArray = new Object[]{"aValue"}; + assertEquals(0, ArrayUtils.getLength(null)); + assertEquals(0, ArrayUtils.getLength(emptyObjectArray)); + assertEquals(1, ArrayUtils.getLength(notEmptyObjectArray)); - @Test - public void testNullToEmptyDoubleNull() { - assertEquals(ArrayUtils.EMPTY_DOUBLE_ARRAY, ArrayUtils.nullToEmpty((double[]) null)); - } + final int[] emptyIntArray = new int[]{}; + final int[] notEmptyIntArray = new int[]{1}; + assertEquals(0, ArrayUtils.getLength(null)); + assertEquals(0, ArrayUtils.getLength(emptyIntArray)); + assertEquals(1, ArrayUtils.getLength(notEmptyIntArray)); - @Test - public void testNullToEmptyDoubleEmptyArray() { - final double[] empty = new double[]{}; - final double[] result = ArrayUtils.nullToEmpty(empty); - assertEquals(ArrayUtils.EMPTY_DOUBLE_ARRAY, result); - assertNotSame(empty, result); - } + final short[] emptyShortArray = new short[]{}; + final short[] notEmptyShortArray = new short[]{1}; + assertEquals(0, ArrayUtils.getLength(null)); + assertEquals(0, ArrayUtils.getLength(emptyShortArray)); + assertEquals(1, ArrayUtils.getLength(notEmptyShortArray)); - @Test - public void testNullToEmptyDouble() { - final double[] original = new double[]{1L, 2L}; - assertEquals(original, ArrayUtils.nullToEmpty(original)); - } + final char[] emptyCharArray = new char[]{}; + final char[] notEmptyCharArray = new char[]{1}; + assertEquals(0, ArrayUtils.getLength(null)); + assertEquals(0, ArrayUtils.getLength(emptyCharArray)); + assertEquals(1, ArrayUtils.getLength(notEmptyCharArray)); - @Test - public void testNullToEmptyFloatNull() { - assertEquals(ArrayUtils.EMPTY_FLOAT_ARRAY, ArrayUtils.nullToEmpty((float[]) null)); - } + final byte[] emptyByteArray = new byte[]{}; + final byte[] notEmptyByteArray = new byte[]{1}; + assertEquals(0, ArrayUtils.getLength(null)); + assertEquals(0, ArrayUtils.getLength(emptyByteArray)); + assertEquals(1, ArrayUtils.getLength(notEmptyByteArray)); - @Test - public void testNullToEmptyFloatEmptyArray() { - final float[] empty = new float[]{}; - final float[] result = ArrayUtils.nullToEmpty(empty); - assertEquals(ArrayUtils.EMPTY_FLOAT_ARRAY, result); - assertNotSame(empty, result); - } + final double[] emptyDoubleArray = new double[]{}; + final double[] notEmptyDoubleArray = new double[]{1.0}; + assertEquals(0, ArrayUtils.getLength(null)); + assertEquals(0, ArrayUtils.getLength(emptyDoubleArray)); + assertEquals(1, ArrayUtils.getLength(notEmptyDoubleArray)); - @Test - public void testNullToEmptyFloat() { - final float[] original = new float[]{2.6f, 3.8f}; - assertEquals(original, ArrayUtils.nullToEmpty(original)); - } + final float[] emptyFloatArray = new float[]{}; + final float[] notEmptyFloatArray = new float[]{1.0F}; + assertEquals(0, ArrayUtils.getLength(null)); + assertEquals(0, ArrayUtils.getLength(emptyFloatArray)); + assertEquals(1, ArrayUtils.getLength(notEmptyFloatArray)); - @Test - public void testNullToEmptyObjectNull() { - assertArrayEquals(ArrayUtils.EMPTY_OBJECT_ARRAY, ArrayUtils.nullToEmpty((Object[]) null)); - } + final boolean[] emptyBooleanArray = new boolean[]{}; + final boolean[] notEmptyBooleanArray = new boolean[]{true}; + assertEquals(0, ArrayUtils.getLength(null)); + assertEquals(0, ArrayUtils.getLength(emptyBooleanArray)); + assertEquals(1, ArrayUtils.getLength(notEmptyBooleanArray)); - @Test - public void testNullToEmptyObjectEmptyArray() { - final Object[] empty = new Object[]{}; - final Object[] result = ArrayUtils.nullToEmpty(empty); - assertArrayEquals(ArrayUtils.EMPTY_OBJECT_ARRAY, result); - assertNotSame(empty, result); + assertThrows(IllegalArgumentException.class, () -> ArrayUtils.getLength("notAnArray")); } + //----------------------------------------------------------------------- @Test - public void testNullToEmptyObject() { - final Object[] original = new Object[]{Boolean.TRUE, Boolean.FALSE}; - assertArrayEquals(original, ArrayUtils.nullToEmpty(original)); - } + public void testHashCode() { + final long[][] array1 = new long[][]{{2, 5}, {4, 5}}; + final long[][] array2 = new long[][]{{2, 5}, {4, 6}}; + assertEquals(ArrayUtils.hashCode(array1), ArrayUtils.hashCode(array1)); + assertNotEquals(ArrayUtils.hashCode(array1), ArrayUtils.hashCode(array2)); - @Test - public void testNullToEmptyClassNull() { - assertArrayEquals(ArrayUtils.EMPTY_CLASS_ARRAY, ArrayUtils.nullToEmpty((Class[]) null)); - } + final Object[] array3 = new Object[]{new String(new char[]{'A', 'B'})}; + final Object[] array4 = new Object[]{"AB"}; + assertEquals(ArrayUtils.hashCode(array3), ArrayUtils.hashCode(array3)); + assertEquals(ArrayUtils.hashCode(array3), ArrayUtils.hashCode(array4)); - @Test - public void testNullToEmptyClassEmptyArray() { - final Class[] empty = {}; - final Class[] result = ArrayUtils.nullToEmpty(empty); - assertArrayEquals(ArrayUtils.EMPTY_CLASS_ARRAY, result); - assertNotSame(empty, result); + final Object[] arrayA = new Object[]{new boolean[]{true, false}, new int[]{6, 7}}; + final Object[] arrayB = new Object[]{new boolean[]{true, false}, new int[]{6, 7}}; + assertEquals(ArrayUtils.hashCode(arrayB), ArrayUtils.hashCode(arrayA)); } @Test - public void testNullToEmptyClass() { - final Class[] original = {Object.class, String.class}; - assertArrayEquals(original, ArrayUtils.nullToEmpty(original)); + public void testIndexesOf() { + final Object[] array = new Object[]{"0", "1", "2", "3", null, "0"}; + final BitSet emptySet = new BitSet(); + final BitSet testSet = new BitSet(); + assertEquals(emptySet, ArrayUtils.indexesOf((Object[]) null, null)); + assertEquals(emptySet, ArrayUtils.indexesOf(new Object[0], "0")); + testSet.set(5); + testSet.set(0); + assertEquals(testSet, ArrayUtils.indexesOf(array, "0")); + testSet.clear(); + testSet.set(2); + assertEquals(testSet, ArrayUtils.indexesOf(array, "2")); + testSet.clear(); + testSet.set(3); + assertEquals(testSet, ArrayUtils.indexesOf(array, "3")); + testSet.clear(); + testSet.set(4); + assertEquals(testSet, ArrayUtils.indexesOf(array, null)); + assertEquals(emptySet, ArrayUtils.indexesOf(array, "notInArray")); } @Test - public void testNullToEmptyStringNull() { - assertArrayEquals(ArrayUtils.EMPTY_STRING_ARRAY, ArrayUtils.nullToEmpty((String[]) null)); + public void testIndexesOfBoolean() { + boolean[] array = null; + final BitSet emptySet = new BitSet(); + final BitSet testSet = new BitSet(); + assertEquals(emptySet, ArrayUtils.indexesOf(array, true)); + array = new boolean[0]; + assertEquals(emptySet, ArrayUtils.indexesOf(array, true)); + array = new boolean[]{true, false, true}; + testSet.set(0); + testSet.set(2); + assertEquals(testSet, ArrayUtils.indexesOf(array, true)); + testSet.clear(); + testSet.set(1); + assertEquals(testSet, ArrayUtils.indexesOf(array, false)); + array = new boolean[]{true, true}; + assertEquals(emptySet, ArrayUtils.indexesOf(array, false)); } @Test - public void testNullToEmptyStringEmptyArray() { - final String[] empty = new String[]{}; - final String[] result = ArrayUtils.nullToEmpty(empty); - assertArrayEquals(ArrayUtils.EMPTY_STRING_ARRAY, result); - assertNotSame(empty, result); + public void testIndexesOfBooleanWithStartIndex() { + boolean[] array = null; + final BitSet emptySet = new BitSet(); + final BitSet testSet = new BitSet(); + assertEquals(emptySet, ArrayUtils.indexesOf(array, true, 0)); + array = new boolean[0]; + assertEquals(emptySet, ArrayUtils.indexesOf(array, true, 0)); + array = new boolean[]{true, false, true}; + testSet.set(2); + assertEquals(testSet, ArrayUtils.indexesOf(array, true, 1)); + testSet.set(0); + assertEquals(testSet, ArrayUtils.indexesOf(array, true, 0)); + testSet.clear(); + testSet.set(1); + assertEquals(testSet, ArrayUtils.indexesOf(array, false, 1)); + array = new boolean[]{true, true}; + assertEquals(emptySet, ArrayUtils.indexesOf(array, false, 0)); + assertEquals(emptySet, ArrayUtils.indexesOf(array, false, -1)); } @Test - public void testNullToEmptyString() { - final String[] original = new String[]{"abc", "def"}; - assertArrayEquals(original, ArrayUtils.nullToEmpty(original)); + public void testIndexesOfByte() { + byte[] array = null; + final BitSet emptySet = new BitSet(); + final BitSet testSet = new BitSet(); + assertEquals(emptySet, ArrayUtils.indexesOf(array, (byte) 0)); + array = new byte[]{0, 1, 2, 3, 0}; + testSet.set(0); + testSet.set(4); + assertEquals(testSet, ArrayUtils.indexesOf(array, (byte) 0)); + testSet.clear(); + testSet.set(1); + assertEquals(testSet, ArrayUtils.indexesOf(array, (byte) 1)); + testSet.clear(); + testSet.set(2); + assertEquals(testSet, ArrayUtils.indexesOf(array, (byte) 2)); + testSet.clear(); + testSet.set(3); + assertEquals(testSet, ArrayUtils.indexesOf(array, (byte) 3)); + assertEquals(emptySet, ArrayUtils.indexesOf(array, (byte) 99)); } @Test - public void testNullToEmptyBooleanObjectNull() { - assertArrayEquals(ArrayUtils.EMPTY_BOOLEAN_OBJECT_ARRAY, ArrayUtils.nullToEmpty((Boolean[]) null)); + public void testIndexesOfByteWithStartIndex() { + byte[] array = null; + final BitSet emptySet = new BitSet(); + final BitSet testSet = new BitSet(); + assertEquals(emptySet, ArrayUtils.indexesOf(array, (byte) 0, 2)); + array = new byte[]{0, 1, 2, 3, 0}; + testSet.set(4); + assertEquals(testSet, ArrayUtils.indexesOf(array, (byte) 0, 2)); + testSet.set(0); + assertEquals(testSet, ArrayUtils.indexesOf(array, (byte) 0, 0)); + testSet.clear(); + testSet.set(1); + assertEquals(testSet, ArrayUtils.indexesOf(array, (byte) 1, 1)); + testSet.clear(); + testSet.set(2); + assertEquals(testSet, ArrayUtils.indexesOf(array, (byte) 2, 0)); + testSet.clear(); + testSet.set(3); + assertEquals(testSet, ArrayUtils.indexesOf(array, (byte) 3, 0)); + assertEquals(testSet, ArrayUtils.indexesOf(array, (byte) 3, -1)); + assertEquals(emptySet, ArrayUtils.indexesOf(array, (byte) 99, 0)); } @Test - public void testNullToEmptyBooleanObjectEmptyArray() { - final Boolean[] empty = new Boolean[]{}; - final Boolean[] result = ArrayUtils.nullToEmpty(empty); - assertArrayEquals(ArrayUtils.EMPTY_BOOLEAN_OBJECT_ARRAY, result); - assertNotSame(empty, result); + public void testIndexesOfChar() { + char[] array = null; + final BitSet emptySet = new BitSet(); + final BitSet testSet = new BitSet(); + assertEquals(emptySet, ArrayUtils.indexesOf(array, 'a')); + array = new char[]{'a', 'b', 'c', 'd', 'a'}; + testSet.set(0); + testSet.set(4); + assertEquals(testSet, ArrayUtils.indexesOf(array, 'a')); + testSet.clear(); + testSet.set(1); + assertEquals(testSet, ArrayUtils.indexesOf(array, 'b')); + testSet.clear(); + testSet.set(2); + assertEquals(testSet, ArrayUtils.indexesOf(array, 'c')); + testSet.clear(); + testSet.set(3); + assertEquals(testSet, ArrayUtils.indexesOf(array, 'd')); + assertEquals(emptySet, ArrayUtils.indexesOf(array, 'e')); } @Test - public void testNullToEmptyBooleanObject() { - final Boolean[] original = new Boolean[]{Boolean.TRUE, Boolean.FALSE}; - assertArrayEquals(original, ArrayUtils.nullToEmpty(original)); + public void testIndexesOfCharWithStartIndex() { + char[] array = null; + final BitSet emptySet = new BitSet(); + final BitSet testSet = new BitSet(); + assertEquals(emptySet, ArrayUtils.indexesOf(array, 'a', 0)); + array = new char[]{'a', 'b', 'c', 'd', 'a'}; + testSet.set(4); + assertEquals(testSet, ArrayUtils.indexesOf(array, 'a', 2)); + testSet.set(0); + assertEquals(testSet, ArrayUtils.indexesOf(array, 'a', 0)); + assertEquals(testSet, ArrayUtils.indexesOf(array, 'a', -1)); + testSet.clear(); + testSet.set(1); + assertEquals(testSet, ArrayUtils.indexesOf(array, 'b', 1)); + testSet.clear(); + testSet.set(2); + assertEquals(testSet, ArrayUtils.indexesOf(array, 'c', 0)); + testSet.clear(); + testSet.set(3); + assertEquals(testSet, ArrayUtils.indexesOf(array, 'd', 0)); + assertEquals(emptySet, ArrayUtils.indexesOf(array, 'd', 5)); + assertEquals(emptySet, ArrayUtils.indexesOf(array, 'e', 0)); } + @SuppressWarnings("cast") @Test - public void testNullToEmptyLongObjectNull() { - assertArrayEquals(ArrayUtils.EMPTY_LONG_OBJECT_ARRAY, ArrayUtils.nullToEmpty((Long[]) null)); + public void testIndexesOfDouble() { + double[] array = null; + final BitSet emptySet = new BitSet(); + final BitSet testSet = new BitSet(); + assertEquals(emptySet, ArrayUtils.indexesOf(array, 0)); + array = new double[]{0, 1, 2, 3, 0}; + testSet.set(0); + testSet.set(4); + assertEquals(testSet, ArrayUtils.indexesOf(array, 0)); + testSet.clear(); + testSet.set(1); + assertEquals(testSet, ArrayUtils.indexesOf(array, 1)); + testSet.clear(); + testSet.set(2); + assertEquals(testSet, ArrayUtils.indexesOf(array, 2)); + testSet.clear(); + testSet.set(3); + assertEquals(testSet, ArrayUtils.indexesOf(array, 3)); + assertEquals(emptySet, ArrayUtils.indexesOf(array, 99)); } + @SuppressWarnings("cast") @Test - public void testNullToEmptyLongObjectEmptyArray() { - final Long[] empty = new Long[]{}; - final Long[] result = ArrayUtils.nullToEmpty(empty); - assertArrayEquals(ArrayUtils.EMPTY_LONG_OBJECT_ARRAY, result); - assertNotSame(empty, result); - } - - @Test - public void testNullToEmptyLongObject() { - @SuppressWarnings("boxing") final Long[] original = new Long[]{1L, 2L}; - assertArrayEquals(original, ArrayUtils.nullToEmpty(original)); - } - - @Test - public void testNullToEmptyIntObjectNull() { - assertArrayEquals(ArrayUtils.EMPTY_INTEGER_OBJECT_ARRAY, ArrayUtils.nullToEmpty((Integer[]) null)); + public void testIndexesOfDoubleTolerance() { + double[] array = null; + final BitSet emptySet = new BitSet(); + final BitSet testSet = new BitSet(); + assertEquals(emptySet, ArrayUtils.indexesOf(array, (double) 0, (double) 0)); + array = new double[0]; + assertEquals(emptySet, ArrayUtils.indexesOf(array, (double) 0, (double) 0)); + array = new double[]{0, 1, 2, 3, 0}; + testSet.set(0); + testSet.set(4); + assertEquals(testSet, ArrayUtils.indexesOf(array, (double) 0, 0.3)); + testSet.clear(); + testSet.set(3); + assertEquals(testSet, ArrayUtils.indexesOf(array, 4.15, 2.0)); + testSet.clear(); + testSet.set(1); + assertEquals(testSet, ArrayUtils.indexesOf(array, 1.00001324, 0.0001)); } + @SuppressWarnings("cast") @Test - public void testNullToEmptyIntObjectEmptyArray() { - final Integer[] empty = new Integer[]{}; - final Integer[] result = ArrayUtils.nullToEmpty(empty); - assertArrayEquals(ArrayUtils.EMPTY_INTEGER_OBJECT_ARRAY, result); - assertNotSame(empty, result); + public void testIndexesOfDoubleWithStartIndex() { + double[] array = null; + final BitSet emptySet = new BitSet(); + final BitSet testSet = new BitSet(); + assertEquals(emptySet, ArrayUtils.indexesOf(array, 0, 2)); + array = new double[]{0, 1, 2, 3, 0}; + testSet.set(4); + assertEquals(testSet, ArrayUtils.indexesOf(array, 0, 2)); + testSet.set(0); + assertEquals(testSet, ArrayUtils.indexesOf(array, 0, 0)); + testSet.clear(); + testSet.set(1); + assertEquals(testSet, ArrayUtils.indexesOf(array, 1, 1)); + testSet.clear(); + testSet.set(2); + assertEquals(testSet, ArrayUtils.indexesOf(array, 2, 0)); + testSet.clear(); + testSet.set(3); + assertEquals(testSet, ArrayUtils.indexesOf(array, 3, 0)); + assertEquals(testSet, ArrayUtils.indexesOf(array, 3, -1)); + assertEquals(emptySet, ArrayUtils.indexesOf(array, 99, 0)); } + @SuppressWarnings("cast") @Test - public void testNullToEmptyIntObject() { - final Integer[] original = new Integer[]{1, 2}; - assertArrayEquals(original, ArrayUtils.nullToEmpty(original)); + public void testIndexesOfDoubleWithStartIndexTolerance() { + double[] array = null; + final BitSet emptySet = new BitSet(); + final BitSet testSet = new BitSet(); + assertEquals(emptySet, ArrayUtils.indexesOf(array, (double) 0, 0, (double) 0)); + array = new double[0]; + assertEquals(emptySet, ArrayUtils.indexesOf(array, (double) 0, 0, (double) 0)); + array = new double[]{0, 1, 2, 3, 0}; + testSet.set(4); + assertEquals(testSet, ArrayUtils.indexesOf(array, (double) 0, 1, 0.3)); + testSet.set(0); + assertEquals(testSet, ArrayUtils.indexesOf(array, (double) 0, 0, 0.3)); + testSet.clear(); + testSet.set(2); + assertEquals(testSet, ArrayUtils.indexesOf(array, 2, 0, 0.35)); + assertEquals(testSet, ArrayUtils.indexesOf(array, 2, 2, 0.35)); + assertEquals(testSet, ArrayUtils.indexesOf(array, 2, -1, 0.35)); + assertEquals(emptySet, ArrayUtils.indexesOf(array, 2, 3, 0.35)); + testSet.clear(); + testSet.set(3); + assertEquals(testSet, ArrayUtils.indexesOf(array, 4.15, 0, 2.0)); + testSet.clear(); + testSet.set(1); + assertEquals(testSet, ArrayUtils.indexesOf(array, 1.00001324, 0, 0.0001)); } + @SuppressWarnings("cast") @Test - public void testNullToEmptyShortObjectNull() { - assertArrayEquals(ArrayUtils.EMPTY_SHORT_OBJECT_ARRAY, ArrayUtils.nullToEmpty((Short[]) null)); + public void testIndexesOfFloat() { + float[] array = null; + final BitSet emptySet = new BitSet(); + final BitSet testSet = new BitSet(); + assertEquals(emptySet, ArrayUtils.indexesOf(array, 0)); + array = new float[]{0, 1, 2, 3, 0}; + testSet.set(0); + testSet.set(4); + assertEquals(testSet, ArrayUtils.indexesOf(array, 0)); + testSet.clear(); + testSet.set(1); + assertEquals(testSet, ArrayUtils.indexesOf(array, 1)); + testSet.clear(); + testSet.set(2); + assertEquals(testSet, ArrayUtils.indexesOf(array, 2)); + testSet.clear(); + testSet.set(3); + assertEquals(testSet, ArrayUtils.indexesOf(array, 3)); + assertEquals(emptySet, ArrayUtils.indexesOf(array, 99)); } + @SuppressWarnings("cast") @Test - public void testNullToEmptyShortObjectEmptyArray() { - final Short[] empty = new Short[]{}; - final Short[] result = ArrayUtils.nullToEmpty(empty); - assertArrayEquals(ArrayUtils.EMPTY_SHORT_OBJECT_ARRAY, result); - assertNotSame(empty, result); + public void testIndexesOfFloatWithStartIndex() { + float[] array = null; + final BitSet emptySet = new BitSet(); + final BitSet testSet = new BitSet(); + assertEquals(emptySet, ArrayUtils.indexesOf(array, 0, 2)); + array = new float[]{0, 1, 2, 3, 0}; + testSet.set(4); + assertEquals(testSet, ArrayUtils.indexesOf(array, 0, 2)); + testSet.set(0); + assertEquals(testSet, ArrayUtils.indexesOf(array, 0, 0)); + testSet.clear(); + testSet.set(1); + assertEquals(testSet, ArrayUtils.indexesOf(array, 1, 1)); + testSet.clear(); + testSet.set(2); + assertEquals(testSet, ArrayUtils.indexesOf(array, 2, 0)); + testSet.clear(); + testSet.set(3); + assertEquals(testSet, ArrayUtils.indexesOf(array, 3, 0)); + assertEquals(testSet, ArrayUtils.indexesOf(array, 3, -1)); + assertEquals(emptySet, ArrayUtils.indexesOf(array, 99, 0)); } @Test - public void testNullToEmptyShortObject() { - @SuppressWarnings("boxing") final Short[] original = new Short[]{1, 2}; - assertArrayEquals(original, ArrayUtils.nullToEmpty(original)); + public void testIndexesOfIntWithStartIndex() { + int[] array = null; + final BitSet emptySet = new BitSet(); + final BitSet testSet = new BitSet(); + assertEquals(emptySet, ArrayUtils.indexesOf(array, 0, 2)); + array = new int[]{0, 1, 2, 3, 0}; + testSet.set(4); + assertEquals(testSet, ArrayUtils.indexesOf(array, 0, 2)); + testSet.set(0); + assertEquals(testSet, ArrayUtils.indexesOf(array, 0, 0)); + testSet.clear(); + testSet.set(1); + assertEquals(testSet, ArrayUtils.indexesOf(array, 1, 1)); + testSet.clear(); + testSet.set(2); + assertEquals(testSet, ArrayUtils.indexesOf(array, 2, 0)); + testSet.clear(); + testSet.set(3); + assertEquals(testSet, ArrayUtils.indexesOf(array, 3, 0)); + assertEquals(testSet, ArrayUtils.indexesOf(array, 3, -1)); + assertEquals(emptySet, ArrayUtils.indexesOf(array, 99, 0)); } @Test - public void testNUllToEmptyCharObjectNull() { - assertArrayEquals(ArrayUtils.EMPTY_CHARACTER_OBJECT_ARRAY, ArrayUtils.nullToEmpty((Character[]) null)); + public void testIndexesOfLong() { + final long[] array = new long[]{0, 1, 2, 3}; + final BitSet emptySet = new BitSet(); + final BitSet testSet = new BitSet(); + assertEquals(emptySet, ArrayUtils.indexesOf((long[]) null, 0)); + assertEquals(emptySet, ArrayUtils.indexesOf(array, 4)); + testSet.set(0); + assertEquals(testSet, ArrayUtils.indexesOf(array, 0)); + testSet.clear(); + testSet.set(1); + assertEquals(testSet, ArrayUtils.indexesOf(array, 1)); + testSet.clear(); + testSet.set(2); + assertEquals(testSet, ArrayUtils.indexesOf(array, 2)); + testSet.clear(); + testSet.set(3); + assertEquals(testSet, ArrayUtils.indexesOf(array, 3)); } @Test - public void testNullToEmptyCharObjectEmptyArray() { - final Character[] empty = new Character[]{}; - final Character[] result = ArrayUtils.nullToEmpty(empty); - assertArrayEquals(ArrayUtils.EMPTY_CHARACTER_OBJECT_ARRAY, result); - assertNotSame(empty, result); + public void testIndexesOfLongWithStartIndex() { + final long[] array = new long[]{0, 1, 2, 3, 2, 1, 0, 1}; + final BitSet emptySet = new BitSet(); + final BitSet testSet = new BitSet(); + assertEquals(emptySet, ArrayUtils.indexesOf((long[]) null, 0, 0)); + assertEquals(emptySet, ArrayUtils.indexesOf(array, 4, 0)); + testSet.set(6); + assertEquals(testSet, ArrayUtils.indexesOf(array, 0, 1)); + testSet.set(0); + assertEquals(testSet, ArrayUtils.indexesOf(array, 0, 0)); + testSet.clear(); + testSet.set(1); + testSet.set(5); + testSet.set(7); + assertEquals(testSet, ArrayUtils.indexesOf(array, 1, 0)); + testSet.clear(); + testSet.set(2); + testSet.set(4); + assertEquals(testSet, ArrayUtils.indexesOf(array, 2, 0)); + testSet.clear(); + testSet.set(3); + assertEquals(testSet, ArrayUtils.indexesOf(array, 3, 0)); + assertEquals(emptySet, ArrayUtils.indexesOf(array, 3, 8)); } @Test - public void testNullToEmptyCharObject() { - final Character[] original = new Character[]{'a', 'b'}; - assertArrayEquals(original, ArrayUtils.nullToEmpty(original)); + public void testIndexesOfShort() { + short[] array = null; + final BitSet emptySet = new BitSet(); + final BitSet testSet = new BitSet(); + assertEquals(emptySet, ArrayUtils.indexesOf(array, (short) 0)); + array = new short[]{0, 1, 2, 3, 0}; + testSet.set(0); + testSet.set(4); + assertEquals(testSet, ArrayUtils.indexesOf(array, (short) 0)); + testSet.clear(); + testSet.set(1); + assertEquals(testSet, ArrayUtils.indexesOf(array, (short) 1)); + testSet.clear(); + testSet.set(2); + assertEquals(testSet, ArrayUtils.indexesOf(array, (short) 2)); + testSet.clear(); + testSet.set(3); + assertEquals(testSet, ArrayUtils.indexesOf(array, (short) 3)); + assertEquals(emptySet, ArrayUtils.indexesOf(array, (short) 99)); } @Test - public void testNullToEmptyByteObjectNull() { - assertArrayEquals(ArrayUtils.EMPTY_BYTE_OBJECT_ARRAY, ArrayUtils.nullToEmpty((Byte[]) null)); + public void testIndexesOfShortWithStartIndex() { + short[] array = null; + final BitSet emptySet = new BitSet(); + final BitSet testSet = new BitSet(); + assertEquals(emptySet, ArrayUtils.indexesOf(array, (short) 0, 2)); + array = new short[]{0, 1, 2, 3, 0}; + testSet.set(4); + assertEquals(testSet, ArrayUtils.indexesOf(array, (short) 0, 2)); + testSet.set(0); + assertEquals(testSet, ArrayUtils.indexesOf(array, (short) 0, 0)); + testSet.clear(); + testSet.set(1); + assertEquals(testSet, ArrayUtils.indexesOf(array, (short) 1, 1)); + testSet.clear(); + testSet.set(2); + assertEquals(testSet, ArrayUtils.indexesOf(array, (short) 2, 0)); + testSet.clear(); + testSet.set(3); + assertEquals(testSet, ArrayUtils.indexesOf(array, (short) 3, 0)); + assertEquals(testSet, ArrayUtils.indexesOf(array, (short) 3, -1)); + assertEquals(emptySet, ArrayUtils.indexesOf(array, (short) 99, 0)); } @Test - public void testNullToEmptyByteObjectEmptyArray() { - final Byte[] empty = new Byte[]{}; - final Byte[] result = ArrayUtils.nullToEmpty(empty); - assertArrayEquals(ArrayUtils.EMPTY_BYTE_OBJECT_ARRAY, result); - assertNotSame(empty, result); - } - + public void testIndexesOfWithStartIndex() { + final Object[] array = new Object[]{"0", "1", "2", "3", "2", "3", "1", null, "0"}; + final BitSet emptySet = new BitSet(); + final BitSet testSet = new BitSet(); + assertEquals(emptySet, ArrayUtils.indexesOf(null, null, 2)); + assertEquals(emptySet, ArrayUtils.indexesOf(new Object[0], "0", 0)); + assertEquals(emptySet, ArrayUtils.indexesOf(null, "0", 2)); + testSet.set(8); + assertEquals(testSet, ArrayUtils.indexesOf(array, "0", 8)); + testSet.set(0); + assertEquals(testSet, ArrayUtils.indexesOf(array, "0", 0)); + testSet.clear(); + testSet.set(6); + testSet.set(1); + assertEquals(testSet, ArrayUtils.indexesOf(array, "1", 0)); + assertEquals(emptySet, ArrayUtils.indexesOf(array, "1", 9)); + testSet.clear(); + testSet.set(4); + assertEquals(testSet, ArrayUtils.indexesOf(array, "2", 3)); + testSet.set(2); + assertEquals(testSet, ArrayUtils.indexesOf(array, "2", 0)); + testSet.clear(); + testSet.set(3); + testSet.set(5); + assertEquals(testSet, ArrayUtils.indexesOf(array, "3", 0)); + testSet.clear(); + testSet.set(7); + assertEquals(testSet, ArrayUtils.indexesOf(array, null, 0)); + + } + + //----------------------------------------------------------------------- @Test - public void testNullToEmptyByteObject() { - final Byte[] original = new Byte[]{0x0F, 0x0E}; - assertArrayEquals(original, ArrayUtils.nullToEmpty(original)); + public void testIndexOf() { + final Object[] array = new Object[]{"0", "1", "2", "3", null, "0"}; + assertEquals(-1, ArrayUtils.indexOf(null, null)); + assertEquals(-1, ArrayUtils.indexOf(null, "0")); + assertEquals(-1, ArrayUtils.indexOf(new Object[0], "0")); + assertEquals(0, ArrayUtils.indexOf(array, "0")); + assertEquals(1, ArrayUtils.indexOf(array, "1")); + assertEquals(2, ArrayUtils.indexOf(array, "2")); + assertEquals(3, ArrayUtils.indexOf(array, "3")); + assertEquals(4, ArrayUtils.indexOf(array, null)); + assertEquals(-1, ArrayUtils.indexOf(array, "notInArray")); } + //----------------------------------------------------------------------- @Test - public void testNullToEmptyDoubleObjectNull() { - assertArrayEquals(ArrayUtils.EMPTY_DOUBLE_OBJECT_ARRAY, ArrayUtils.nullToEmpty((Double[]) null)); + public void testIndexOfBoolean() { + boolean[] array = null; + assertEquals(-1, ArrayUtils.indexOf(array, true)); + array = new boolean[0]; + assertEquals(-1, ArrayUtils.indexOf(array, true)); + array = new boolean[]{true, false, true}; + assertEquals(0, ArrayUtils.indexOf(array, true)); + assertEquals(1, ArrayUtils.indexOf(array, false)); + array = new boolean[]{true, true}; + assertEquals(-1, ArrayUtils.indexOf(array, false)); } @Test - public void testNullToEmptyDoubleObjectEmptyArray() { - final Double[] empty = new Double[]{}; - final Double[] result = ArrayUtils.nullToEmpty(empty); - assertArrayEquals(ArrayUtils.EMPTY_DOUBLE_OBJECT_ARRAY, result); - assertNotSame(empty, result); + public void testIndexOfBooleanWithStartIndex() { + boolean[] array = null; + assertEquals(-1, ArrayUtils.indexOf(array, true, 2)); + array = new boolean[0]; + assertEquals(-1, ArrayUtils.indexOf(array, true, 2)); + array = new boolean[]{true, false, true}; + assertEquals(2, ArrayUtils.indexOf(array, true, 1)); + assertEquals(-1, ArrayUtils.indexOf(array, false, 2)); + assertEquals(1, ArrayUtils.indexOf(array, false, 0)); + assertEquals(1, ArrayUtils.indexOf(array, false, -1)); + array = new boolean[]{true, true}; + assertEquals(-1, ArrayUtils.indexOf(array, false, 0)); + assertEquals(-1, ArrayUtils.indexOf(array, false, -1)); } + //----------------------------------------------------------------------- @Test - public void testNullToEmptyDoubleObject() { - final Double[] original = new Double[]{1D, 2D}; - assertArrayEquals(original, ArrayUtils.nullToEmpty(original)); + public void testIndexOfByte() { + byte[] array = null; + assertEquals(-1, ArrayUtils.indexOf(array, (byte) 0)); + array = new byte[]{0, 1, 2, 3, 0}; + assertEquals(0, ArrayUtils.indexOf(array, (byte) 0)); + assertEquals(1, ArrayUtils.indexOf(array, (byte) 1)); + assertEquals(2, ArrayUtils.indexOf(array, (byte) 2)); + assertEquals(3, ArrayUtils.indexOf(array, (byte) 3)); + assertEquals(-1, ArrayUtils.indexOf(array, (byte) 99)); } @Test - public void testNullToEmptyFloatObjectNull() { - assertArrayEquals(ArrayUtils.EMPTY_FLOAT_OBJECT_ARRAY, ArrayUtils.nullToEmpty((Float[]) null)); + public void testIndexOfByteWithStartIndex() { + byte[] array = null; + assertEquals(-1, ArrayUtils.indexOf(array, (byte) 0, 2)); + array = new byte[]{0, 1, 2, 3, 0}; + assertEquals(4, ArrayUtils.indexOf(array, (byte) 0, 2)); + assertEquals(-1, ArrayUtils.indexOf(array, (byte) 1, 2)); + assertEquals(2, ArrayUtils.indexOf(array, (byte) 2, 2)); + assertEquals(3, ArrayUtils.indexOf(array, (byte) 3, 2)); + assertEquals(3, ArrayUtils.indexOf(array, (byte) 3, -1)); + assertEquals(-1, ArrayUtils.indexOf(array, (byte) 99, 0)); + assertEquals(-1, ArrayUtils.indexOf(array, (byte) 0, 6)); } + //----------------------------------------------------------------------- @Test - public void testNullToEmptyFloatObjectEmptyArray() { - final Float[] empty = new Float[]{}; - final Float[] result = ArrayUtils.nullToEmpty(empty); - assertArrayEquals(ArrayUtils.EMPTY_FLOAT_OBJECT_ARRAY, result); - assertNotSame(empty, result); + public void testIndexOfChar() { + char[] array = null; + assertEquals(-1, ArrayUtils.indexOf(array, 'a')); + array = new char[]{'a', 'b', 'c', 'd', 'a'}; + assertEquals(0, ArrayUtils.indexOf(array, 'a')); + assertEquals(1, ArrayUtils.indexOf(array, 'b')); + assertEquals(2, ArrayUtils.indexOf(array, 'c')); + assertEquals(3, ArrayUtils.indexOf(array, 'd')); + assertEquals(-1, ArrayUtils.indexOf(array, 'e')); } @Test - public void testNullToEmptyFloatObject() { - final Float[] original = new Float[]{2.6f, 3.8f}; - assertArrayEquals(original, ArrayUtils.nullToEmpty(original)); + public void testIndexOfCharWithStartIndex() { + char[] array = null; + assertEquals(-1, ArrayUtils.indexOf(array, 'a', 2)); + array = new char[]{'a', 'b', 'c', 'd', 'a'}; + assertEquals(4, ArrayUtils.indexOf(array, 'a', 2)); + assertEquals(-1, ArrayUtils.indexOf(array, 'b', 2)); + assertEquals(2, ArrayUtils.indexOf(array, 'c', 2)); + assertEquals(3, ArrayUtils.indexOf(array, 'd', 2)); + assertEquals(3, ArrayUtils.indexOf(array, 'd', -1)); + assertEquals(-1, ArrayUtils.indexOf(array, 'e', 0)); + assertEquals(-1, ArrayUtils.indexOf(array, 'a', 6)); } //----------------------------------------------------------------------- - + @SuppressWarnings("cast") @Test - public void testSubarrayObject() { - final Object[] nullArray = null; - final Object[] objectArray = {"a", "b", "c", "d", "e", "f"}; + public void testIndexOfDouble() { + double[] array = null; + assertEquals(-1, ArrayUtils.indexOf(array, (double) 0)); + array = new double[0]; + assertEquals(-1, ArrayUtils.indexOf(array, (double) 0)); + array = new double[]{0, 1, 2, 3, 0}; + assertEquals(0, ArrayUtils.indexOf(array, (double) 0)); + assertEquals(1, ArrayUtils.indexOf(array, (double) 1)); + assertEquals(2, ArrayUtils.indexOf(array, (double) 2)); + assertEquals(3, ArrayUtils.indexOf(array, (double) 3)); + assertEquals(3, ArrayUtils.indexOf(array, (double) 3, -1)); + assertEquals(-1, ArrayUtils.indexOf(array, (double) 99)); + } - assertEquals("abcd", StringUtils.join(ArrayUtils.subarray(objectArray, 0, 4)), "0 start, mid end"); - assertEquals("abcdef", StringUtils.join(ArrayUtils.subarray(objectArray, 0, objectArray.length)), - "0 start, length end"); - assertEquals("bcd", StringUtils.join(ArrayUtils.subarray(objectArray, 1, 4)), "mid start, mid end"); - assertEquals("bcdef", StringUtils.join(ArrayUtils.subarray(objectArray, 1, objectArray.length)), - "mid start, length end"); + @SuppressWarnings("cast") + @Test + public void testIndexOfDoubleTolerance() { + double[] array = null; + assertEquals(-1, ArrayUtils.indexOf(array, (double) 0, (double) 0)); + array = new double[0]; + assertEquals(-1, ArrayUtils.indexOf(array, (double) 0, (double) 0)); + array = new double[]{0, 1, 2, 3, 0}; + assertEquals(0, ArrayUtils.indexOf(array, (double) 0, 0.3)); + assertEquals(2, ArrayUtils.indexOf(array, 2.2, 0.35)); + assertEquals(3, ArrayUtils.indexOf(array, 4.15, 2.0)); + assertEquals(1, ArrayUtils.indexOf(array, 1.00001324, 0.0001)); + } - assertNull(ArrayUtils.subarray(nullArray, 0, 3), "null input"); - assertEquals("", StringUtils.join(ArrayUtils.subarray(ArrayUtils.EMPTY_OBJECT_ARRAY, 1, 2)), "empty array"); - assertEquals("", StringUtils.join(ArrayUtils.subarray(objectArray, 4, 2)), "start > end"); - assertEquals("", StringUtils.join(ArrayUtils.subarray(objectArray, 3, 3)), "start == end"); - assertEquals("abcd", StringUtils.join(ArrayUtils.subarray(objectArray, -2, 4)), "start undershoot, normal end"); - assertEquals("", StringUtils.join(ArrayUtils.subarray(objectArray, 33, 4)), "start overshoot, any end"); - assertEquals("cdef", StringUtils.join(ArrayUtils.subarray(objectArray, 2, 33)), "normal start, end overshoot"); - assertEquals("abcdef", StringUtils.join(ArrayUtils.subarray(objectArray, -2, 12)), - "start undershoot, end overshoot"); + @SuppressWarnings("cast") + @Test + public void testIndexOfDoubleWithStartIndex() { + double[] array = null; + assertEquals(-1, ArrayUtils.indexOf(array, (double) 0, 2)); + array = new double[0]; + assertEquals(-1, ArrayUtils.indexOf(array, (double) 0, 2)); + array = new double[]{0, 1, 2, 3, 0}; + assertEquals(4, ArrayUtils.indexOf(array, (double) 0, 2)); + assertEquals(-1, ArrayUtils.indexOf(array, (double) 1, 2)); + assertEquals(2, ArrayUtils.indexOf(array, (double) 2, 2)); + assertEquals(3, ArrayUtils.indexOf(array, (double) 3, 2)); + assertEquals(-1, ArrayUtils.indexOf(array, (double) 99, 0)); + assertEquals(-1, ArrayUtils.indexOf(array, (double) 0, 6)); + } - // array type tests - final Date[] dateArray = {new java.sql.Date(new Date().getTime()), - new Date(), new Date(), new Date(), new Date()}; + @SuppressWarnings("cast") + @Test + public void testIndexOfDoubleWithStartIndexTolerance() { + double[] array = null; + assertEquals(-1, ArrayUtils.indexOf(array, (double) 0, 2, (double) 0)); + array = new double[0]; + assertEquals(-1, ArrayUtils.indexOf(array, (double) 0, 2, (double) 0)); + array = new double[]{0, 1, 2, 3, 0}; + assertEquals(-1, ArrayUtils.indexOf(array, (double) 0, 99, 0.3)); + assertEquals(0, ArrayUtils.indexOf(array, (double) 0, 0, 0.3)); + assertEquals(4, ArrayUtils.indexOf(array, (double) 0, 3, 0.3)); + assertEquals(2, ArrayUtils.indexOf(array, 2.2, 0, 0.35)); + assertEquals(3, ArrayUtils.indexOf(array, 4.15, 0, 2.0)); + assertEquals(1, ArrayUtils.indexOf(array, 1.00001324, 0, 0.0001)); + assertEquals(3, ArrayUtils.indexOf(array, 4.15, -1, 2.0)); + assertEquals(1, ArrayUtils.indexOf(array, 1.00001324, -300, 0.0001)); + } - assertSame(Object.class, ArrayUtils.subarray(objectArray, 2, 4).getClass().getComponentType(), "Object type"); - assertSame(Date.class, ArrayUtils.subarray(dateArray, 1, 4).getClass().getComponentType(), - "java.util.Date type"); - assertNotSame(java.sql.Date.class, ArrayUtils.subarray(dateArray, 1, 4).getClass().getComponentType(), - "java.sql.Date type"); - assertThrows(ClassCastException.class, - () -> java.sql.Date[].class.cast(ArrayUtils.subarray(dateArray, 1, 3)), - "Invalid downcast"); + //----------------------------------------------------------------------- + @SuppressWarnings("cast") + @Test + public void testIndexOfFloat() { + float[] array = null; + assertEquals(-1, ArrayUtils.indexOf(array, (float) 0)); + array = new float[0]; + assertEquals(-1, ArrayUtils.indexOf(array, (float) 0)); + array = new float[]{0, 1, 2, 3, 0}; + assertEquals(0, ArrayUtils.indexOf(array, (float) 0)); + assertEquals(1, ArrayUtils.indexOf(array, (float) 1)); + assertEquals(2, ArrayUtils.indexOf(array, (float) 2)); + assertEquals(3, ArrayUtils.indexOf(array, (float) 3)); + assertEquals(-1, ArrayUtils.indexOf(array, (float) 99)); } + @SuppressWarnings("cast") @Test - public void testSubarrayLong() { - final long[] nullArray = null; - final long[] array = {999910, 999911, 999912, 999913, 999914, 999915}; - final long[] leftSubarray = {999910, 999911, 999912, 999913}; - final long[] midSubarray = {999911, 999912, 999913, 999914}; - final long[] rightSubarray = {999912, 999913, 999914, 999915}; + public void testIndexOfFloatWithStartIndex() { + float[] array = null; + assertEquals(-1, ArrayUtils.indexOf(array, (float) 0, 2)); + array = new float[0]; + assertEquals(-1, ArrayUtils.indexOf(array, (float) 0, 2)); + array = new float[]{0, 1, 2, 3, 0}; + assertEquals(4, ArrayUtils.indexOf(array, (float) 0, 2)); + assertEquals(-1, ArrayUtils.indexOf(array, (float) 1, 2)); + assertEquals(2, ArrayUtils.indexOf(array, (float) 2, 2)); + assertEquals(3, ArrayUtils.indexOf(array, (float) 3, 2)); + assertEquals(3, ArrayUtils.indexOf(array, (float) 3, -1)); + assertEquals(-1, ArrayUtils.indexOf(array, (float) 99, 0)); + assertEquals(-1, ArrayUtils.indexOf(array, (float) 0, 6)); + } - assertTrue(ArrayUtils.isEquals(leftSubarray, ArrayUtils.subarray(array, 0, 4)), "0 start, mid end"); - - assertTrue(ArrayUtils.isEquals(array, ArrayUtils.subarray(array, 0, array.length)), "0 start, length end"); - - assertTrue(ArrayUtils.isEquals(midSubarray, ArrayUtils.subarray(array, 1, 5)), "mid start, mid end"); - - assertTrue(ArrayUtils.isEquals(rightSubarray, ArrayUtils.subarray(array, 2, array.length)), - "mid start, length end"); - - assertNull(ArrayUtils.subarray(nullArray, 0, 3), "null input"); - - assertEquals(ArrayUtils.EMPTY_LONG_ARRAY, ArrayUtils.subarray(ArrayUtils.EMPTY_LONG_ARRAY, 1, 2), - "empty array"); - - assertEquals(ArrayUtils.EMPTY_LONG_ARRAY, ArrayUtils.subarray(array, 4, 2), "start > end"); + //----------------------------------------------------------------------- + @Test + public void testIndexOfInt() { + int[] array = null; + assertEquals(-1, ArrayUtils.indexOf(array, 0)); + array = new int[]{0, 1, 2, 3, 0}; + assertEquals(0, ArrayUtils.indexOf(array, 0)); + assertEquals(1, ArrayUtils.indexOf(array, 1)); + assertEquals(2, ArrayUtils.indexOf(array, 2)); + assertEquals(3, ArrayUtils.indexOf(array, 3)); + assertEquals(-1, ArrayUtils.indexOf(array, 99)); + } - assertEquals(ArrayUtils.EMPTY_LONG_ARRAY, ArrayUtils.subarray(array, 3, 3), "start == end"); + @Test + public void testIndexOfIntWithStartIndex() { + int[] array = null; + assertEquals(-1, ArrayUtils.indexOf(array, 0, 2)); + array = new int[]{0, 1, 2, 3, 0}; + assertEquals(4, ArrayUtils.indexOf(array, 0, 2)); + assertEquals(-1, ArrayUtils.indexOf(array, 1, 2)); + assertEquals(2, ArrayUtils.indexOf(array, 2, 2)); + assertEquals(3, ArrayUtils.indexOf(array, 3, 2)); + assertEquals(3, ArrayUtils.indexOf(array, 3, -1)); + assertEquals(-1, ArrayUtils.indexOf(array, 99, 0)); + assertEquals(-1, ArrayUtils.indexOf(array, 0, 6)); + } - assertTrue(ArrayUtils.isEquals(leftSubarray, ArrayUtils.subarray(array, -2, 4)), - "start undershoot, normal end"); + //----------------------------------------------------------------------- + @Test + public void testIndexOfLong() { + long[] array = null; + assertEquals(-1, ArrayUtils.indexOf(array, 0)); + array = new long[]{0, 1, 2, 3, 0}; + assertEquals(0, ArrayUtils.indexOf(array, 0)); + assertEquals(1, ArrayUtils.indexOf(array, 1)); + assertEquals(2, ArrayUtils.indexOf(array, 2)); + assertEquals(3, ArrayUtils.indexOf(array, 3)); + assertEquals(-1, ArrayUtils.indexOf(array, 99)); + } - assertEquals(ArrayUtils.EMPTY_LONG_ARRAY, ArrayUtils.subarray(array, 33, 4), "start overshoot, any end"); + @Test + public void testIndexOfLongWithStartIndex() { + long[] array = null; + assertEquals(-1, ArrayUtils.indexOf(array, 0, 2)); + array = new long[]{0, 1, 2, 3, 0}; + assertEquals(4, ArrayUtils.indexOf(array, 0, 2)); + assertEquals(-1, ArrayUtils.indexOf(array, 1, 2)); + assertEquals(2, ArrayUtils.indexOf(array, 2, 2)); + assertEquals(3, ArrayUtils.indexOf(array, 3, 2)); + assertEquals(3, ArrayUtils.indexOf(array, 3, -1)); + assertEquals(-1, ArrayUtils.indexOf(array, 99, 0)); + assertEquals(-1, ArrayUtils.indexOf(array, 0, 6)); + } - assertTrue(ArrayUtils.isEquals(rightSubarray, ArrayUtils.subarray(array, 2, 33)), - "normal start, end overshoot"); + //----------------------------------------------------------------------- + @Test + public void testIndexOfShort() { + short[] array = null; + assertEquals(-1, ArrayUtils.indexOf(array, (short) 0)); + array = new short[]{0, 1, 2, 3, 0}; + assertEquals(0, ArrayUtils.indexOf(array, (short) 0)); + assertEquals(1, ArrayUtils.indexOf(array, (short) 1)); + assertEquals(2, ArrayUtils.indexOf(array, (short) 2)); + assertEquals(3, ArrayUtils.indexOf(array, (short) 3)); + assertEquals(-1, ArrayUtils.indexOf(array, (short) 99)); + } - assertTrue(ArrayUtils.isEquals(array, ArrayUtils.subarray(array, -2, 12)), "start undershoot, end overshoot"); + @Test + public void testIndexOfShortWithStartIndex() { + short[] array = null; + assertEquals(-1, ArrayUtils.indexOf(array, (short) 0, 2)); + array = new short[]{0, 1, 2, 3, 0}; + assertEquals(4, ArrayUtils.indexOf(array, (short) 0, 2)); + assertEquals(-1, ArrayUtils.indexOf(array, (short) 1, 2)); + assertEquals(2, ArrayUtils.indexOf(array, (short) 2, 2)); + assertEquals(3, ArrayUtils.indexOf(array, (short) 3, 2)); + assertEquals(3, ArrayUtils.indexOf(array, (short) 3, -1)); + assertEquals(-1, ArrayUtils.indexOf(array, (short) 99, 0)); + assertEquals(-1, ArrayUtils.indexOf(array, (short) 0, 6)); + } - // empty-return tests + @Test + public void testIndexOfWithStartIndex() { + final Object[] array = new Object[]{"0", "1", "2", "3", null, "0"}; + assertEquals(-1, ArrayUtils.indexOf(null, null, 2)); + assertEquals(-1, ArrayUtils.indexOf(new Object[0], "0", 0)); + assertEquals(-1, ArrayUtils.indexOf(null, "0", 2)); + assertEquals(5, ArrayUtils.indexOf(array, "0", 2)); + assertEquals(-1, ArrayUtils.indexOf(array, "1", 2)); + assertEquals(2, ArrayUtils.indexOf(array, "2", 2)); + assertEquals(3, ArrayUtils.indexOf(array, "3", 2)); + assertEquals(4, ArrayUtils.indexOf(array, null, 2)); + assertEquals(-1, ArrayUtils.indexOf(array, "notInArray", 2)); - assertSame(ArrayUtils.EMPTY_LONG_ARRAY, ArrayUtils.subarray(ArrayUtils.EMPTY_LONG_ARRAY, 1, 2), - "empty array, object test"); + assertEquals(4, ArrayUtils.indexOf(array, null, -1)); + assertEquals(-1, ArrayUtils.indexOf(array, null, 8)); + assertEquals(-1, ArrayUtils.indexOf(array, "0", 8)); + } - assertSame(ArrayUtils.EMPTY_LONG_ARRAY, ArrayUtils.subarray(array, 4, 1), "start > end, object test"); + /** + * Tests generic array creation with generic type. + */ + @Test + public void testIndirectArrayCreation() { + final String[] array = toArrayPropagatingType("foo", "bar"); + assertEquals(2, array.length); + assertEquals("foo", array[0]); + assertEquals("bar", array[1]); + } - assertSame(ArrayUtils.EMPTY_LONG_ARRAY, ArrayUtils.subarray(array, 3, 3), "start == end, object test"); + /** + * Tests indirect generic empty array creation with generic type. + */ + @Test + public void testIndirectEmptyArrayCreation() { + final String[] array = ArrayUtilsTest.toArrayPropagatingType(); + assertEquals(0, array.length); + } - assertSame(ArrayUtils.EMPTY_LONG_ARRAY, ArrayUtils.subarray(array, 8733, 4), - "start overshoot, any end, object test"); + @Test + public void testIsArrayIndexValid() { + assertFalse(ArrayUtils.isArrayIndexValid(null, 0)); + final String[] array = new String[1]; - // array type tests + //too big + assertFalse(ArrayUtils.isArrayIndexValid(array, 1)); - assertSame(long.class, ArrayUtils.subarray(array, 2, 4).getClass().getComponentType(), "long type"); + //negative index + assertFalse(ArrayUtils.isArrayIndexValid(array, -1)); + //good to go + assertTrue(ArrayUtils.isArrayIndexValid(array, 0)); } + /** + * Test for {@link ArrayUtils#isEmpty(java.lang.Object[])}. + */ @Test - public void testSubarrayInt() { - final int[] nullArray = null; - final int[] array = {10, 11, 12, 13, 14, 15}; - final int[] leftSubarray = {10, 11, 12, 13}; - final int[] midSubarray = {11, 12, 13, 14}; - final int[] rightSubarray = {12, 13, 14, 15}; + public void testIsEmptyObject() { + final Object[] emptyArray = new Object[]{}; + final Object[] notEmptyArray = new Object[]{new String("Value")}; + assertTrue(ArrayUtils.isEmpty((Object[]) null)); + assertTrue(ArrayUtils.isEmpty(emptyArray)); + assertFalse(ArrayUtils.isEmpty(notEmptyArray)); + } + /** + * Tests for {@link ArrayUtils#isEmpty(long[])}, + * {@link ArrayUtils#isEmpty(int[])}, + * {@link ArrayUtils#isEmpty(short[])}, + * {@link ArrayUtils#isEmpty(char[])}, + * {@link ArrayUtils#isEmpty(byte[])}, + * {@link ArrayUtils#isEmpty(double[])}, + * {@link ArrayUtils#isEmpty(float[])} and + * {@link ArrayUtils#isEmpty(boolean[])}. + */ + @Test + public void testIsEmptyPrimitives() { + final long[] emptyLongArray = new long[]{}; + final long[] notEmptyLongArray = new long[]{1L}; + assertTrue(ArrayUtils.isEmpty((long[]) null)); + assertTrue(ArrayUtils.isEmpty(emptyLongArray)); + assertFalse(ArrayUtils.isEmpty(notEmptyLongArray)); - assertTrue(ArrayUtils.isEquals(leftSubarray, ArrayUtils.subarray(array, 0, 4)), "0 start, mid end"); + final int[] emptyIntArray = new int[]{}; + final int[] notEmptyIntArray = new int[]{1}; + assertTrue(ArrayUtils.isEmpty((int[]) null)); + assertTrue(ArrayUtils.isEmpty(emptyIntArray)); + assertFalse(ArrayUtils.isEmpty(notEmptyIntArray)); - assertTrue(ArrayUtils.isEquals(array, ArrayUtils.subarray(array, 0, array.length)), "0 start, length end"); + final short[] emptyShortArray = new short[]{}; + final short[] notEmptyShortArray = new short[]{1}; + assertTrue(ArrayUtils.isEmpty((short[]) null)); + assertTrue(ArrayUtils.isEmpty(emptyShortArray)); + assertFalse(ArrayUtils.isEmpty(notEmptyShortArray)); - assertTrue(ArrayUtils.isEquals(midSubarray, ArrayUtils.subarray(array, 1, 5)), "mid start, mid end"); + final char[] emptyCharArray = new char[]{}; + final char[] notEmptyCharArray = new char[]{1}; + assertTrue(ArrayUtils.isEmpty((char[]) null)); + assertTrue(ArrayUtils.isEmpty(emptyCharArray)); + assertFalse(ArrayUtils.isEmpty(notEmptyCharArray)); - assertTrue(ArrayUtils.isEquals(rightSubarray, ArrayUtils.subarray(array, 2, array.length)), - "mid start, length end"); + final byte[] emptyByteArray = new byte[]{}; + final byte[] notEmptyByteArray = new byte[]{1}; + assertTrue(ArrayUtils.isEmpty((byte[]) null)); + assertTrue(ArrayUtils.isEmpty(emptyByteArray)); + assertFalse(ArrayUtils.isEmpty(notEmptyByteArray)); + final double[] emptyDoubleArray = new double[]{}; + final double[] notEmptyDoubleArray = new double[]{1.0}; + assertTrue(ArrayUtils.isEmpty((double[]) null)); + assertTrue(ArrayUtils.isEmpty(emptyDoubleArray)); + assertFalse(ArrayUtils.isEmpty(notEmptyDoubleArray)); - assertNull(ArrayUtils.subarray(nullArray, 0, 3), "null input"); + final float[] emptyFloatArray = new float[]{}; + final float[] notEmptyFloatArray = new float[]{1.0F}; + assertTrue(ArrayUtils.isEmpty((float[]) null)); + assertTrue(ArrayUtils.isEmpty(emptyFloatArray)); + assertFalse(ArrayUtils.isEmpty(notEmptyFloatArray)); - assertEquals(ArrayUtils.EMPTY_INT_ARRAY, ArrayUtils.subarray(ArrayUtils.EMPTY_INT_ARRAY, 1, 2), "empty array"); + final boolean[] emptyBooleanArray = new boolean[]{}; + final boolean[] notEmptyBooleanArray = new boolean[]{true}; + assertTrue(ArrayUtils.isEmpty((boolean[]) null)); + assertTrue(ArrayUtils.isEmpty(emptyBooleanArray)); + assertFalse(ArrayUtils.isEmpty(notEmptyBooleanArray)); + } - assertEquals(ArrayUtils.EMPTY_INT_ARRAY, ArrayUtils.subarray(array, 4, 2), "start > end"); + @Test + public void testIsEquals() { + final long[][] larray1 = new long[][]{{2, 5}, {4, 5}}; + final long[][] larray2 = new long[][]{{2, 5}, {4, 6}}; + final long[] larray3 = new long[]{2, 5}; + this.assertIsEquals(larray1, larray2, larray3); - assertEquals(ArrayUtils.EMPTY_INT_ARRAY, ArrayUtils.subarray(array, 3, 3), "start == end"); + final int[][] iarray1 = new int[][]{{2, 5}, {4, 5}}; + final int[][] iarray2 = new int[][]{{2, 5}, {4, 6}}; + final int[] iarray3 = new int[]{2, 5}; + this.assertIsEquals(iarray1, iarray2, iarray3); - assertTrue(ArrayUtils.isEquals(leftSubarray, ArrayUtils.subarray(array, -2, 4)), - "start undershoot, normal end"); + final short[][] sarray1 = new short[][]{{2, 5}, {4, 5}}; + final short[][] sarray2 = new short[][]{{2, 5}, {4, 6}}; + final short[] sarray3 = new short[]{2, 5}; + this.assertIsEquals(sarray1, sarray2, sarray3); - assertEquals(ArrayUtils.EMPTY_INT_ARRAY, ArrayUtils.subarray(array, 33, 4), "start overshoot, any end"); + final float[][] farray1 = new float[][]{{2, 5}, {4, 5}}; + final float[][] farray2 = new float[][]{{2, 5}, {4, 6}}; + final float[] farray3 = new float[]{2, 5}; + this.assertIsEquals(farray1, farray2, farray3); - assertTrue(ArrayUtils.isEquals(rightSubarray, ArrayUtils.subarray(array, 2, 33)), - "normal start, end overshoot"); + final double[][] darray1 = new double[][]{{2, 5}, {4, 5}}; + final double[][] darray2 = new double[][]{{2, 5}, {4, 6}}; + final double[] darray3 = new double[]{2, 5}; + this.assertIsEquals(darray1, darray2, darray3); - assertTrue(ArrayUtils.isEquals(array, ArrayUtils.subarray(array, -2, 12)), "start undershoot, end overshoot"); - - // empty-return tests - - assertSame(ArrayUtils.EMPTY_INT_ARRAY, ArrayUtils.subarray(ArrayUtils.EMPTY_INT_ARRAY, 1, 2), - "empty array, object test"); + final byte[][] byteArray1 = new byte[][]{{2, 5}, {4, 5}}; + final byte[][] byteArray2 = new byte[][]{{2, 5}, {4, 6}}; + final byte[] byteArray3 = new byte[]{2, 5}; + this.assertIsEquals(byteArray1, byteArray2, byteArray3); - assertSame(ArrayUtils.EMPTY_INT_ARRAY, ArrayUtils.subarray(array, 4, 1), "start > end, object test"); + final char[][] charArray1 = new char[][]{{2, 5}, {4, 5}}; + final char[][] charArray2 = new char[][]{{2, 5}, {4, 6}}; + final char[] charArray3 = new char[]{2, 5}; + this.assertIsEquals(charArray1, charArray2, charArray3); - assertSame(ArrayUtils.EMPTY_INT_ARRAY, ArrayUtils.subarray(array, 3, 3), "start == end, object test"); + final boolean[][] barray1 = new boolean[][]{{true, false}, {true, true}}; + final boolean[][] barray2 = new boolean[][]{{true, false}, {true, false}}; + final boolean[] barray3 = new boolean[]{false, true}; + this.assertIsEquals(barray1, barray2, barray3); - assertSame(ArrayUtils.EMPTY_INT_ARRAY, ArrayUtils.subarray(array, 8733, 4), - "start overshoot, any end, object test"); + final Object[] array3 = new Object[]{new String(new char[]{'A', 'B'})}; + final Object[] array4 = new Object[]{"AB"}; + assertTrue(ArrayUtils.isEquals(array3, array3)); + assertTrue(ArrayUtils.isEquals(array3, array4)); - // array type tests + assertTrue(ArrayUtils.isEquals(null, null)); + assertFalse(ArrayUtils.isEquals(null, array4)); + } - assertSame(int.class, ArrayUtils.subarray(array, 2, 4).getClass().getComponentType(), "int type"); + /** + * Test for {@link ArrayUtils#isNotEmpty(java.lang.Object[])}. + */ + @Test + public void testIsNotEmptyObject() { + final Object[] emptyArray = new Object[]{}; + final Object[] notEmptyArray = new Object[]{new String("Value")}; + assertFalse(ArrayUtils.isNotEmpty((Object[]) null)); + assertFalse(ArrayUtils.isNotEmpty(emptyArray)); + assertTrue(ArrayUtils.isNotEmpty(notEmptyArray)); } + /** + * Tests for {@link ArrayUtils#isNotEmpty(long[])}, + * {@link ArrayUtils#isNotEmpty(int[])}, + * {@link ArrayUtils#isNotEmpty(short[])}, + * {@link ArrayUtils#isNotEmpty(char[])}, + * {@link ArrayUtils#isNotEmpty(byte[])}, + * {@link ArrayUtils#isNotEmpty(double[])}, + * {@link ArrayUtils#isNotEmpty(float[])} and + * {@link ArrayUtils#isNotEmpty(boolean[])}. + */ @Test - public void testSubarrayShort() { - final short[] nullArray = null; - final short[] array = {10, 11, 12, 13, 14, 15}; - final short[] leftSubarray = {10, 11, 12, 13}; - final short[] midSubarray = {11, 12, 13, 14}; - final short[] rightSubarray = {12, 13, 14, 15}; + public void testIsNotEmptyPrimitives() { + final long[] emptyLongArray = new long[]{}; + final long[] notEmptyLongArray = new long[]{1L}; + assertFalse(ArrayUtils.isNotEmpty((long[]) null)); + assertFalse(ArrayUtils.isNotEmpty(emptyLongArray)); + assertTrue(ArrayUtils.isNotEmpty(notEmptyLongArray)); - assertTrue(ArrayUtils.isEquals(leftSubarray, ArrayUtils.subarray(array, 0, 4)), "0 start, mid end"); - assertTrue(ArrayUtils.isEquals(array, ArrayUtils.subarray(array, 0, array.length)), "0 start, length end"); - assertTrue(ArrayUtils.isEquals(midSubarray, ArrayUtils.subarray(array, 1, 5)), "mid start, mid end"); - assertTrue(ArrayUtils.isEquals(rightSubarray, ArrayUtils.subarray(array, 2, array.length)), - "mid start, length end"); + final int[] emptyIntArray = new int[]{}; + final int[] notEmptyIntArray = new int[]{1}; + assertFalse(ArrayUtils.isNotEmpty((int[]) null)); + assertFalse(ArrayUtils.isNotEmpty(emptyIntArray)); + assertTrue(ArrayUtils.isNotEmpty(notEmptyIntArray)); - assertNull(ArrayUtils.subarray(nullArray, 0, 3), "null input"); - assertEquals(ArrayUtils.EMPTY_SHORT_ARRAY, ArrayUtils.subarray(ArrayUtils.EMPTY_SHORT_ARRAY, 1, 2), - "empty array"); - assertEquals(ArrayUtils.EMPTY_SHORT_ARRAY, ArrayUtils.subarray(array, 4, 2), "start > end"); - assertEquals(ArrayUtils.EMPTY_SHORT_ARRAY, ArrayUtils.subarray(array, 3, 3), "start == end"); - assertTrue(ArrayUtils.isEquals(leftSubarray, ArrayUtils.subarray(array, -2, 4)), - "start undershoot, normal end"); - assertEquals(ArrayUtils.EMPTY_SHORT_ARRAY, ArrayUtils.subarray(array, 33, 4), "start overshoot, any end"); - assertTrue(ArrayUtils.isEquals(rightSubarray, ArrayUtils.subarray(array, 2, 33)), - "normal start, end overshoot"); - assertTrue(ArrayUtils.isEquals(array, ArrayUtils.subarray(array, -2, 12)), "start undershoot, end overshoot"); + final short[] emptyShortArray = new short[]{}; + final short[] notEmptyShortArray = new short[]{1}; + assertFalse(ArrayUtils.isNotEmpty((short[]) null)); + assertFalse(ArrayUtils.isNotEmpty(emptyShortArray)); + assertTrue(ArrayUtils.isNotEmpty(notEmptyShortArray)); - // empty-return tests + final char[] emptyCharArray = new char[]{}; + final char[] notEmptyCharArray = new char[]{1}; + assertFalse(ArrayUtils.isNotEmpty((char[]) null)); + assertFalse(ArrayUtils.isNotEmpty(emptyCharArray)); + assertTrue(ArrayUtils.isNotEmpty(notEmptyCharArray)); - assertSame(ArrayUtils.EMPTY_SHORT_ARRAY, ArrayUtils.subarray(ArrayUtils.EMPTY_SHORT_ARRAY, 1, 2), - "empty array, object test"); - assertSame(ArrayUtils.EMPTY_SHORT_ARRAY, ArrayUtils.subarray(array, 4, 1), "start > end, object test"); - assertSame(ArrayUtils.EMPTY_SHORT_ARRAY, ArrayUtils.subarray(array, 3, 3), "start == end, object test"); - assertSame(ArrayUtils.EMPTY_SHORT_ARRAY, ArrayUtils.subarray(array, 8733, 4), - "start overshoot, any end, object test"); + final byte[] emptyByteArray = new byte[]{}; + final byte[] notEmptyByteArray = new byte[]{1}; + assertFalse(ArrayUtils.isNotEmpty((byte[]) null)); + assertFalse(ArrayUtils.isNotEmpty(emptyByteArray)); + assertTrue(ArrayUtils.isNotEmpty(notEmptyByteArray)); - // array type tests + final double[] emptyDoubleArray = new double[]{}; + final double[] notEmptyDoubleArray = new double[]{1.0}; + assertFalse(ArrayUtils.isNotEmpty((double[]) null)); + assertFalse(ArrayUtils.isNotEmpty(emptyDoubleArray)); + assertTrue(ArrayUtils.isNotEmpty(notEmptyDoubleArray)); - assertSame(short.class, ArrayUtils.subarray(array, 2, 4).getClass().getComponentType(), "short type"); + final float[] emptyFloatArray = new float[]{}; + final float[] notEmptyFloatArray = new float[]{1.0F}; + assertFalse(ArrayUtils.isNotEmpty((float[]) null)); + assertFalse(ArrayUtils.isNotEmpty(emptyFloatArray)); + assertTrue(ArrayUtils.isNotEmpty(notEmptyFloatArray)); + + final boolean[] emptyBooleanArray = new boolean[]{}; + final boolean[] notEmptyBooleanArray = new boolean[]{true}; + assertFalse(ArrayUtils.isNotEmpty((boolean[]) null)); + assertFalse(ArrayUtils.isNotEmpty(emptyBooleanArray)); + assertTrue(ArrayUtils.isNotEmpty(notEmptyBooleanArray)); } @Test - public void testSubarrChar() { - final char[] nullArray = null; - final char[] array = {'a', 'b', 'c', 'd', 'e', 'f'}; - final char[] leftSubarray = {'a', 'b', 'c', 'd'}; - final char[] midSubarray = {'b', 'c', 'd', 'e'}; - final char[] rightSubarray = {'c', 'd', 'e', 'f'}; + public void testIsSorted() { + Integer[] array = null; + assertTrue(ArrayUtils.isSorted(array)); - assertTrue(ArrayUtils.isEquals(leftSubarray, ArrayUtils.subarray(array, 0, 4)), "0 start, mid end"); - assertTrue(ArrayUtils.isEquals(array, ArrayUtils.subarray(array, 0, array.length)), "0 start, length end"); - assertTrue(ArrayUtils.isEquals(midSubarray, ArrayUtils.subarray(array, 1, 5)), "mid start, mid end"); - assertTrue(ArrayUtils.isEquals(rightSubarray, ArrayUtils.subarray(array, 2, array.length)), - "mid start, length end"); + array = new Integer[]{1}; + assertTrue(ArrayUtils.isSorted(array)); - assertNull(ArrayUtils.subarray(nullArray, 0, 3), "null input"); - assertEquals(ArrayUtils.EMPTY_CHAR_ARRAY, ArrayUtils.subarray(ArrayUtils.EMPTY_CHAR_ARRAY, 1, 2), - "empty array"); - assertEquals(ArrayUtils.EMPTY_CHAR_ARRAY, ArrayUtils.subarray(array, 4, 2), "start > end"); - assertEquals(ArrayUtils.EMPTY_CHAR_ARRAY, ArrayUtils.subarray(array, 3, 3), "start == end"); - assertTrue(ArrayUtils.isEquals(leftSubarray, ArrayUtils.subarray(array, -2, 4)), - "start undershoot, normal end"); - assertEquals(ArrayUtils.EMPTY_CHAR_ARRAY, ArrayUtils.subarray(array, 33, 4), "start overshoot, any end"); - assertTrue(ArrayUtils.isEquals(rightSubarray, ArrayUtils.subarray(array, 2, 33)), - "normal start, end overshoot"); - assertTrue(ArrayUtils.isEquals(array, ArrayUtils.subarray(array, -2, 12)), "start undershoot, end overshoot"); + array = new Integer[]{1, 2, 3}; + assertTrue(ArrayUtils.isSorted(array)); - // empty-return tests + array = new Integer[]{1, 3, 2}; + assertFalse(ArrayUtils.isSorted(array)); + } - assertSame(ArrayUtils.EMPTY_CHAR_ARRAY, ArrayUtils.subarray(ArrayUtils.EMPTY_CHAR_ARRAY, 1, 2), - "empty array, object test"); - assertSame(ArrayUtils.EMPTY_CHAR_ARRAY, ArrayUtils.subarray(array, 4, 1), "start > end, object test"); - assertSame(ArrayUtils.EMPTY_CHAR_ARRAY, ArrayUtils.subarray(array, 3, 3), "start == end, object test"); - assertSame(ArrayUtils.EMPTY_CHAR_ARRAY, ArrayUtils.subarray(array, 8733, 4), - "start overshoot, any end, object test"); + @Test + public void testIsSortedBool() { + boolean[] array = null; + assertTrue(ArrayUtils.isSorted(array)); - // array type tests + array = new boolean[]{true}; + assertTrue(ArrayUtils.isSorted(array)); - assertSame(char.class, ArrayUtils.subarray(array, 2, 4).getClass().getComponentType(), "char type"); + array = new boolean[]{false, true}; + assertTrue(ArrayUtils.isSorted(array)); + + array = new boolean[]{true, false}; + assertFalse(ArrayUtils.isSorted(array)); } @Test - public void testSubarrayByte() { - final byte[] nullArray = null; - final byte[] array = {10, 11, 12, 13, 14, 15}; - final byte[] leftSubarray = {10, 11, 12, 13}; - final byte[] midSubarray = {11, 12, 13, 14}; - final byte[] rightSubarray = {12, 13, 14, 15}; + public void testIsSortedByte() { + byte[] array = null; + assertTrue(ArrayUtils.isSorted(array)); - assertTrue(ArrayUtils.isEquals(leftSubarray, ArrayUtils.subarray(array, 0, 4)), "0 start, mid end"); - assertTrue(ArrayUtils.isEquals(array, ArrayUtils.subarray(array, 0, array.length)), "0 start, length end"); - assertTrue(ArrayUtils.isEquals(midSubarray, ArrayUtils.subarray(array, 1, 5)), "mid start, mid end"); - assertTrue(ArrayUtils.isEquals(rightSubarray, ArrayUtils.subarray(array, 2, array.length)), - "mid start, length end"); + array = new byte[]{0x10}; + assertTrue(ArrayUtils.isSorted(array)); - assertNull(ArrayUtils.subarray(nullArray, 0, 3), "null input"); - assertEquals(ArrayUtils.EMPTY_BYTE_ARRAY, ArrayUtils.subarray(ArrayUtils.EMPTY_BYTE_ARRAY, 1, 2), - "empty array"); - assertEquals(ArrayUtils.EMPTY_BYTE_ARRAY, ArrayUtils.subarray(array, 4, 2), "start > end"); - assertEquals(ArrayUtils.EMPTY_BYTE_ARRAY, ArrayUtils.subarray(array, 3, 3), "start == end"); - assertTrue(ArrayUtils.isEquals(leftSubarray, ArrayUtils.subarray(array, -2, 4)), - "start undershoot, normal end"); - assertEquals(ArrayUtils.EMPTY_BYTE_ARRAY, ArrayUtils.subarray(array, 33, 4), "start overshoot, any end"); - assertTrue(ArrayUtils.isEquals(rightSubarray, ArrayUtils.subarray(array, 2, 33)), - "normal start, end overshoot"); - assertTrue(ArrayUtils.isEquals(array, ArrayUtils.subarray(array, -2, 12)), "start undershoot, end overshoot"); + array = new byte[]{0x10, 0x20, 0x30}; + assertTrue(ArrayUtils.isSorted(array)); - // empty-return tests + array = new byte[]{0x10, 0x30, 0x20}; + assertFalse(ArrayUtils.isSorted(array)); + } - assertSame(ArrayUtils.EMPTY_BYTE_ARRAY, ArrayUtils.subarray(ArrayUtils.EMPTY_BYTE_ARRAY, 1, 2), - "empty array, object test"); - assertSame(ArrayUtils.EMPTY_BYTE_ARRAY, ArrayUtils.subarray(array, 4, 1), "start > end, object test"); - assertSame(ArrayUtils.EMPTY_BYTE_ARRAY, ArrayUtils.subarray(array, 3, 3), "start == end, object test"); - assertSame(ArrayUtils.EMPTY_BYTE_ARRAY, ArrayUtils.subarray(array, 8733, 4), - "start overshoot, any end, object test"); + @Test + public void testIsSortedChar() { + char[] array = null; + assertTrue(ArrayUtils.isSorted(array)); - // array type tests + array = new char[]{'a'}; + assertTrue(ArrayUtils.isSorted(array)); - assertSame(byte.class, ArrayUtils.subarray(array, 2, 4).getClass().getComponentType(), "byte type"); + array = new char[]{'a', 'b', 'c'}; + assertTrue(ArrayUtils.isSorted(array)); + + array = new char[]{'a', 'c', 'b'}; + assertFalse(ArrayUtils.isSorted(array)); } @Test - public void testSubarrayDouble() { - final double[] nullArray = null; - final double[] array = {10.123, 11.234, 12.345, 13.456, 14.567, 15.678}; - final double[] leftSubarray = {10.123, 11.234, 12.345, 13.456}; - final double[] midSubarray = {11.234, 12.345, 13.456, 14.567}; - final double[] rightSubarray = {12.345, 13.456, 14.567, 15.678}; + public void testIsSortedComparator() { + final Comparator c = (o1, o2) -> o2.compareTo(o1); - assertTrue(ArrayUtils.isEquals(leftSubarray, ArrayUtils.subarray(array, 0, 4)), "0 start, mid end"); - assertTrue(ArrayUtils.isEquals(array, ArrayUtils.subarray(array, 0, array.length)), "0 start, length end"); - assertTrue(ArrayUtils.isEquals(midSubarray, ArrayUtils.subarray(array, 1, 5)), "mid start, mid end"); - assertTrue(ArrayUtils.isEquals(rightSubarray, ArrayUtils.subarray(array, 2, array.length)), - "mid start, length end"); + Integer[] array = null; + assertTrue(ArrayUtils.isSorted(array, c)); - assertNull(ArrayUtils.subarray(nullArray, 0, 3), "null input"); - assertEquals(ArrayUtils.EMPTY_DOUBLE_ARRAY, ArrayUtils.subarray(ArrayUtils.EMPTY_DOUBLE_ARRAY, 1, 2), - "empty array"); - assertEquals(ArrayUtils.EMPTY_DOUBLE_ARRAY, ArrayUtils.subarray(array, 4, 2), "start > end"); - assertEquals(ArrayUtils.EMPTY_DOUBLE_ARRAY, ArrayUtils.subarray(array, 3, 3), "start == end"); - assertTrue(ArrayUtils.isEquals(leftSubarray, ArrayUtils.subarray(array, -2, 4)), - "start undershoot, normal end"); - assertEquals(ArrayUtils.EMPTY_DOUBLE_ARRAY, ArrayUtils.subarray(array, 33, 4), "start overshoot, any end"); - assertTrue(ArrayUtils.isEquals(rightSubarray, ArrayUtils.subarray(array, 2, 33)), - "normal start, end overshoot"); - assertTrue(ArrayUtils.isEquals(array, ArrayUtils.subarray(array, -2, 12)), "start undershoot, end overshoot"); + array = new Integer[]{1}; + assertTrue(ArrayUtils.isSorted(array, c)); - // empty-return tests - - assertSame(ArrayUtils.EMPTY_DOUBLE_ARRAY, ArrayUtils.subarray(ArrayUtils.EMPTY_DOUBLE_ARRAY, 1, 2), - "empty array, object test"); - assertSame(ArrayUtils.EMPTY_DOUBLE_ARRAY, ArrayUtils.subarray(array, 4, 1), "start > end, object test"); - assertSame(ArrayUtils.EMPTY_DOUBLE_ARRAY, ArrayUtils.subarray(array, 3, 3), "start == end, object test"); - assertSame(ArrayUtils.EMPTY_DOUBLE_ARRAY, ArrayUtils.subarray(array, 8733, 4), - "start overshoot, any end, object test"); - - // array type tests + array = new Integer[]{3, 2, 1}; + assertTrue(ArrayUtils.isSorted(array, c)); - assertSame(double.class, ArrayUtils.subarray(array, 2, 4).getClass().getComponentType(), "double type"); + array = new Integer[]{1, 3, 2}; + assertFalse(ArrayUtils.isSorted(array, c)); } @Test - public void testSubarrayFloat() { - final float[] nullArray = null; - final float[] array = {10, 11, 12, 13, 14, 15}; - final float[] leftSubarray = {10, 11, 12, 13}; - final float[] midSubarray = {11, 12, 13, 14}; - final float[] rightSubarray = {12, 13, 14, 15}; - - assertTrue(ArrayUtils.isEquals(leftSubarray, ArrayUtils.subarray(array, 0, 4)), "0 start, mid end"); - assertTrue(ArrayUtils.isEquals(array, ArrayUtils.subarray(array, 0, array.length)), "0 start, length end"); - assertTrue(ArrayUtils.isEquals(midSubarray, ArrayUtils.subarray(array, 1, 5)), "mid start, mid end"); - assertTrue(ArrayUtils.isEquals(rightSubarray, ArrayUtils.subarray(array, 2, array.length)), - "mid start, length end"); - - assertNull(ArrayUtils.subarray(nullArray, 0, 3), "null input"); - assertEquals(ArrayUtils.EMPTY_FLOAT_ARRAY, ArrayUtils.subarray(ArrayUtils.EMPTY_FLOAT_ARRAY, 1, 2), - "empty array"); - assertEquals(ArrayUtils.EMPTY_FLOAT_ARRAY, ArrayUtils.subarray(array, 4, 2), "start > end"); - assertEquals(ArrayUtils.EMPTY_FLOAT_ARRAY, ArrayUtils.subarray(array, 3, 3), "start == end"); - assertTrue(ArrayUtils.isEquals(leftSubarray, ArrayUtils.subarray(array, -2, 4)), - "start undershoot, normal end"); - assertEquals(ArrayUtils.EMPTY_FLOAT_ARRAY, ArrayUtils.subarray(array, 33, 4), "start overshoot, any end"); - assertTrue(ArrayUtils.isEquals(rightSubarray, ArrayUtils.subarray(array, 2, 33)), - "normal start, end overshoot"); - assertTrue(ArrayUtils.isEquals(array, ArrayUtils.subarray(array, -2, 12)), "start undershoot, end overshoot"); - - // empty-return tests + public void testIsSortedDouble() { + double[] array = null; + assertTrue(ArrayUtils.isSorted(array)); - assertSame(ArrayUtils.EMPTY_FLOAT_ARRAY, ArrayUtils.subarray(ArrayUtils.EMPTY_FLOAT_ARRAY, 1, 2), - "empty array, object test"); - assertSame(ArrayUtils.EMPTY_FLOAT_ARRAY, ArrayUtils.subarray(array, 4, 1), "start > end, object test"); - assertSame(ArrayUtils.EMPTY_FLOAT_ARRAY, ArrayUtils.subarray(array, 3, 3), "start == end, object test"); - assertSame(ArrayUtils.EMPTY_FLOAT_ARRAY, ArrayUtils.subarray(array, 8733, 4), - "start overshoot, any end, object test"); + array = new double[]{0.0}; + assertTrue(ArrayUtils.isSorted(array)); - // array type tests + array = new double[]{-1.0, 0.0, 0.1, 0.2}; + assertTrue(ArrayUtils.isSorted(array)); - assertSame(float.class, ArrayUtils.subarray(array, 2, 4).getClass().getComponentType(), "float type"); + array = new double[]{-1.0, 0.2, 0.1, 0.0}; + assertFalse(ArrayUtils.isSorted(array)); } - @Test - public void testSubarrayBoolean() { - final boolean[] nullArray = null; - final boolean[] array = {true, true, false, true, false, true}; - final boolean[] leftSubarray = {true, true, false, true}; - final boolean[] midSubarray = {true, false, true, false}; - final boolean[] rightSubarray = {false, true, false, true}; - - assertTrue(ArrayUtils.isEquals(leftSubarray, ArrayUtils.subarray(array, 0, 4)), "0 start, mid end"); - assertTrue(ArrayUtils.isEquals(array, ArrayUtils.subarray(array, 0, array.length)), "0 start, length end"); - assertTrue(ArrayUtils.isEquals(midSubarray, ArrayUtils.subarray(array, 1, 5)), "mid start, mid end"); - assertTrue(ArrayUtils.isEquals(rightSubarray, ArrayUtils.subarray(array, 2, array.length)), - "mid start, length end"); - - assertNull(ArrayUtils.subarray(nullArray, 0, 3), "null input"); - assertEquals(ArrayUtils.EMPTY_BOOLEAN_ARRAY, ArrayUtils.subarray(ArrayUtils.EMPTY_BOOLEAN_ARRAY, 1, 2), - "empty array"); - assertEquals(ArrayUtils.EMPTY_BOOLEAN_ARRAY, ArrayUtils.subarray(array, 4, 2), "start > end"); - assertEquals(ArrayUtils.EMPTY_BOOLEAN_ARRAY, ArrayUtils.subarray(array, 3, 3), "start == end"); - assertTrue(ArrayUtils.isEquals(leftSubarray, ArrayUtils.subarray(array, -2, 4)), - "start undershoot, normal end"); - assertEquals(ArrayUtils.EMPTY_BOOLEAN_ARRAY, ArrayUtils.subarray(array, 33, 4), "start overshoot, any end"); - assertTrue(ArrayUtils.isEquals(rightSubarray, ArrayUtils.subarray(array, 2, 33)), - "normal start, end overshoot"); - assertTrue(ArrayUtils.isEquals(array, ArrayUtils.subarray(array, -2, 12)), "start undershoot, end overshoot"); + //----------------------------------------------------------------------- - // empty-return tests + @Test + public void testIsSortedFloat() { + float[] array = null; + assertTrue(ArrayUtils.isSorted(array)); - assertSame(ArrayUtils.EMPTY_BOOLEAN_ARRAY, ArrayUtils.subarray(ArrayUtils.EMPTY_BOOLEAN_ARRAY, 1, 2), - "empty array, object test"); - assertSame(ArrayUtils.EMPTY_BOOLEAN_ARRAY, ArrayUtils.subarray(array, 4, 1), "start > end, object test"); - assertSame(ArrayUtils.EMPTY_BOOLEAN_ARRAY, ArrayUtils.subarray(array, 3, 3), "start == end, object test"); - assertSame(ArrayUtils.EMPTY_BOOLEAN_ARRAY, ArrayUtils.subarray(array, 8733, 4), - "start overshoot, any end, object test"); + array = new float[]{0f}; + assertTrue(ArrayUtils.isSorted(array)); - // array type tests + array = new float[]{-1f, 0f, 0.1f, 0.2f}; + assertTrue(ArrayUtils.isSorted(array)); - assertSame(boolean.class, ArrayUtils.subarray(array, 2, 4).getClass().getComponentType(), "boolean type"); + array = new float[]{-1f, 0.2f, 0.1f, 0f}; + assertFalse(ArrayUtils.isSorted(array)); } - //----------------------------------------------------------------------- @Test - public void testSameLength() { - final Object[] nullArray = null; - final Object[] emptyArray = new Object[0]; - final Object[] oneArray = new Object[]{"pick"}; - final Object[] twoArray = new Object[]{"pick", "stick"}; - - assertTrue(ArrayUtils.isSameLength(nullArray, nullArray)); - assertTrue(ArrayUtils.isSameLength(nullArray, emptyArray)); - assertFalse(ArrayUtils.isSameLength(nullArray, oneArray)); - assertFalse(ArrayUtils.isSameLength(nullArray, twoArray)); + public void testIsSortedInt() { + int[] array = null; + assertTrue(ArrayUtils.isSorted(array)); - assertTrue(ArrayUtils.isSameLength(emptyArray, nullArray)); - assertTrue(ArrayUtils.isSameLength(emptyArray, emptyArray)); - assertFalse(ArrayUtils.isSameLength(emptyArray, oneArray)); - assertFalse(ArrayUtils.isSameLength(emptyArray, twoArray)); + array = new int[]{1}; + assertTrue(ArrayUtils.isSorted(array)); - assertFalse(ArrayUtils.isSameLength(oneArray, nullArray)); - assertFalse(ArrayUtils.isSameLength(oneArray, emptyArray)); - assertTrue(ArrayUtils.isSameLength(oneArray, oneArray)); - assertFalse(ArrayUtils.isSameLength(oneArray, twoArray)); + array = new int[]{1, 2, 3}; + assertTrue(ArrayUtils.isSorted(array)); - assertFalse(ArrayUtils.isSameLength(twoArray, nullArray)); - assertFalse(ArrayUtils.isSameLength(twoArray, emptyArray)); - assertFalse(ArrayUtils.isSameLength(twoArray, oneArray)); - assertTrue(ArrayUtils.isSameLength(twoArray, twoArray)); + array = new int[]{1, 3, 2}; + assertFalse(ArrayUtils.isSorted(array)); } @Test - public void testSameLengthBoolean() { - final boolean[] nullArray = null; - final boolean[] emptyArray = new boolean[0]; - final boolean[] oneArray = new boolean[]{true}; - final boolean[] twoArray = new boolean[]{true, false}; - - assertTrue(ArrayUtils.isSameLength(nullArray, nullArray)); - assertTrue(ArrayUtils.isSameLength(nullArray, emptyArray)); - assertFalse(ArrayUtils.isSameLength(nullArray, oneArray)); - assertFalse(ArrayUtils.isSameLength(nullArray, twoArray)); + public void testIsSortedLong() { + long[] array = null; + assertTrue(ArrayUtils.isSorted(array)); - assertTrue(ArrayUtils.isSameLength(emptyArray, nullArray)); - assertTrue(ArrayUtils.isSameLength(emptyArray, emptyArray)); - assertFalse(ArrayUtils.isSameLength(emptyArray, oneArray)); - assertFalse(ArrayUtils.isSameLength(emptyArray, twoArray)); + array = new long[]{0L}; + assertTrue(ArrayUtils.isSorted(array)); - assertFalse(ArrayUtils.isSameLength(oneArray, nullArray)); - assertFalse(ArrayUtils.isSameLength(oneArray, emptyArray)); - assertTrue(ArrayUtils.isSameLength(oneArray, oneArray)); - assertFalse(ArrayUtils.isSameLength(oneArray, twoArray)); + array = new long[]{-1L, 0L, 1L}; + assertTrue(ArrayUtils.isSorted(array)); - assertFalse(ArrayUtils.isSameLength(twoArray, nullArray)); - assertFalse(ArrayUtils.isSameLength(twoArray, emptyArray)); - assertFalse(ArrayUtils.isSameLength(twoArray, oneArray)); - assertTrue(ArrayUtils.isSameLength(twoArray, twoArray)); + array = new long[]{-1L, 1L, 0L}; + assertFalse(ArrayUtils.isSorted(array)); } @Test - public void testSameLengthLong() { - final long[] nullArray = null; - final long[] emptyArray = new long[0]; - final long[] oneArray = new long[]{0L}; - final long[] twoArray = new long[]{0L, 76L}; - - assertTrue(ArrayUtils.isSameLength(nullArray, nullArray)); - assertTrue(ArrayUtils.isSameLength(nullArray, emptyArray)); - assertFalse(ArrayUtils.isSameLength(nullArray, oneArray)); - assertFalse(ArrayUtils.isSameLength(nullArray, twoArray)); - - assertTrue(ArrayUtils.isSameLength(emptyArray, nullArray)); - assertTrue(ArrayUtils.isSameLength(emptyArray, emptyArray)); - assertFalse(ArrayUtils.isSameLength(emptyArray, oneArray)); - assertFalse(ArrayUtils.isSameLength(emptyArray, twoArray)); - - assertFalse(ArrayUtils.isSameLength(oneArray, nullArray)); - assertFalse(ArrayUtils.isSameLength(oneArray, emptyArray)); - assertTrue(ArrayUtils.isSameLength(oneArray, oneArray)); - assertFalse(ArrayUtils.isSameLength(oneArray, twoArray)); - - assertFalse(ArrayUtils.isSameLength(twoArray, nullArray)); - assertFalse(ArrayUtils.isSameLength(twoArray, emptyArray)); - assertFalse(ArrayUtils.isSameLength(twoArray, oneArray)); - assertTrue(ArrayUtils.isSameLength(twoArray, twoArray)); + public void testIsSortedNullComparator() { + assertThrows(IllegalArgumentException.class, () -> ArrayUtils.isSorted(null, null)); } @Test - public void testSameLengthInt() { - final int[] nullArray = null; - final int[] emptyArray = new int[0]; - final int[] oneArray = new int[]{4}; - final int[] twoArray = new int[]{5, 7}; - - assertTrue(ArrayUtils.isSameLength(nullArray, nullArray)); - assertTrue(ArrayUtils.isSameLength(nullArray, emptyArray)); - assertFalse(ArrayUtils.isSameLength(nullArray, oneArray)); - assertFalse(ArrayUtils.isSameLength(nullArray, twoArray)); + public void testIsSortedShort() { + short[] array = null; + assertTrue(ArrayUtils.isSorted(array)); - assertTrue(ArrayUtils.isSameLength(emptyArray, nullArray)); - assertTrue(ArrayUtils.isSameLength(emptyArray, emptyArray)); - assertFalse(ArrayUtils.isSameLength(emptyArray, oneArray)); - assertFalse(ArrayUtils.isSameLength(emptyArray, twoArray)); + array = new short[]{0}; + assertTrue(ArrayUtils.isSorted(array)); - assertFalse(ArrayUtils.isSameLength(oneArray, nullArray)); - assertFalse(ArrayUtils.isSameLength(oneArray, emptyArray)); - assertTrue(ArrayUtils.isSameLength(oneArray, oneArray)); - assertFalse(ArrayUtils.isSameLength(oneArray, twoArray)); + array = new short[]{-1, 0, 1}; + assertTrue(ArrayUtils.isSorted(array)); - assertFalse(ArrayUtils.isSameLength(twoArray, nullArray)); - assertFalse(ArrayUtils.isSameLength(twoArray, emptyArray)); - assertFalse(ArrayUtils.isSameLength(twoArray, oneArray)); - assertTrue(ArrayUtils.isSameLength(twoArray, twoArray)); + array = new short[]{-1, 1, 0}; + assertFalse(ArrayUtils.isSorted(array)); } @Test - public void testSameLengthShort() { - final short[] nullArray = null; - final short[] emptyArray = new short[0]; - final short[] oneArray = new short[]{4}; - final short[] twoArray = new short[]{6, 8}; + public void testLastIndexOf() { + final Object[] array = new Object[]{"0", "1", "2", "3", null, "0"}; + assertEquals(-1, ArrayUtils.lastIndexOf(null, null)); + assertEquals(-1, ArrayUtils.lastIndexOf(null, "0")); + assertEquals(5, ArrayUtils.lastIndexOf(array, "0")); + assertEquals(1, ArrayUtils.lastIndexOf(array, "1")); + assertEquals(2, ArrayUtils.lastIndexOf(array, "2")); + assertEquals(3, ArrayUtils.lastIndexOf(array, "3")); + assertEquals(4, ArrayUtils.lastIndexOf(array, null)); + assertEquals(-1, ArrayUtils.lastIndexOf(array, "notInArray")); + } - assertTrue(ArrayUtils.isSameLength(nullArray, nullArray)); - assertTrue(ArrayUtils.isSameLength(nullArray, emptyArray)); - assertFalse(ArrayUtils.isSameLength(nullArray, oneArray)); - assertFalse(ArrayUtils.isSameLength(nullArray, twoArray)); + @Test + public void testLastIndexOfBoolean() { + boolean[] array = null; + assertEquals(-1, ArrayUtils.lastIndexOf(array, true)); + array = new boolean[0]; + assertEquals(-1, ArrayUtils.lastIndexOf(array, true)); + array = new boolean[]{true, false, true}; + assertEquals(2, ArrayUtils.lastIndexOf(array, true)); + assertEquals(1, ArrayUtils.lastIndexOf(array, false)); + array = new boolean[]{true, true}; + assertEquals(-1, ArrayUtils.lastIndexOf(array, false)); + } - assertTrue(ArrayUtils.isSameLength(emptyArray, nullArray)); - assertTrue(ArrayUtils.isSameLength(emptyArray, emptyArray)); - assertFalse(ArrayUtils.isSameLength(emptyArray, oneArray)); - assertFalse(ArrayUtils.isSameLength(emptyArray, twoArray)); - - assertFalse(ArrayUtils.isSameLength(oneArray, nullArray)); - assertFalse(ArrayUtils.isSameLength(oneArray, emptyArray)); - assertTrue(ArrayUtils.isSameLength(oneArray, oneArray)); - assertFalse(ArrayUtils.isSameLength(oneArray, twoArray)); - - assertFalse(ArrayUtils.isSameLength(twoArray, nullArray)); - assertFalse(ArrayUtils.isSameLength(twoArray, emptyArray)); - assertFalse(ArrayUtils.isSameLength(twoArray, oneArray)); - assertTrue(ArrayUtils.isSameLength(twoArray, twoArray)); + @Test + public void testLastIndexOfBooleanWithStartIndex() { + boolean[] array = null; + assertEquals(-1, ArrayUtils.lastIndexOf(array, true, 2)); + array = new boolean[0]; + assertEquals(-1, ArrayUtils.lastIndexOf(array, true, 2)); + array = new boolean[]{true, false, true}; + assertEquals(2, ArrayUtils.lastIndexOf(array, true, 2)); + assertEquals(0, ArrayUtils.lastIndexOf(array, true, 1)); + assertEquals(1, ArrayUtils.lastIndexOf(array, false, 2)); + assertEquals(-1, ArrayUtils.lastIndexOf(array, true, -1)); + array = new boolean[]{true, true}; + assertEquals(-1, ArrayUtils.lastIndexOf(array, false, 2)); + assertEquals(-1, ArrayUtils.lastIndexOf(array, true, -1)); } @Test - public void testSameLengthChar() { - final char[] nullArray = null; - final char[] emptyArray = new char[0]; - final char[] oneArray = new char[]{'f'}; - final char[] twoArray = new char[]{'d', 't'}; - - assertTrue(ArrayUtils.isSameLength(nullArray, nullArray)); - assertTrue(ArrayUtils.isSameLength(nullArray, emptyArray)); - assertFalse(ArrayUtils.isSameLength(nullArray, oneArray)); - assertFalse(ArrayUtils.isSameLength(nullArray, twoArray)); - - assertTrue(ArrayUtils.isSameLength(emptyArray, nullArray)); - assertTrue(ArrayUtils.isSameLength(emptyArray, emptyArray)); - assertFalse(ArrayUtils.isSameLength(emptyArray, oneArray)); - assertFalse(ArrayUtils.isSameLength(emptyArray, twoArray)); - - assertFalse(ArrayUtils.isSameLength(oneArray, nullArray)); - assertFalse(ArrayUtils.isSameLength(oneArray, emptyArray)); - assertTrue(ArrayUtils.isSameLength(oneArray, oneArray)); - assertFalse(ArrayUtils.isSameLength(oneArray, twoArray)); - - assertFalse(ArrayUtils.isSameLength(twoArray, nullArray)); - assertFalse(ArrayUtils.isSameLength(twoArray, emptyArray)); - assertFalse(ArrayUtils.isSameLength(twoArray, oneArray)); - assertTrue(ArrayUtils.isSameLength(twoArray, twoArray)); + public void testLastIndexOfByte() { + byte[] array = null; + assertEquals(-1, ArrayUtils.lastIndexOf(array, (byte) 0)); + array = new byte[]{0, 1, 2, 3, 0}; + assertEquals(4, ArrayUtils.lastIndexOf(array, (byte) 0)); + assertEquals(1, ArrayUtils.lastIndexOf(array, (byte) 1)); + assertEquals(2, ArrayUtils.lastIndexOf(array, (byte) 2)); + assertEquals(3, ArrayUtils.lastIndexOf(array, (byte) 3)); + assertEquals(-1, ArrayUtils.lastIndexOf(array, (byte) 99)); } @Test - public void testSameLengthByte() { - final byte[] nullArray = null; - final byte[] emptyArray = new byte[0]; - final byte[] oneArray = new byte[]{3}; - final byte[] twoArray = new byte[]{4, 6}; - - assertTrue(ArrayUtils.isSameLength(nullArray, nullArray)); - assertTrue(ArrayUtils.isSameLength(nullArray, emptyArray)); - assertFalse(ArrayUtils.isSameLength(nullArray, oneArray)); - assertFalse(ArrayUtils.isSameLength(nullArray, twoArray)); - - assertTrue(ArrayUtils.isSameLength(emptyArray, nullArray)); - assertTrue(ArrayUtils.isSameLength(emptyArray, emptyArray)); - assertFalse(ArrayUtils.isSameLength(emptyArray, oneArray)); - assertFalse(ArrayUtils.isSameLength(emptyArray, twoArray)); - - assertFalse(ArrayUtils.isSameLength(oneArray, nullArray)); - assertFalse(ArrayUtils.isSameLength(oneArray, emptyArray)); - assertTrue(ArrayUtils.isSameLength(oneArray, oneArray)); - assertFalse(ArrayUtils.isSameLength(oneArray, twoArray)); - - assertFalse(ArrayUtils.isSameLength(twoArray, nullArray)); - assertFalse(ArrayUtils.isSameLength(twoArray, emptyArray)); - assertFalse(ArrayUtils.isSameLength(twoArray, oneArray)); - assertTrue(ArrayUtils.isSameLength(twoArray, twoArray)); + public void testLastIndexOfByteWithStartIndex() { + byte[] array = null; + assertEquals(-1, ArrayUtils.lastIndexOf(array, (byte) 0, 2)); + array = new byte[]{0, 1, 2, 3, 0}; + assertEquals(0, ArrayUtils.lastIndexOf(array, (byte) 0, 2)); + assertEquals(1, ArrayUtils.lastIndexOf(array, (byte) 1, 2)); + assertEquals(2, ArrayUtils.lastIndexOf(array, (byte) 2, 2)); + assertEquals(-1, ArrayUtils.lastIndexOf(array, (byte) 3, 2)); + assertEquals(-1, ArrayUtils.lastIndexOf(array, (byte) 3, -1)); + assertEquals(-1, ArrayUtils.lastIndexOf(array, (byte) 99)); + assertEquals(4, ArrayUtils.lastIndexOf(array, (byte) 0, 88)); } @Test - public void testSameLengthDouble() { - final double[] nullArray = null; - final double[] emptyArray = new double[0]; - final double[] oneArray = new double[]{1.3d}; - final double[] twoArray = new double[]{4.5d, 6.3d}; - - assertTrue(ArrayUtils.isSameLength(nullArray, nullArray)); - assertTrue(ArrayUtils.isSameLength(nullArray, emptyArray)); - assertFalse(ArrayUtils.isSameLength(nullArray, oneArray)); - assertFalse(ArrayUtils.isSameLength(nullArray, twoArray)); - - assertTrue(ArrayUtils.isSameLength(emptyArray, nullArray)); - assertTrue(ArrayUtils.isSameLength(emptyArray, emptyArray)); - assertFalse(ArrayUtils.isSameLength(emptyArray, oneArray)); - assertFalse(ArrayUtils.isSameLength(emptyArray, twoArray)); + public void testLastIndexOfChar() { + char[] array = null; + assertEquals(-1, ArrayUtils.lastIndexOf(array, 'a')); + array = new char[]{'a', 'b', 'c', 'd', 'a'}; + assertEquals(4, ArrayUtils.lastIndexOf(array, 'a')); + assertEquals(1, ArrayUtils.lastIndexOf(array, 'b')); + assertEquals(2, ArrayUtils.lastIndexOf(array, 'c')); + assertEquals(3, ArrayUtils.lastIndexOf(array, 'd')); + assertEquals(-1, ArrayUtils.lastIndexOf(array, 'e')); + } - assertFalse(ArrayUtils.isSameLength(oneArray, nullArray)); - assertFalse(ArrayUtils.isSameLength(oneArray, emptyArray)); - assertTrue(ArrayUtils.isSameLength(oneArray, oneArray)); - assertFalse(ArrayUtils.isSameLength(oneArray, twoArray)); + @Test + public void testLastIndexOfCharWithStartIndex() { + char[] array = null; + assertEquals(-1, ArrayUtils.lastIndexOf(array, 'a', 2)); + array = new char[]{'a', 'b', 'c', 'd', 'a'}; + assertEquals(0, ArrayUtils.lastIndexOf(array, 'a', 2)); + assertEquals(1, ArrayUtils.lastIndexOf(array, 'b', 2)); + assertEquals(2, ArrayUtils.lastIndexOf(array, 'c', 2)); + assertEquals(-1, ArrayUtils.lastIndexOf(array, 'd', 2)); + assertEquals(-1, ArrayUtils.lastIndexOf(array, 'd', -1)); + assertEquals(-1, ArrayUtils.lastIndexOf(array, 'e')); + assertEquals(4, ArrayUtils.lastIndexOf(array, 'a', 88)); + } - assertFalse(ArrayUtils.isSameLength(twoArray, nullArray)); - assertFalse(ArrayUtils.isSameLength(twoArray, emptyArray)); - assertFalse(ArrayUtils.isSameLength(twoArray, oneArray)); - assertTrue(ArrayUtils.isSameLength(twoArray, twoArray)); + @SuppressWarnings("cast") + @Test + public void testLastIndexOfDouble() { + double[] array = null; + assertEquals(-1, ArrayUtils.lastIndexOf(array, (double) 0)); + array = new double[0]; + assertEquals(-1, ArrayUtils.lastIndexOf(array, (double) 0)); + array = new double[]{0, 1, 2, 3, 0}; + assertEquals(4, ArrayUtils.lastIndexOf(array, (double) 0)); + assertEquals(1, ArrayUtils.lastIndexOf(array, (double) 1)); + assertEquals(2, ArrayUtils.lastIndexOf(array, (double) 2)); + assertEquals(3, ArrayUtils.lastIndexOf(array, (double) 3)); + assertEquals(-1, ArrayUtils.lastIndexOf(array, (double) 99)); } + @SuppressWarnings("cast") @Test - public void testSameLengthFloat() { - final float[] nullArray = null; - final float[] emptyArray = new float[0]; - final float[] oneArray = new float[]{2.5f}; - final float[] twoArray = new float[]{6.4f, 5.8f}; + public void testLastIndexOfDoubleTolerance() { + double[] array = null; + assertEquals(-1, ArrayUtils.lastIndexOf(array, (double) 0, (double) 0)); + array = new double[0]; + assertEquals(-1, ArrayUtils.lastIndexOf(array, (double) 0, (double) 0)); + array = new double[]{0, 1, 2, 3, 0}; + assertEquals(4, ArrayUtils.lastIndexOf(array, (double) 0, 0.3)); + assertEquals(2, ArrayUtils.lastIndexOf(array, 2.2, 0.35)); + assertEquals(3, ArrayUtils.lastIndexOf(array, 4.15, 2.0)); + assertEquals(1, ArrayUtils.lastIndexOf(array, 1.00001324, 0.0001)); + } - assertTrue(ArrayUtils.isSameLength(nullArray, nullArray)); - assertTrue(ArrayUtils.isSameLength(nullArray, emptyArray)); - assertFalse(ArrayUtils.isSameLength(nullArray, oneArray)); - assertFalse(ArrayUtils.isSameLength(nullArray, twoArray)); + @SuppressWarnings("cast") + @Test + public void testLastIndexOfDoubleWithStartIndex() { + double[] array = null; + assertEquals(-1, ArrayUtils.lastIndexOf(array, (double) 0, 2)); + array = new double[0]; + assertEquals(-1, ArrayUtils.lastIndexOf(array, (double) 0, 2)); + array = new double[]{0, 1, 2, 3, 0}; + assertEquals(0, ArrayUtils.lastIndexOf(array, (double) 0, 2)); + assertEquals(1, ArrayUtils.lastIndexOf(array, (double) 1, 2)); + assertEquals(2, ArrayUtils.lastIndexOf(array, (double) 2, 2)); + assertEquals(-1, ArrayUtils.lastIndexOf(array, (double) 3, 2)); + assertEquals(-1, ArrayUtils.lastIndexOf(array, (double) 3, -1)); + assertEquals(-1, ArrayUtils.lastIndexOf(array, (double) 99)); + assertEquals(4, ArrayUtils.lastIndexOf(array, (double) 0, 88)); + } - assertTrue(ArrayUtils.isSameLength(emptyArray, nullArray)); - assertTrue(ArrayUtils.isSameLength(emptyArray, emptyArray)); - assertFalse(ArrayUtils.isSameLength(emptyArray, oneArray)); - assertFalse(ArrayUtils.isSameLength(emptyArray, twoArray)); + @SuppressWarnings("cast") + @Test + public void testLastIndexOfDoubleWithStartIndexTolerance() { + double[] array = null; + assertEquals(-1, ArrayUtils.lastIndexOf(array, (double) 0, 2, (double) 0)); + array = new double[0]; + assertEquals(-1, ArrayUtils.lastIndexOf(array, (double) 0, 2, (double) 0)); + array = new double[]{(double) 3}; + assertEquals(-1, ArrayUtils.lastIndexOf(array, (double) 1, 0, (double) 0)); + array = new double[]{0, 1, 2, 3, 0}; + assertEquals(4, ArrayUtils.lastIndexOf(array, (double) 0, 99, 0.3)); + assertEquals(0, ArrayUtils.lastIndexOf(array, (double) 0, 3, 0.3)); + assertEquals(2, ArrayUtils.lastIndexOf(array, 2.2, 3, 0.35)); + assertEquals(3, ArrayUtils.lastIndexOf(array, 4.15, array.length, 2.0)); + assertEquals(1, ArrayUtils.lastIndexOf(array, 1.00001324, array.length, 0.0001)); + assertEquals(-1, ArrayUtils.lastIndexOf(array, 4.15, -200, 2.0)); + } - assertFalse(ArrayUtils.isSameLength(oneArray, nullArray)); - assertFalse(ArrayUtils.isSameLength(oneArray, emptyArray)); - assertTrue(ArrayUtils.isSameLength(oneArray, oneArray)); - assertFalse(ArrayUtils.isSameLength(oneArray, twoArray)); + @SuppressWarnings("cast") + @Test + public void testLastIndexOfFloat() { + float[] array = null; + assertEquals(-1, ArrayUtils.lastIndexOf(array, (float) 0)); + array = new float[0]; + assertEquals(-1, ArrayUtils.lastIndexOf(array, (float) 0)); + array = new float[]{0, 1, 2, 3, 0}; + assertEquals(4, ArrayUtils.lastIndexOf(array, (float) 0)); + assertEquals(1, ArrayUtils.lastIndexOf(array, (float) 1)); + assertEquals(2, ArrayUtils.lastIndexOf(array, (float) 2)); + assertEquals(3, ArrayUtils.lastIndexOf(array, (float) 3)); + assertEquals(-1, ArrayUtils.lastIndexOf(array, (float) 99)); + } - assertFalse(ArrayUtils.isSameLength(twoArray, nullArray)); - assertFalse(ArrayUtils.isSameLength(twoArray, emptyArray)); - assertFalse(ArrayUtils.isSameLength(twoArray, oneArray)); - assertTrue(ArrayUtils.isSameLength(twoArray, twoArray)); + @SuppressWarnings("cast") + @Test + public void testLastIndexOfFloatWithStartIndex() { + float[] array = null; + assertEquals(-1, ArrayUtils.lastIndexOf(array, (float) 0, 2)); + array = new float[0]; + assertEquals(-1, ArrayUtils.lastIndexOf(array, (float) 0, 2)); + array = new float[]{0, 1, 2, 3, 0}; + assertEquals(0, ArrayUtils.lastIndexOf(array, (float) 0, 2)); + assertEquals(1, ArrayUtils.lastIndexOf(array, (float) 1, 2)); + assertEquals(2, ArrayUtils.lastIndexOf(array, (float) 2, 2)); + assertEquals(-1, ArrayUtils.lastIndexOf(array, (float) 3, 2)); + assertEquals(-1, ArrayUtils.lastIndexOf(array, (float) 3, -1)); + assertEquals(-1, ArrayUtils.lastIndexOf(array, (float) 99)); + assertEquals(4, ArrayUtils.lastIndexOf(array, (float) 0, 88)); } @Test - public void testSameLengthAll() { - final Object[] nullArrayObject = null; - final Object[] emptyArrayObject = new Object[0]; - final Object[] oneArrayObject = new Object[]{"pick"}; - final Object[] twoArrayObject = new Object[]{"pick", "stick"}; - final boolean[] nullArrayBoolean = null; - final boolean[] emptyArrayBoolean = new boolean[0]; - final boolean[] oneArrayBoolean = new boolean[]{true}; - final boolean[] twoArrayBoolean = new boolean[]{true, false}; - final long[] nullArrayLong = null; - final long[] emptyArrayLong = new long[0]; - final long[] oneArrayLong = new long[]{0L}; - final long[] twoArrayLong = new long[]{0L, 76L}; - final int[] nullArrayInt = null; - final int[] emptyArrayInt = new int[0]; - final int[] oneArrayInt = new int[]{4}; - final int[] twoArrayInt = new int[]{5, 7}; - final short[] nullArrayShort = null; - final short[] emptyArrayShort = new short[0]; - final short[] oneArrayShort = new short[]{4}; - final short[] twoArrayShort = new short[]{6, 8}; - final char[] nullArrayChar = null; - final char[] emptyArrayChar = new char[0]; - final char[] oneArrayChar = new char[]{'f'}; - final char[] twoArrayChar = new char[]{'d', 't'}; - final byte[] nullArrayByte = null; - final byte[] emptyArrayByte = new byte[0]; - final byte[] oneArrayByte = new byte[]{3}; - final byte[] twoArrayByte = new byte[]{4, 6}; - final double[] nullArrayDouble = null; - final double[] emptyArrayDouble = new double[0]; - final double[] oneArrayDouble = new double[]{1.3d}; - final double[] twoArrayDouble = new double[]{4.5d, 6.3d}; - final float[] nullArrayFloat = null; - final float[] emptyArrayFloat = new float[0]; - final float[] oneArrayFloat = new float[]{2.5f}; - final float[] twoArrayFloat = new float[]{6.4f, 5.8f}; - assertTrue(ArrayUtils.isSameLength(nullArrayObject, nullArrayObject)); - assertTrue(ArrayUtils.isSameLength(nullArrayObject, nullArrayBoolean)); - assertTrue(ArrayUtils.isSameLength(nullArrayObject, nullArrayLong)); - assertTrue(ArrayUtils.isSameLength(nullArrayObject, nullArrayInt)); - assertTrue(ArrayUtils.isSameLength(nullArrayObject, nullArrayShort)); - assertTrue(ArrayUtils.isSameLength(nullArrayObject, nullArrayChar)); - assertTrue(ArrayUtils.isSameLength(nullArrayObject, nullArrayByte)); - assertTrue(ArrayUtils.isSameLength(nullArrayObject, nullArrayDouble)); - assertTrue(ArrayUtils.isSameLength(nullArrayObject, nullArrayFloat)); - assertTrue(ArrayUtils.isSameLength(nullArrayBoolean, nullArrayObject)); - assertTrue(ArrayUtils.isSameLength(nullArrayBoolean, nullArrayBoolean)); - assertTrue(ArrayUtils.isSameLength(nullArrayBoolean, nullArrayLong)); - assertTrue(ArrayUtils.isSameLength(nullArrayBoolean, nullArrayInt)); - assertTrue(ArrayUtils.isSameLength(nullArrayBoolean, nullArrayShort)); - assertTrue(ArrayUtils.isSameLength(nullArrayBoolean, nullArrayChar)); - assertTrue(ArrayUtils.isSameLength(nullArrayBoolean, nullArrayByte)); - assertTrue(ArrayUtils.isSameLength(nullArrayBoolean, nullArrayDouble)); - assertTrue(ArrayUtils.isSameLength(nullArrayBoolean, nullArrayFloat)); - assertTrue(ArrayUtils.isSameLength(nullArrayLong, nullArrayObject)); - assertTrue(ArrayUtils.isSameLength(nullArrayLong, nullArrayBoolean)); - assertTrue(ArrayUtils.isSameLength(nullArrayLong, nullArrayLong)); - assertTrue(ArrayUtils.isSameLength(nullArrayLong, nullArrayInt)); - assertTrue(ArrayUtils.isSameLength(nullArrayLong, nullArrayShort)); - assertTrue(ArrayUtils.isSameLength(nullArrayLong, nullArrayChar)); - assertTrue(ArrayUtils.isSameLength(nullArrayLong, nullArrayByte)); - assertTrue(ArrayUtils.isSameLength(nullArrayLong, nullArrayDouble)); - assertTrue(ArrayUtils.isSameLength(nullArrayLong, nullArrayFloat)); - assertTrue(ArrayUtils.isSameLength(nullArrayInt, nullArrayObject)); - assertTrue(ArrayUtils.isSameLength(nullArrayInt, nullArrayBoolean)); - assertTrue(ArrayUtils.isSameLength(nullArrayInt, nullArrayLong)); - assertTrue(ArrayUtils.isSameLength(nullArrayInt, nullArrayInt)); - assertTrue(ArrayUtils.isSameLength(nullArrayInt, nullArrayShort)); - assertTrue(ArrayUtils.isSameLength(nullArrayInt, nullArrayChar)); - assertTrue(ArrayUtils.isSameLength(nullArrayInt, nullArrayByte)); - assertTrue(ArrayUtils.isSameLength(nullArrayInt, nullArrayDouble)); - assertTrue(ArrayUtils.isSameLength(nullArrayInt, nullArrayFloat)); - assertTrue(ArrayUtils.isSameLength(nullArrayShort, nullArrayObject)); - assertTrue(ArrayUtils.isSameLength(nullArrayShort, nullArrayBoolean)); - assertTrue(ArrayUtils.isSameLength(nullArrayShort, nullArrayLong)); - assertTrue(ArrayUtils.isSameLength(nullArrayShort, nullArrayInt)); - assertTrue(ArrayUtils.isSameLength(nullArrayShort, nullArrayShort)); - assertTrue(ArrayUtils.isSameLength(nullArrayShort, nullArrayChar)); - assertTrue(ArrayUtils.isSameLength(nullArrayShort, nullArrayByte)); - assertTrue(ArrayUtils.isSameLength(nullArrayShort, nullArrayDouble)); - assertTrue(ArrayUtils.isSameLength(nullArrayShort, nullArrayFloat)); - assertTrue(ArrayUtils.isSameLength(nullArrayChar, nullArrayObject)); - assertTrue(ArrayUtils.isSameLength(nullArrayChar, nullArrayBoolean)); - assertTrue(ArrayUtils.isSameLength(nullArrayChar, nullArrayLong)); - assertTrue(ArrayUtils.isSameLength(nullArrayChar, nullArrayInt)); - assertTrue(ArrayUtils.isSameLength(nullArrayChar, nullArrayShort)); - assertTrue(ArrayUtils.isSameLength(nullArrayChar, nullArrayChar)); - assertTrue(ArrayUtils.isSameLength(nullArrayChar, nullArrayByte)); - assertTrue(ArrayUtils.isSameLength(nullArrayChar, nullArrayDouble)); - assertTrue(ArrayUtils.isSameLength(nullArrayChar, nullArrayFloat)); - assertTrue(ArrayUtils.isSameLength(nullArrayByte, nullArrayObject)); - assertTrue(ArrayUtils.isSameLength(nullArrayByte, nullArrayBoolean)); - assertTrue(ArrayUtils.isSameLength(nullArrayByte, nullArrayLong)); - assertTrue(ArrayUtils.isSameLength(nullArrayByte, nullArrayInt)); - assertTrue(ArrayUtils.isSameLength(nullArrayByte, nullArrayShort)); - assertTrue(ArrayUtils.isSameLength(nullArrayByte, nullArrayChar)); - assertTrue(ArrayUtils.isSameLength(nullArrayByte, nullArrayByte)); - assertTrue(ArrayUtils.isSameLength(nullArrayByte, nullArrayDouble)); - assertTrue(ArrayUtils.isSameLength(nullArrayByte, nullArrayFloat)); - assertTrue(ArrayUtils.isSameLength(nullArrayDouble, nullArrayObject)); - assertTrue(ArrayUtils.isSameLength(nullArrayDouble, nullArrayBoolean)); - assertTrue(ArrayUtils.isSameLength(nullArrayDouble, nullArrayLong)); - assertTrue(ArrayUtils.isSameLength(nullArrayDouble, nullArrayInt)); - assertTrue(ArrayUtils.isSameLength(nullArrayDouble, nullArrayShort)); - assertTrue(ArrayUtils.isSameLength(nullArrayDouble, nullArrayChar)); - assertTrue(ArrayUtils.isSameLength(nullArrayDouble, nullArrayByte)); - assertTrue(ArrayUtils.isSameLength(nullArrayDouble, nullArrayDouble)); - assertTrue(ArrayUtils.isSameLength(nullArrayDouble, nullArrayFloat)); - assertTrue(ArrayUtils.isSameLength(nullArrayFloat, nullArrayObject)); - assertTrue(ArrayUtils.isSameLength(nullArrayFloat, nullArrayBoolean)); - assertTrue(ArrayUtils.isSameLength(nullArrayFloat, nullArrayLong)); - assertTrue(ArrayUtils.isSameLength(nullArrayFloat, nullArrayInt)); - assertTrue(ArrayUtils.isSameLength(nullArrayFloat, nullArrayShort)); - assertTrue(ArrayUtils.isSameLength(nullArrayFloat, nullArrayChar)); - assertTrue(ArrayUtils.isSameLength(nullArrayFloat, nullArrayByte)); - assertTrue(ArrayUtils.isSameLength(nullArrayFloat, nullArrayDouble)); - assertTrue(ArrayUtils.isSameLength(nullArrayFloat, nullArrayFloat)); - assertTrue(ArrayUtils.isSameLength(nullArrayObject, emptyArrayObject)); - assertTrue(ArrayUtils.isSameLength(nullArrayObject, emptyArrayBoolean)); - assertTrue(ArrayUtils.isSameLength(nullArrayObject, emptyArrayLong)); - assertTrue(ArrayUtils.isSameLength(nullArrayObject, emptyArrayInt)); - assertTrue(ArrayUtils.isSameLength(nullArrayObject, emptyArrayShort)); - assertTrue(ArrayUtils.isSameLength(nullArrayObject, emptyArrayChar)); - assertTrue(ArrayUtils.isSameLength(nullArrayObject, emptyArrayByte)); - assertTrue(ArrayUtils.isSameLength(nullArrayObject, emptyArrayDouble)); - assertTrue(ArrayUtils.isSameLength(nullArrayObject, emptyArrayFloat)); - assertTrue(ArrayUtils.isSameLength(nullArrayBoolean, emptyArrayObject)); - assertTrue(ArrayUtils.isSameLength(nullArrayBoolean, emptyArrayBoolean)); - assertTrue(ArrayUtils.isSameLength(nullArrayBoolean, emptyArrayLong)); - assertTrue(ArrayUtils.isSameLength(nullArrayBoolean, emptyArrayInt)); - assertTrue(ArrayUtils.isSameLength(nullArrayBoolean, emptyArrayShort)); - assertTrue(ArrayUtils.isSameLength(nullArrayBoolean, emptyArrayChar)); - assertTrue(ArrayUtils.isSameLength(nullArrayBoolean, emptyArrayByte)); - assertTrue(ArrayUtils.isSameLength(nullArrayBoolean, emptyArrayDouble)); - assertTrue(ArrayUtils.isSameLength(nullArrayBoolean, emptyArrayFloat)); - assertTrue(ArrayUtils.isSameLength(nullArrayLong, emptyArrayObject)); - assertTrue(ArrayUtils.isSameLength(nullArrayLong, emptyArrayBoolean)); - assertTrue(ArrayUtils.isSameLength(nullArrayLong, emptyArrayLong)); - assertTrue(ArrayUtils.isSameLength(nullArrayLong, emptyArrayInt)); - assertTrue(ArrayUtils.isSameLength(nullArrayLong, emptyArrayShort)); - assertTrue(ArrayUtils.isSameLength(nullArrayLong, emptyArrayChar)); - assertTrue(ArrayUtils.isSameLength(nullArrayLong, emptyArrayByte)); - assertTrue(ArrayUtils.isSameLength(nullArrayLong, emptyArrayDouble)); - assertTrue(ArrayUtils.isSameLength(nullArrayLong, emptyArrayFloat)); - assertTrue(ArrayUtils.isSameLength(nullArrayInt, emptyArrayObject)); - assertTrue(ArrayUtils.isSameLength(nullArrayInt, emptyArrayBoolean)); - assertTrue(ArrayUtils.isSameLength(nullArrayInt, emptyArrayLong)); - assertTrue(ArrayUtils.isSameLength(nullArrayInt, emptyArrayInt)); - assertTrue(ArrayUtils.isSameLength(nullArrayInt, emptyArrayShort)); - assertTrue(ArrayUtils.isSameLength(nullArrayInt, emptyArrayChar)); - assertTrue(ArrayUtils.isSameLength(nullArrayInt, emptyArrayByte)); - assertTrue(ArrayUtils.isSameLength(nullArrayInt, emptyArrayDouble)); - assertTrue(ArrayUtils.isSameLength(nullArrayInt, emptyArrayFloat)); - assertTrue(ArrayUtils.isSameLength(nullArrayShort, emptyArrayObject)); - assertTrue(ArrayUtils.isSameLength(nullArrayShort, emptyArrayBoolean)); - assertTrue(ArrayUtils.isSameLength(nullArrayShort, emptyArrayLong)); - assertTrue(ArrayUtils.isSameLength(nullArrayShort, emptyArrayInt)); - assertTrue(ArrayUtils.isSameLength(nullArrayShort, emptyArrayShort)); - assertTrue(ArrayUtils.isSameLength(nullArrayShort, emptyArrayChar)); - assertTrue(ArrayUtils.isSameLength(nullArrayShort, emptyArrayByte)); - assertTrue(ArrayUtils.isSameLength(nullArrayShort, emptyArrayDouble)); - assertTrue(ArrayUtils.isSameLength(nullArrayShort, emptyArrayFloat)); - assertTrue(ArrayUtils.isSameLength(nullArrayChar, emptyArrayObject)); - assertTrue(ArrayUtils.isSameLength(nullArrayChar, emptyArrayBoolean)); - assertTrue(ArrayUtils.isSameLength(nullArrayChar, emptyArrayLong)); - assertTrue(ArrayUtils.isSameLength(nullArrayChar, emptyArrayInt)); - assertTrue(ArrayUtils.isSameLength(nullArrayChar, emptyArrayShort)); - assertTrue(ArrayUtils.isSameLength(nullArrayChar, emptyArrayChar)); - assertTrue(ArrayUtils.isSameLength(nullArrayChar, emptyArrayByte)); - assertTrue(ArrayUtils.isSameLength(nullArrayChar, emptyArrayDouble)); - assertTrue(ArrayUtils.isSameLength(nullArrayChar, emptyArrayFloat)); - assertTrue(ArrayUtils.isSameLength(nullArrayByte, emptyArrayObject)); - assertTrue(ArrayUtils.isSameLength(nullArrayByte, emptyArrayBoolean)); - assertTrue(ArrayUtils.isSameLength(nullArrayByte, emptyArrayLong)); - assertTrue(ArrayUtils.isSameLength(nullArrayByte, emptyArrayInt)); - assertTrue(ArrayUtils.isSameLength(nullArrayByte, emptyArrayShort)); - assertTrue(ArrayUtils.isSameLength(nullArrayByte, emptyArrayChar)); - assertTrue(ArrayUtils.isSameLength(nullArrayByte, emptyArrayByte)); - assertTrue(ArrayUtils.isSameLength(nullArrayByte, emptyArrayDouble)); - assertTrue(ArrayUtils.isSameLength(nullArrayByte, emptyArrayFloat)); - assertTrue(ArrayUtils.isSameLength(nullArrayDouble, emptyArrayObject)); - assertTrue(ArrayUtils.isSameLength(nullArrayDouble, emptyArrayBoolean)); - assertTrue(ArrayUtils.isSameLength(nullArrayDouble, emptyArrayLong)); - assertTrue(ArrayUtils.isSameLength(nullArrayDouble, emptyArrayInt)); - assertTrue(ArrayUtils.isSameLength(nullArrayDouble, emptyArrayShort)); - assertTrue(ArrayUtils.isSameLength(nullArrayDouble, emptyArrayChar)); - assertTrue(ArrayUtils.isSameLength(nullArrayDouble, emptyArrayByte)); - assertTrue(ArrayUtils.isSameLength(nullArrayDouble, emptyArrayDouble)); - assertTrue(ArrayUtils.isSameLength(nullArrayDouble, emptyArrayFloat)); - assertTrue(ArrayUtils.isSameLength(nullArrayFloat, emptyArrayObject)); - assertTrue(ArrayUtils.isSameLength(nullArrayFloat, emptyArrayBoolean)); - assertTrue(ArrayUtils.isSameLength(nullArrayFloat, emptyArrayLong)); - assertTrue(ArrayUtils.isSameLength(nullArrayFloat, emptyArrayInt)); - assertTrue(ArrayUtils.isSameLength(nullArrayFloat, emptyArrayShort)); - assertTrue(ArrayUtils.isSameLength(nullArrayFloat, emptyArrayChar)); - assertTrue(ArrayUtils.isSameLength(nullArrayFloat, emptyArrayByte)); - assertTrue(ArrayUtils.isSameLength(nullArrayFloat, emptyArrayDouble)); - assertTrue(ArrayUtils.isSameLength(nullArrayFloat, emptyArrayFloat)); - assertFalse(ArrayUtils.isSameLength(nullArrayObject, oneArrayObject)); - assertFalse(ArrayUtils.isSameLength(nullArrayObject, oneArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(nullArrayObject, oneArrayLong)); - assertFalse(ArrayUtils.isSameLength(nullArrayObject, oneArrayInt)); - assertFalse(ArrayUtils.isSameLength(nullArrayObject, oneArrayShort)); - assertFalse(ArrayUtils.isSameLength(nullArrayObject, oneArrayChar)); - assertFalse(ArrayUtils.isSameLength(nullArrayObject, oneArrayByte)); - assertFalse(ArrayUtils.isSameLength(nullArrayObject, oneArrayDouble)); - assertFalse(ArrayUtils.isSameLength(nullArrayObject, oneArrayFloat)); - assertFalse(ArrayUtils.isSameLength(nullArrayBoolean, oneArrayObject)); - assertFalse(ArrayUtils.isSameLength(nullArrayBoolean, oneArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(nullArrayBoolean, oneArrayLong)); - assertFalse(ArrayUtils.isSameLength(nullArrayBoolean, oneArrayInt)); - assertFalse(ArrayUtils.isSameLength(nullArrayBoolean, oneArrayShort)); - assertFalse(ArrayUtils.isSameLength(nullArrayBoolean, oneArrayChar)); - assertFalse(ArrayUtils.isSameLength(nullArrayBoolean, oneArrayByte)); - assertFalse(ArrayUtils.isSameLength(nullArrayBoolean, oneArrayDouble)); - assertFalse(ArrayUtils.isSameLength(nullArrayBoolean, oneArrayFloat)); - assertFalse(ArrayUtils.isSameLength(nullArrayLong, oneArrayObject)); - assertFalse(ArrayUtils.isSameLength(nullArrayLong, oneArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(nullArrayLong, oneArrayLong)); - assertFalse(ArrayUtils.isSameLength(nullArrayLong, oneArrayInt)); - assertFalse(ArrayUtils.isSameLength(nullArrayLong, oneArrayShort)); - assertFalse(ArrayUtils.isSameLength(nullArrayLong, oneArrayChar)); - assertFalse(ArrayUtils.isSameLength(nullArrayLong, oneArrayByte)); - assertFalse(ArrayUtils.isSameLength(nullArrayLong, oneArrayDouble)); - assertFalse(ArrayUtils.isSameLength(nullArrayLong, oneArrayFloat)); - assertFalse(ArrayUtils.isSameLength(nullArrayInt, oneArrayObject)); - assertFalse(ArrayUtils.isSameLength(nullArrayInt, oneArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(nullArrayInt, oneArrayLong)); - assertFalse(ArrayUtils.isSameLength(nullArrayInt, oneArrayInt)); - assertFalse(ArrayUtils.isSameLength(nullArrayInt, oneArrayShort)); - assertFalse(ArrayUtils.isSameLength(nullArrayInt, oneArrayChar)); - assertFalse(ArrayUtils.isSameLength(nullArrayInt, oneArrayByte)); - assertFalse(ArrayUtils.isSameLength(nullArrayInt, oneArrayDouble)); - assertFalse(ArrayUtils.isSameLength(nullArrayInt, oneArrayFloat)); - assertFalse(ArrayUtils.isSameLength(nullArrayShort, oneArrayObject)); - assertFalse(ArrayUtils.isSameLength(nullArrayShort, oneArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(nullArrayShort, oneArrayLong)); - assertFalse(ArrayUtils.isSameLength(nullArrayShort, oneArrayInt)); - assertFalse(ArrayUtils.isSameLength(nullArrayShort, oneArrayShort)); - assertFalse(ArrayUtils.isSameLength(nullArrayShort, oneArrayChar)); - assertFalse(ArrayUtils.isSameLength(nullArrayShort, oneArrayByte)); - assertFalse(ArrayUtils.isSameLength(nullArrayShort, oneArrayDouble)); - assertFalse(ArrayUtils.isSameLength(nullArrayShort, oneArrayFloat)); - assertFalse(ArrayUtils.isSameLength(nullArrayChar, oneArrayObject)); - assertFalse(ArrayUtils.isSameLength(nullArrayChar, oneArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(nullArrayChar, oneArrayLong)); - assertFalse(ArrayUtils.isSameLength(nullArrayChar, oneArrayInt)); - assertFalse(ArrayUtils.isSameLength(nullArrayChar, oneArrayShort)); - assertFalse(ArrayUtils.isSameLength(nullArrayChar, oneArrayChar)); - assertFalse(ArrayUtils.isSameLength(nullArrayChar, oneArrayByte)); - assertFalse(ArrayUtils.isSameLength(nullArrayChar, oneArrayDouble)); - assertFalse(ArrayUtils.isSameLength(nullArrayChar, oneArrayFloat)); - assertFalse(ArrayUtils.isSameLength(nullArrayByte, oneArrayObject)); - assertFalse(ArrayUtils.isSameLength(nullArrayByte, oneArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(nullArrayByte, oneArrayLong)); - assertFalse(ArrayUtils.isSameLength(nullArrayByte, oneArrayInt)); - assertFalse(ArrayUtils.isSameLength(nullArrayByte, oneArrayShort)); - assertFalse(ArrayUtils.isSameLength(nullArrayByte, oneArrayChar)); - assertFalse(ArrayUtils.isSameLength(nullArrayByte, oneArrayByte)); - assertFalse(ArrayUtils.isSameLength(nullArrayByte, oneArrayDouble)); - assertFalse(ArrayUtils.isSameLength(nullArrayByte, oneArrayFloat)); - assertFalse(ArrayUtils.isSameLength(nullArrayDouble, oneArrayObject)); - assertFalse(ArrayUtils.isSameLength(nullArrayDouble, oneArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(nullArrayDouble, oneArrayLong)); - assertFalse(ArrayUtils.isSameLength(nullArrayDouble, oneArrayInt)); - assertFalse(ArrayUtils.isSameLength(nullArrayDouble, oneArrayShort)); - assertFalse(ArrayUtils.isSameLength(nullArrayDouble, oneArrayChar)); - assertFalse(ArrayUtils.isSameLength(nullArrayDouble, oneArrayByte)); - assertFalse(ArrayUtils.isSameLength(nullArrayDouble, oneArrayDouble)); - assertFalse(ArrayUtils.isSameLength(nullArrayDouble, oneArrayFloat)); - assertFalse(ArrayUtils.isSameLength(nullArrayFloat, oneArrayObject)); - assertFalse(ArrayUtils.isSameLength(nullArrayFloat, oneArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(nullArrayFloat, oneArrayLong)); - assertFalse(ArrayUtils.isSameLength(nullArrayFloat, oneArrayInt)); - assertFalse(ArrayUtils.isSameLength(nullArrayFloat, oneArrayShort)); - assertFalse(ArrayUtils.isSameLength(nullArrayFloat, oneArrayChar)); - assertFalse(ArrayUtils.isSameLength(nullArrayFloat, oneArrayByte)); - assertFalse(ArrayUtils.isSameLength(nullArrayFloat, oneArrayDouble)); - assertFalse(ArrayUtils.isSameLength(nullArrayFloat, oneArrayFloat)); - assertFalse(ArrayUtils.isSameLength(nullArrayObject, twoArrayObject)); - assertFalse(ArrayUtils.isSameLength(nullArrayObject, twoArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(nullArrayObject, twoArrayLong)); - assertFalse(ArrayUtils.isSameLength(nullArrayObject, twoArrayInt)); - assertFalse(ArrayUtils.isSameLength(nullArrayObject, twoArrayShort)); - assertFalse(ArrayUtils.isSameLength(nullArrayObject, twoArrayChar)); - assertFalse(ArrayUtils.isSameLength(nullArrayObject, twoArrayByte)); - assertFalse(ArrayUtils.isSameLength(nullArrayObject, twoArrayDouble)); - assertFalse(ArrayUtils.isSameLength(nullArrayObject, twoArrayFloat)); - assertFalse(ArrayUtils.isSameLength(nullArrayBoolean, twoArrayObject)); - assertFalse(ArrayUtils.isSameLength(nullArrayBoolean, twoArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(nullArrayBoolean, twoArrayLong)); - assertFalse(ArrayUtils.isSameLength(nullArrayBoolean, twoArrayInt)); - assertFalse(ArrayUtils.isSameLength(nullArrayBoolean, twoArrayShort)); - assertFalse(ArrayUtils.isSameLength(nullArrayBoolean, twoArrayChar)); - assertFalse(ArrayUtils.isSameLength(nullArrayBoolean, twoArrayByte)); - assertFalse(ArrayUtils.isSameLength(nullArrayBoolean, twoArrayDouble)); - assertFalse(ArrayUtils.isSameLength(nullArrayBoolean, twoArrayFloat)); - assertFalse(ArrayUtils.isSameLength(nullArrayLong, twoArrayObject)); - assertFalse(ArrayUtils.isSameLength(nullArrayLong, twoArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(nullArrayLong, twoArrayLong)); - assertFalse(ArrayUtils.isSameLength(nullArrayLong, twoArrayInt)); - assertFalse(ArrayUtils.isSameLength(nullArrayLong, twoArrayShort)); - assertFalse(ArrayUtils.isSameLength(nullArrayLong, twoArrayChar)); - assertFalse(ArrayUtils.isSameLength(nullArrayLong, twoArrayByte)); - assertFalse(ArrayUtils.isSameLength(nullArrayLong, twoArrayDouble)); - assertFalse(ArrayUtils.isSameLength(nullArrayLong, twoArrayFloat)); - assertFalse(ArrayUtils.isSameLength(nullArrayInt, twoArrayObject)); - assertFalse(ArrayUtils.isSameLength(nullArrayInt, twoArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(nullArrayInt, twoArrayLong)); - assertFalse(ArrayUtils.isSameLength(nullArrayInt, twoArrayInt)); - assertFalse(ArrayUtils.isSameLength(nullArrayInt, twoArrayShort)); - assertFalse(ArrayUtils.isSameLength(nullArrayInt, twoArrayChar)); - assertFalse(ArrayUtils.isSameLength(nullArrayInt, twoArrayByte)); - assertFalse(ArrayUtils.isSameLength(nullArrayInt, twoArrayDouble)); - assertFalse(ArrayUtils.isSameLength(nullArrayInt, twoArrayFloat)); - assertFalse(ArrayUtils.isSameLength(nullArrayShort, twoArrayObject)); - assertFalse(ArrayUtils.isSameLength(nullArrayShort, twoArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(nullArrayShort, twoArrayLong)); - assertFalse(ArrayUtils.isSameLength(nullArrayShort, twoArrayInt)); - assertFalse(ArrayUtils.isSameLength(nullArrayShort, twoArrayShort)); - assertFalse(ArrayUtils.isSameLength(nullArrayShort, twoArrayChar)); - assertFalse(ArrayUtils.isSameLength(nullArrayShort, twoArrayByte)); - assertFalse(ArrayUtils.isSameLength(nullArrayShort, twoArrayDouble)); - assertFalse(ArrayUtils.isSameLength(nullArrayShort, twoArrayFloat)); - assertFalse(ArrayUtils.isSameLength(nullArrayChar, twoArrayObject)); - assertFalse(ArrayUtils.isSameLength(nullArrayChar, twoArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(nullArrayChar, twoArrayLong)); - assertFalse(ArrayUtils.isSameLength(nullArrayChar, twoArrayInt)); - assertFalse(ArrayUtils.isSameLength(nullArrayChar, twoArrayShort)); - assertFalse(ArrayUtils.isSameLength(nullArrayChar, twoArrayChar)); - assertFalse(ArrayUtils.isSameLength(nullArrayChar, twoArrayByte)); - assertFalse(ArrayUtils.isSameLength(nullArrayChar, twoArrayDouble)); - assertFalse(ArrayUtils.isSameLength(nullArrayChar, twoArrayFloat)); - assertFalse(ArrayUtils.isSameLength(nullArrayByte, twoArrayObject)); - assertFalse(ArrayUtils.isSameLength(nullArrayByte, twoArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(nullArrayByte, twoArrayLong)); - assertFalse(ArrayUtils.isSameLength(nullArrayByte, twoArrayInt)); - assertFalse(ArrayUtils.isSameLength(nullArrayByte, twoArrayShort)); - assertFalse(ArrayUtils.isSameLength(nullArrayByte, twoArrayChar)); - assertFalse(ArrayUtils.isSameLength(nullArrayByte, twoArrayByte)); - assertFalse(ArrayUtils.isSameLength(nullArrayByte, twoArrayDouble)); - assertFalse(ArrayUtils.isSameLength(nullArrayByte, twoArrayFloat)); - assertFalse(ArrayUtils.isSameLength(nullArrayDouble, twoArrayObject)); - assertFalse(ArrayUtils.isSameLength(nullArrayDouble, twoArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(nullArrayDouble, twoArrayLong)); - assertFalse(ArrayUtils.isSameLength(nullArrayDouble, twoArrayInt)); - assertFalse(ArrayUtils.isSameLength(nullArrayDouble, twoArrayShort)); - assertFalse(ArrayUtils.isSameLength(nullArrayDouble, twoArrayChar)); - assertFalse(ArrayUtils.isSameLength(nullArrayDouble, twoArrayByte)); - assertFalse(ArrayUtils.isSameLength(nullArrayDouble, twoArrayDouble)); - assertFalse(ArrayUtils.isSameLength(nullArrayDouble, twoArrayFloat)); - assertFalse(ArrayUtils.isSameLength(nullArrayFloat, twoArrayObject)); - assertFalse(ArrayUtils.isSameLength(nullArrayFloat, twoArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(nullArrayFloat, twoArrayLong)); - assertFalse(ArrayUtils.isSameLength(nullArrayFloat, twoArrayInt)); - assertFalse(ArrayUtils.isSameLength(nullArrayFloat, twoArrayShort)); - assertFalse(ArrayUtils.isSameLength(nullArrayFloat, twoArrayChar)); - assertFalse(ArrayUtils.isSameLength(nullArrayFloat, twoArrayByte)); - assertFalse(ArrayUtils.isSameLength(nullArrayFloat, twoArrayDouble)); - assertFalse(ArrayUtils.isSameLength(nullArrayFloat, twoArrayFloat)); - assertTrue(ArrayUtils.isSameLength(emptyArrayObject, nullArrayObject)); - assertTrue(ArrayUtils.isSameLength(emptyArrayObject, nullArrayBoolean)); - assertTrue(ArrayUtils.isSameLength(emptyArrayObject, nullArrayLong)); - assertTrue(ArrayUtils.isSameLength(emptyArrayObject, nullArrayInt)); - assertTrue(ArrayUtils.isSameLength(emptyArrayObject, nullArrayShort)); - assertTrue(ArrayUtils.isSameLength(emptyArrayObject, nullArrayChar)); - assertTrue(ArrayUtils.isSameLength(emptyArrayObject, nullArrayByte)); - assertTrue(ArrayUtils.isSameLength(emptyArrayObject, nullArrayDouble)); - assertTrue(ArrayUtils.isSameLength(emptyArrayObject, nullArrayFloat)); - assertTrue(ArrayUtils.isSameLength(emptyArrayBoolean, nullArrayObject)); - assertTrue(ArrayUtils.isSameLength(emptyArrayBoolean, nullArrayBoolean)); - assertTrue(ArrayUtils.isSameLength(emptyArrayBoolean, nullArrayLong)); - assertTrue(ArrayUtils.isSameLength(emptyArrayBoolean, nullArrayInt)); - assertTrue(ArrayUtils.isSameLength(emptyArrayBoolean, nullArrayShort)); - assertTrue(ArrayUtils.isSameLength(emptyArrayBoolean, nullArrayChar)); - assertTrue(ArrayUtils.isSameLength(emptyArrayBoolean, nullArrayByte)); - assertTrue(ArrayUtils.isSameLength(emptyArrayBoolean, nullArrayDouble)); - assertTrue(ArrayUtils.isSameLength(emptyArrayBoolean, nullArrayFloat)); - assertTrue(ArrayUtils.isSameLength(emptyArrayLong, nullArrayObject)); - assertTrue(ArrayUtils.isSameLength(emptyArrayLong, nullArrayBoolean)); - assertTrue(ArrayUtils.isSameLength(emptyArrayLong, nullArrayLong)); - assertTrue(ArrayUtils.isSameLength(emptyArrayLong, nullArrayInt)); - assertTrue(ArrayUtils.isSameLength(emptyArrayLong, nullArrayShort)); - assertTrue(ArrayUtils.isSameLength(emptyArrayLong, nullArrayChar)); - assertTrue(ArrayUtils.isSameLength(emptyArrayLong, nullArrayByte)); - assertTrue(ArrayUtils.isSameLength(emptyArrayLong, nullArrayDouble)); - assertTrue(ArrayUtils.isSameLength(emptyArrayLong, nullArrayFloat)); - assertTrue(ArrayUtils.isSameLength(emptyArrayInt, nullArrayObject)); - assertTrue(ArrayUtils.isSameLength(emptyArrayInt, nullArrayBoolean)); - assertTrue(ArrayUtils.isSameLength(emptyArrayInt, nullArrayLong)); - assertTrue(ArrayUtils.isSameLength(emptyArrayInt, nullArrayInt)); - assertTrue(ArrayUtils.isSameLength(emptyArrayInt, nullArrayShort)); - assertTrue(ArrayUtils.isSameLength(emptyArrayInt, nullArrayChar)); - assertTrue(ArrayUtils.isSameLength(emptyArrayInt, nullArrayByte)); - assertTrue(ArrayUtils.isSameLength(emptyArrayInt, nullArrayDouble)); - assertTrue(ArrayUtils.isSameLength(emptyArrayInt, nullArrayFloat)); - assertTrue(ArrayUtils.isSameLength(emptyArrayShort, nullArrayObject)); - assertTrue(ArrayUtils.isSameLength(emptyArrayShort, nullArrayBoolean)); - assertTrue(ArrayUtils.isSameLength(emptyArrayShort, nullArrayLong)); - assertTrue(ArrayUtils.isSameLength(emptyArrayShort, nullArrayInt)); - assertTrue(ArrayUtils.isSameLength(emptyArrayShort, nullArrayShort)); - assertTrue(ArrayUtils.isSameLength(emptyArrayShort, nullArrayChar)); - assertTrue(ArrayUtils.isSameLength(emptyArrayShort, nullArrayByte)); - assertTrue(ArrayUtils.isSameLength(emptyArrayShort, nullArrayDouble)); - assertTrue(ArrayUtils.isSameLength(emptyArrayShort, nullArrayFloat)); - assertTrue(ArrayUtils.isSameLength(emptyArrayChar, nullArrayObject)); - assertTrue(ArrayUtils.isSameLength(emptyArrayChar, nullArrayBoolean)); - assertTrue(ArrayUtils.isSameLength(emptyArrayChar, nullArrayLong)); - assertTrue(ArrayUtils.isSameLength(emptyArrayChar, nullArrayInt)); - assertTrue(ArrayUtils.isSameLength(emptyArrayChar, nullArrayShort)); - assertTrue(ArrayUtils.isSameLength(emptyArrayChar, nullArrayChar)); - assertTrue(ArrayUtils.isSameLength(emptyArrayChar, nullArrayByte)); - assertTrue(ArrayUtils.isSameLength(emptyArrayChar, nullArrayDouble)); - assertTrue(ArrayUtils.isSameLength(emptyArrayChar, nullArrayFloat)); - assertTrue(ArrayUtils.isSameLength(emptyArrayByte, nullArrayObject)); - assertTrue(ArrayUtils.isSameLength(emptyArrayByte, nullArrayBoolean)); - assertTrue(ArrayUtils.isSameLength(emptyArrayByte, nullArrayLong)); - assertTrue(ArrayUtils.isSameLength(emptyArrayByte, nullArrayInt)); - assertTrue(ArrayUtils.isSameLength(emptyArrayByte, nullArrayShort)); - assertTrue(ArrayUtils.isSameLength(emptyArrayByte, nullArrayChar)); - assertTrue(ArrayUtils.isSameLength(emptyArrayByte, nullArrayByte)); - assertTrue(ArrayUtils.isSameLength(emptyArrayByte, nullArrayDouble)); - assertTrue(ArrayUtils.isSameLength(emptyArrayByte, nullArrayFloat)); - assertTrue(ArrayUtils.isSameLength(emptyArrayDouble, nullArrayObject)); - assertTrue(ArrayUtils.isSameLength(emptyArrayDouble, nullArrayBoolean)); - assertTrue(ArrayUtils.isSameLength(emptyArrayDouble, nullArrayLong)); - assertTrue(ArrayUtils.isSameLength(emptyArrayDouble, nullArrayInt)); - assertTrue(ArrayUtils.isSameLength(emptyArrayDouble, nullArrayShort)); - assertTrue(ArrayUtils.isSameLength(emptyArrayDouble, nullArrayChar)); - assertTrue(ArrayUtils.isSameLength(emptyArrayDouble, nullArrayByte)); - assertTrue(ArrayUtils.isSameLength(emptyArrayDouble, nullArrayDouble)); - assertTrue(ArrayUtils.isSameLength(emptyArrayDouble, nullArrayFloat)); - assertTrue(ArrayUtils.isSameLength(emptyArrayFloat, nullArrayObject)); - assertTrue(ArrayUtils.isSameLength(emptyArrayFloat, nullArrayBoolean)); - assertTrue(ArrayUtils.isSameLength(emptyArrayFloat, nullArrayLong)); - assertTrue(ArrayUtils.isSameLength(emptyArrayFloat, nullArrayInt)); - assertTrue(ArrayUtils.isSameLength(emptyArrayFloat, nullArrayShort)); - assertTrue(ArrayUtils.isSameLength(emptyArrayFloat, nullArrayChar)); - assertTrue(ArrayUtils.isSameLength(emptyArrayFloat, nullArrayByte)); - assertTrue(ArrayUtils.isSameLength(emptyArrayFloat, nullArrayDouble)); - assertTrue(ArrayUtils.isSameLength(emptyArrayFloat, nullArrayFloat)); - assertTrue(ArrayUtils.isSameLength(emptyArrayObject, emptyArrayObject)); - assertTrue(ArrayUtils.isSameLength(emptyArrayObject, emptyArrayBoolean)); - assertTrue(ArrayUtils.isSameLength(emptyArrayObject, emptyArrayLong)); - assertTrue(ArrayUtils.isSameLength(emptyArrayObject, emptyArrayInt)); - assertTrue(ArrayUtils.isSameLength(emptyArrayObject, emptyArrayShort)); - assertTrue(ArrayUtils.isSameLength(emptyArrayObject, emptyArrayChar)); - assertTrue(ArrayUtils.isSameLength(emptyArrayObject, emptyArrayByte)); - assertTrue(ArrayUtils.isSameLength(emptyArrayObject, emptyArrayDouble)); - assertTrue(ArrayUtils.isSameLength(emptyArrayObject, emptyArrayFloat)); - assertTrue(ArrayUtils.isSameLength(emptyArrayBoolean, emptyArrayObject)); - assertTrue(ArrayUtils.isSameLength(emptyArrayBoolean, emptyArrayBoolean)); - assertTrue(ArrayUtils.isSameLength(emptyArrayBoolean, emptyArrayLong)); - assertTrue(ArrayUtils.isSameLength(emptyArrayBoolean, emptyArrayInt)); - assertTrue(ArrayUtils.isSameLength(emptyArrayBoolean, emptyArrayShort)); - assertTrue(ArrayUtils.isSameLength(emptyArrayBoolean, emptyArrayChar)); - assertTrue(ArrayUtils.isSameLength(emptyArrayBoolean, emptyArrayByte)); - assertTrue(ArrayUtils.isSameLength(emptyArrayBoolean, emptyArrayDouble)); - assertTrue(ArrayUtils.isSameLength(emptyArrayBoolean, emptyArrayFloat)); - assertTrue(ArrayUtils.isSameLength(emptyArrayLong, emptyArrayObject)); - assertTrue(ArrayUtils.isSameLength(emptyArrayLong, emptyArrayBoolean)); - assertTrue(ArrayUtils.isSameLength(emptyArrayLong, emptyArrayLong)); - assertTrue(ArrayUtils.isSameLength(emptyArrayLong, emptyArrayInt)); - assertTrue(ArrayUtils.isSameLength(emptyArrayLong, emptyArrayShort)); - assertTrue(ArrayUtils.isSameLength(emptyArrayLong, emptyArrayChar)); - assertTrue(ArrayUtils.isSameLength(emptyArrayLong, emptyArrayByte)); - assertTrue(ArrayUtils.isSameLength(emptyArrayLong, emptyArrayDouble)); - assertTrue(ArrayUtils.isSameLength(emptyArrayLong, emptyArrayFloat)); - assertTrue(ArrayUtils.isSameLength(emptyArrayInt, emptyArrayObject)); - assertTrue(ArrayUtils.isSameLength(emptyArrayInt, emptyArrayBoolean)); - assertTrue(ArrayUtils.isSameLength(emptyArrayInt, emptyArrayLong)); - assertTrue(ArrayUtils.isSameLength(emptyArrayInt, emptyArrayInt)); - assertTrue(ArrayUtils.isSameLength(emptyArrayInt, emptyArrayShort)); - assertTrue(ArrayUtils.isSameLength(emptyArrayInt, emptyArrayChar)); - assertTrue(ArrayUtils.isSameLength(emptyArrayInt, emptyArrayByte)); - assertTrue(ArrayUtils.isSameLength(emptyArrayInt, emptyArrayDouble)); - assertTrue(ArrayUtils.isSameLength(emptyArrayInt, emptyArrayFloat)); - assertTrue(ArrayUtils.isSameLength(emptyArrayShort, emptyArrayObject)); - assertTrue(ArrayUtils.isSameLength(emptyArrayShort, emptyArrayBoolean)); - assertTrue(ArrayUtils.isSameLength(emptyArrayShort, emptyArrayLong)); - assertTrue(ArrayUtils.isSameLength(emptyArrayShort, emptyArrayInt)); - assertTrue(ArrayUtils.isSameLength(emptyArrayShort, emptyArrayShort)); - assertTrue(ArrayUtils.isSameLength(emptyArrayShort, emptyArrayChar)); - assertTrue(ArrayUtils.isSameLength(emptyArrayShort, emptyArrayByte)); - assertTrue(ArrayUtils.isSameLength(emptyArrayShort, emptyArrayDouble)); - assertTrue(ArrayUtils.isSameLength(emptyArrayShort, emptyArrayFloat)); - assertTrue(ArrayUtils.isSameLength(emptyArrayChar, emptyArrayObject)); - assertTrue(ArrayUtils.isSameLength(emptyArrayChar, emptyArrayBoolean)); - assertTrue(ArrayUtils.isSameLength(emptyArrayChar, emptyArrayLong)); - assertTrue(ArrayUtils.isSameLength(emptyArrayChar, emptyArrayInt)); - assertTrue(ArrayUtils.isSameLength(emptyArrayChar, emptyArrayShort)); - assertTrue(ArrayUtils.isSameLength(emptyArrayChar, emptyArrayChar)); - assertTrue(ArrayUtils.isSameLength(emptyArrayChar, emptyArrayByte)); - assertTrue(ArrayUtils.isSameLength(emptyArrayChar, emptyArrayDouble)); - assertTrue(ArrayUtils.isSameLength(emptyArrayChar, emptyArrayFloat)); - assertTrue(ArrayUtils.isSameLength(emptyArrayByte, emptyArrayObject)); - assertTrue(ArrayUtils.isSameLength(emptyArrayByte, emptyArrayBoolean)); - assertTrue(ArrayUtils.isSameLength(emptyArrayByte, emptyArrayLong)); - assertTrue(ArrayUtils.isSameLength(emptyArrayByte, emptyArrayInt)); - assertTrue(ArrayUtils.isSameLength(emptyArrayByte, emptyArrayShort)); - assertTrue(ArrayUtils.isSameLength(emptyArrayByte, emptyArrayChar)); - assertTrue(ArrayUtils.isSameLength(emptyArrayByte, emptyArrayByte)); - assertTrue(ArrayUtils.isSameLength(emptyArrayByte, emptyArrayDouble)); - assertTrue(ArrayUtils.isSameLength(emptyArrayByte, emptyArrayFloat)); - assertTrue(ArrayUtils.isSameLength(emptyArrayDouble, emptyArrayObject)); - assertTrue(ArrayUtils.isSameLength(emptyArrayDouble, emptyArrayBoolean)); - assertTrue(ArrayUtils.isSameLength(emptyArrayDouble, emptyArrayLong)); - assertTrue(ArrayUtils.isSameLength(emptyArrayDouble, emptyArrayInt)); - assertTrue(ArrayUtils.isSameLength(emptyArrayDouble, emptyArrayShort)); - assertTrue(ArrayUtils.isSameLength(emptyArrayDouble, emptyArrayChar)); - assertTrue(ArrayUtils.isSameLength(emptyArrayDouble, emptyArrayByte)); - assertTrue(ArrayUtils.isSameLength(emptyArrayDouble, emptyArrayDouble)); - assertTrue(ArrayUtils.isSameLength(emptyArrayDouble, emptyArrayFloat)); - assertTrue(ArrayUtils.isSameLength(emptyArrayFloat, emptyArrayObject)); - assertTrue(ArrayUtils.isSameLength(emptyArrayFloat, emptyArrayBoolean)); - assertTrue(ArrayUtils.isSameLength(emptyArrayFloat, emptyArrayLong)); - assertTrue(ArrayUtils.isSameLength(emptyArrayFloat, emptyArrayInt)); - assertTrue(ArrayUtils.isSameLength(emptyArrayFloat, emptyArrayShort)); - assertTrue(ArrayUtils.isSameLength(emptyArrayFloat, emptyArrayChar)); - assertTrue(ArrayUtils.isSameLength(emptyArrayFloat, emptyArrayByte)); - assertTrue(ArrayUtils.isSameLength(emptyArrayFloat, emptyArrayDouble)); - assertTrue(ArrayUtils.isSameLength(emptyArrayFloat, emptyArrayFloat)); - assertFalse(ArrayUtils.isSameLength(emptyArrayObject, oneArrayObject)); - assertFalse(ArrayUtils.isSameLength(emptyArrayObject, oneArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(emptyArrayObject, oneArrayLong)); - assertFalse(ArrayUtils.isSameLength(emptyArrayObject, oneArrayInt)); - assertFalse(ArrayUtils.isSameLength(emptyArrayObject, oneArrayShort)); - assertFalse(ArrayUtils.isSameLength(emptyArrayObject, oneArrayChar)); - assertFalse(ArrayUtils.isSameLength(emptyArrayObject, oneArrayByte)); - assertFalse(ArrayUtils.isSameLength(emptyArrayObject, oneArrayDouble)); - assertFalse(ArrayUtils.isSameLength(emptyArrayObject, oneArrayFloat)); - assertFalse(ArrayUtils.isSameLength(emptyArrayBoolean, oneArrayObject)); - assertFalse(ArrayUtils.isSameLength(emptyArrayBoolean, oneArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(emptyArrayBoolean, oneArrayLong)); - assertFalse(ArrayUtils.isSameLength(emptyArrayBoolean, oneArrayInt)); - assertFalse(ArrayUtils.isSameLength(emptyArrayBoolean, oneArrayShort)); - assertFalse(ArrayUtils.isSameLength(emptyArrayBoolean, oneArrayChar)); - assertFalse(ArrayUtils.isSameLength(emptyArrayBoolean, oneArrayByte)); - assertFalse(ArrayUtils.isSameLength(emptyArrayBoolean, oneArrayDouble)); - assertFalse(ArrayUtils.isSameLength(emptyArrayBoolean, oneArrayFloat)); - assertFalse(ArrayUtils.isSameLength(emptyArrayLong, oneArrayObject)); - assertFalse(ArrayUtils.isSameLength(emptyArrayLong, oneArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(emptyArrayLong, oneArrayLong)); - assertFalse(ArrayUtils.isSameLength(emptyArrayLong, oneArrayInt)); - assertFalse(ArrayUtils.isSameLength(emptyArrayLong, oneArrayShort)); - assertFalse(ArrayUtils.isSameLength(emptyArrayLong, oneArrayChar)); - assertFalse(ArrayUtils.isSameLength(emptyArrayLong, oneArrayByte)); - assertFalse(ArrayUtils.isSameLength(emptyArrayLong, oneArrayDouble)); - assertFalse(ArrayUtils.isSameLength(emptyArrayLong, oneArrayFloat)); - assertFalse(ArrayUtils.isSameLength(emptyArrayInt, oneArrayObject)); - assertFalse(ArrayUtils.isSameLength(emptyArrayInt, oneArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(emptyArrayInt, oneArrayLong)); - assertFalse(ArrayUtils.isSameLength(emptyArrayInt, oneArrayInt)); - assertFalse(ArrayUtils.isSameLength(emptyArrayInt, oneArrayShort)); - assertFalse(ArrayUtils.isSameLength(emptyArrayInt, oneArrayChar)); - assertFalse(ArrayUtils.isSameLength(emptyArrayInt, oneArrayByte)); - assertFalse(ArrayUtils.isSameLength(emptyArrayInt, oneArrayDouble)); - assertFalse(ArrayUtils.isSameLength(emptyArrayInt, oneArrayFloat)); - assertFalse(ArrayUtils.isSameLength(emptyArrayShort, oneArrayObject)); - assertFalse(ArrayUtils.isSameLength(emptyArrayShort, oneArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(emptyArrayShort, oneArrayLong)); - assertFalse(ArrayUtils.isSameLength(emptyArrayShort, oneArrayInt)); - assertFalse(ArrayUtils.isSameLength(emptyArrayShort, oneArrayShort)); - assertFalse(ArrayUtils.isSameLength(emptyArrayShort, oneArrayChar)); - assertFalse(ArrayUtils.isSameLength(emptyArrayShort, oneArrayByte)); - assertFalse(ArrayUtils.isSameLength(emptyArrayShort, oneArrayDouble)); - assertFalse(ArrayUtils.isSameLength(emptyArrayShort, oneArrayFloat)); - assertFalse(ArrayUtils.isSameLength(emptyArrayChar, oneArrayObject)); - assertFalse(ArrayUtils.isSameLength(emptyArrayChar, oneArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(emptyArrayChar, oneArrayLong)); - assertFalse(ArrayUtils.isSameLength(emptyArrayChar, oneArrayInt)); - assertFalse(ArrayUtils.isSameLength(emptyArrayChar, oneArrayShort)); - assertFalse(ArrayUtils.isSameLength(emptyArrayChar, oneArrayChar)); - assertFalse(ArrayUtils.isSameLength(emptyArrayChar, oneArrayByte)); - assertFalse(ArrayUtils.isSameLength(emptyArrayChar, oneArrayDouble)); - assertFalse(ArrayUtils.isSameLength(emptyArrayChar, oneArrayFloat)); - assertFalse(ArrayUtils.isSameLength(emptyArrayByte, oneArrayObject)); - assertFalse(ArrayUtils.isSameLength(emptyArrayByte, oneArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(emptyArrayByte, oneArrayLong)); - assertFalse(ArrayUtils.isSameLength(emptyArrayByte, oneArrayInt)); - assertFalse(ArrayUtils.isSameLength(emptyArrayByte, oneArrayShort)); - assertFalse(ArrayUtils.isSameLength(emptyArrayByte, oneArrayChar)); - assertFalse(ArrayUtils.isSameLength(emptyArrayByte, oneArrayByte)); - assertFalse(ArrayUtils.isSameLength(emptyArrayByte, oneArrayDouble)); - assertFalse(ArrayUtils.isSameLength(emptyArrayByte, oneArrayFloat)); - assertFalse(ArrayUtils.isSameLength(emptyArrayDouble, oneArrayObject)); - assertFalse(ArrayUtils.isSameLength(emptyArrayDouble, oneArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(emptyArrayDouble, oneArrayLong)); - assertFalse(ArrayUtils.isSameLength(emptyArrayDouble, oneArrayInt)); - assertFalse(ArrayUtils.isSameLength(emptyArrayDouble, oneArrayShort)); - assertFalse(ArrayUtils.isSameLength(emptyArrayDouble, oneArrayChar)); - assertFalse(ArrayUtils.isSameLength(emptyArrayDouble, oneArrayByte)); - assertFalse(ArrayUtils.isSameLength(emptyArrayDouble, oneArrayDouble)); - assertFalse(ArrayUtils.isSameLength(emptyArrayDouble, oneArrayFloat)); - assertFalse(ArrayUtils.isSameLength(emptyArrayFloat, oneArrayObject)); - assertFalse(ArrayUtils.isSameLength(emptyArrayFloat, oneArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(emptyArrayFloat, oneArrayLong)); - assertFalse(ArrayUtils.isSameLength(emptyArrayFloat, oneArrayInt)); - assertFalse(ArrayUtils.isSameLength(emptyArrayFloat, oneArrayShort)); - assertFalse(ArrayUtils.isSameLength(emptyArrayFloat, oneArrayChar)); - assertFalse(ArrayUtils.isSameLength(emptyArrayFloat, oneArrayByte)); - assertFalse(ArrayUtils.isSameLength(emptyArrayFloat, oneArrayDouble)); - assertFalse(ArrayUtils.isSameLength(emptyArrayFloat, oneArrayFloat)); - assertFalse(ArrayUtils.isSameLength(emptyArrayObject, twoArrayObject)); - assertFalse(ArrayUtils.isSameLength(emptyArrayObject, twoArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(emptyArrayObject, twoArrayLong)); - assertFalse(ArrayUtils.isSameLength(emptyArrayObject, twoArrayInt)); - assertFalse(ArrayUtils.isSameLength(emptyArrayObject, twoArrayShort)); - assertFalse(ArrayUtils.isSameLength(emptyArrayObject, twoArrayChar)); - assertFalse(ArrayUtils.isSameLength(emptyArrayObject, twoArrayByte)); - assertFalse(ArrayUtils.isSameLength(emptyArrayObject, twoArrayDouble)); - assertFalse(ArrayUtils.isSameLength(emptyArrayObject, twoArrayFloat)); - assertFalse(ArrayUtils.isSameLength(emptyArrayBoolean, twoArrayObject)); - assertFalse(ArrayUtils.isSameLength(emptyArrayBoolean, twoArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(emptyArrayBoolean, twoArrayLong)); - assertFalse(ArrayUtils.isSameLength(emptyArrayBoolean, twoArrayInt)); - assertFalse(ArrayUtils.isSameLength(emptyArrayBoolean, twoArrayShort)); - assertFalse(ArrayUtils.isSameLength(emptyArrayBoolean, twoArrayChar)); - assertFalse(ArrayUtils.isSameLength(emptyArrayBoolean, twoArrayByte)); - assertFalse(ArrayUtils.isSameLength(emptyArrayBoolean, twoArrayDouble)); - assertFalse(ArrayUtils.isSameLength(emptyArrayBoolean, twoArrayFloat)); - assertFalse(ArrayUtils.isSameLength(emptyArrayLong, twoArrayObject)); - assertFalse(ArrayUtils.isSameLength(emptyArrayLong, twoArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(emptyArrayLong, twoArrayLong)); - assertFalse(ArrayUtils.isSameLength(emptyArrayLong, twoArrayInt)); - assertFalse(ArrayUtils.isSameLength(emptyArrayLong, twoArrayShort)); - assertFalse(ArrayUtils.isSameLength(emptyArrayLong, twoArrayChar)); - assertFalse(ArrayUtils.isSameLength(emptyArrayLong, twoArrayByte)); - assertFalse(ArrayUtils.isSameLength(emptyArrayLong, twoArrayDouble)); - assertFalse(ArrayUtils.isSameLength(emptyArrayLong, twoArrayFloat)); - assertFalse(ArrayUtils.isSameLength(emptyArrayInt, twoArrayObject)); - assertFalse(ArrayUtils.isSameLength(emptyArrayInt, twoArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(emptyArrayInt, twoArrayLong)); - assertFalse(ArrayUtils.isSameLength(emptyArrayInt, twoArrayInt)); - assertFalse(ArrayUtils.isSameLength(emptyArrayInt, twoArrayShort)); - assertFalse(ArrayUtils.isSameLength(emptyArrayInt, twoArrayChar)); - assertFalse(ArrayUtils.isSameLength(emptyArrayInt, twoArrayByte)); - assertFalse(ArrayUtils.isSameLength(emptyArrayInt, twoArrayDouble)); - assertFalse(ArrayUtils.isSameLength(emptyArrayInt, twoArrayFloat)); - assertFalse(ArrayUtils.isSameLength(emptyArrayShort, twoArrayObject)); - assertFalse(ArrayUtils.isSameLength(emptyArrayShort, twoArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(emptyArrayShort, twoArrayLong)); - assertFalse(ArrayUtils.isSameLength(emptyArrayShort, twoArrayInt)); - assertFalse(ArrayUtils.isSameLength(emptyArrayShort, twoArrayShort)); - assertFalse(ArrayUtils.isSameLength(emptyArrayShort, twoArrayChar)); - assertFalse(ArrayUtils.isSameLength(emptyArrayShort, twoArrayByte)); - assertFalse(ArrayUtils.isSameLength(emptyArrayShort, twoArrayDouble)); - assertFalse(ArrayUtils.isSameLength(emptyArrayShort, twoArrayFloat)); - assertFalse(ArrayUtils.isSameLength(emptyArrayChar, twoArrayObject)); - assertFalse(ArrayUtils.isSameLength(emptyArrayChar, twoArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(emptyArrayChar, twoArrayLong)); - assertFalse(ArrayUtils.isSameLength(emptyArrayChar, twoArrayInt)); - assertFalse(ArrayUtils.isSameLength(emptyArrayChar, twoArrayShort)); - assertFalse(ArrayUtils.isSameLength(emptyArrayChar, twoArrayChar)); - assertFalse(ArrayUtils.isSameLength(emptyArrayChar, twoArrayByte)); - assertFalse(ArrayUtils.isSameLength(emptyArrayChar, twoArrayDouble)); - assertFalse(ArrayUtils.isSameLength(emptyArrayChar, twoArrayFloat)); - assertFalse(ArrayUtils.isSameLength(emptyArrayByte, twoArrayObject)); - assertFalse(ArrayUtils.isSameLength(emptyArrayByte, twoArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(emptyArrayByte, twoArrayLong)); - assertFalse(ArrayUtils.isSameLength(emptyArrayByte, twoArrayInt)); - assertFalse(ArrayUtils.isSameLength(emptyArrayByte, twoArrayShort)); - assertFalse(ArrayUtils.isSameLength(emptyArrayByte, twoArrayChar)); - assertFalse(ArrayUtils.isSameLength(emptyArrayByte, twoArrayByte)); - assertFalse(ArrayUtils.isSameLength(emptyArrayByte, twoArrayDouble)); - assertFalse(ArrayUtils.isSameLength(emptyArrayByte, twoArrayFloat)); - assertFalse(ArrayUtils.isSameLength(emptyArrayDouble, twoArrayObject)); - assertFalse(ArrayUtils.isSameLength(emptyArrayDouble, twoArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(emptyArrayDouble, twoArrayLong)); - assertFalse(ArrayUtils.isSameLength(emptyArrayDouble, twoArrayInt)); - assertFalse(ArrayUtils.isSameLength(emptyArrayDouble, twoArrayShort)); - assertFalse(ArrayUtils.isSameLength(emptyArrayDouble, twoArrayChar)); - assertFalse(ArrayUtils.isSameLength(emptyArrayDouble, twoArrayByte)); - assertFalse(ArrayUtils.isSameLength(emptyArrayDouble, twoArrayDouble)); - assertFalse(ArrayUtils.isSameLength(emptyArrayDouble, twoArrayFloat)); - assertFalse(ArrayUtils.isSameLength(emptyArrayFloat, twoArrayObject)); - assertFalse(ArrayUtils.isSameLength(emptyArrayFloat, twoArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(emptyArrayFloat, twoArrayLong)); - assertFalse(ArrayUtils.isSameLength(emptyArrayFloat, twoArrayInt)); - assertFalse(ArrayUtils.isSameLength(emptyArrayFloat, twoArrayShort)); - assertFalse(ArrayUtils.isSameLength(emptyArrayFloat, twoArrayChar)); - assertFalse(ArrayUtils.isSameLength(emptyArrayFloat, twoArrayByte)); - assertFalse(ArrayUtils.isSameLength(emptyArrayFloat, twoArrayDouble)); - assertFalse(ArrayUtils.isSameLength(emptyArrayFloat, twoArrayFloat)); - assertFalse(ArrayUtils.isSameLength(oneArrayObject, nullArrayObject)); - assertFalse(ArrayUtils.isSameLength(oneArrayObject, nullArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(oneArrayObject, nullArrayLong)); - assertFalse(ArrayUtils.isSameLength(oneArrayObject, nullArrayInt)); - assertFalse(ArrayUtils.isSameLength(oneArrayObject, nullArrayShort)); - assertFalse(ArrayUtils.isSameLength(oneArrayObject, nullArrayChar)); - assertFalse(ArrayUtils.isSameLength(oneArrayObject, nullArrayByte)); - assertFalse(ArrayUtils.isSameLength(oneArrayObject, nullArrayDouble)); - assertFalse(ArrayUtils.isSameLength(oneArrayObject, nullArrayFloat)); - assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, nullArrayObject)); - assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, nullArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, nullArrayLong)); - assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, nullArrayInt)); - assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, nullArrayShort)); - assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, nullArrayChar)); - assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, nullArrayByte)); - assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, nullArrayDouble)); - assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, nullArrayFloat)); - assertFalse(ArrayUtils.isSameLength(oneArrayLong, nullArrayObject)); - assertFalse(ArrayUtils.isSameLength(oneArrayLong, nullArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(oneArrayLong, nullArrayLong)); - assertFalse(ArrayUtils.isSameLength(oneArrayLong, nullArrayInt)); - assertFalse(ArrayUtils.isSameLength(oneArrayLong, nullArrayShort)); - assertFalse(ArrayUtils.isSameLength(oneArrayLong, nullArrayChar)); - assertFalse(ArrayUtils.isSameLength(oneArrayLong, nullArrayByte)); - assertFalse(ArrayUtils.isSameLength(oneArrayLong, nullArrayDouble)); - assertFalse(ArrayUtils.isSameLength(oneArrayLong, nullArrayFloat)); - assertFalse(ArrayUtils.isSameLength(oneArrayInt, nullArrayObject)); - assertFalse(ArrayUtils.isSameLength(oneArrayInt, nullArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(oneArrayInt, nullArrayLong)); - assertFalse(ArrayUtils.isSameLength(oneArrayInt, nullArrayInt)); - assertFalse(ArrayUtils.isSameLength(oneArrayInt, nullArrayShort)); - assertFalse(ArrayUtils.isSameLength(oneArrayInt, nullArrayChar)); - assertFalse(ArrayUtils.isSameLength(oneArrayInt, nullArrayByte)); - assertFalse(ArrayUtils.isSameLength(oneArrayInt, nullArrayDouble)); - assertFalse(ArrayUtils.isSameLength(oneArrayInt, nullArrayFloat)); - assertFalse(ArrayUtils.isSameLength(oneArrayShort, nullArrayObject)); - assertFalse(ArrayUtils.isSameLength(oneArrayShort, nullArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(oneArrayShort, nullArrayLong)); - assertFalse(ArrayUtils.isSameLength(oneArrayShort, nullArrayInt)); - assertFalse(ArrayUtils.isSameLength(oneArrayShort, nullArrayShort)); - assertFalse(ArrayUtils.isSameLength(oneArrayShort, nullArrayChar)); - assertFalse(ArrayUtils.isSameLength(oneArrayShort, nullArrayByte)); - assertFalse(ArrayUtils.isSameLength(oneArrayShort, nullArrayDouble)); - assertFalse(ArrayUtils.isSameLength(oneArrayShort, nullArrayFloat)); - assertFalse(ArrayUtils.isSameLength(oneArrayChar, nullArrayObject)); - assertFalse(ArrayUtils.isSameLength(oneArrayChar, nullArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(oneArrayChar, nullArrayLong)); - assertFalse(ArrayUtils.isSameLength(oneArrayChar, nullArrayInt)); - assertFalse(ArrayUtils.isSameLength(oneArrayChar, nullArrayShort)); - assertFalse(ArrayUtils.isSameLength(oneArrayChar, nullArrayChar)); - assertFalse(ArrayUtils.isSameLength(oneArrayChar, nullArrayByte)); - assertFalse(ArrayUtils.isSameLength(oneArrayChar, nullArrayDouble)); - assertFalse(ArrayUtils.isSameLength(oneArrayChar, nullArrayFloat)); - assertFalse(ArrayUtils.isSameLength(oneArrayByte, nullArrayObject)); - assertFalse(ArrayUtils.isSameLength(oneArrayByte, nullArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(oneArrayByte, nullArrayLong)); - assertFalse(ArrayUtils.isSameLength(oneArrayByte, nullArrayInt)); - assertFalse(ArrayUtils.isSameLength(oneArrayByte, nullArrayShort)); - assertFalse(ArrayUtils.isSameLength(oneArrayByte, nullArrayChar)); - assertFalse(ArrayUtils.isSameLength(oneArrayByte, nullArrayByte)); - assertFalse(ArrayUtils.isSameLength(oneArrayByte, nullArrayDouble)); - assertFalse(ArrayUtils.isSameLength(oneArrayByte, nullArrayFloat)); - assertFalse(ArrayUtils.isSameLength(oneArrayDouble, nullArrayObject)); - assertFalse(ArrayUtils.isSameLength(oneArrayDouble, nullArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(oneArrayDouble, nullArrayLong)); - assertFalse(ArrayUtils.isSameLength(oneArrayDouble, nullArrayInt)); - assertFalse(ArrayUtils.isSameLength(oneArrayDouble, nullArrayShort)); - assertFalse(ArrayUtils.isSameLength(oneArrayDouble, nullArrayChar)); - assertFalse(ArrayUtils.isSameLength(oneArrayDouble, nullArrayByte)); - assertFalse(ArrayUtils.isSameLength(oneArrayDouble, nullArrayDouble)); - assertFalse(ArrayUtils.isSameLength(oneArrayDouble, nullArrayFloat)); - assertFalse(ArrayUtils.isSameLength(oneArrayFloat, nullArrayObject)); - assertFalse(ArrayUtils.isSameLength(oneArrayFloat, nullArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(oneArrayFloat, nullArrayLong)); - assertFalse(ArrayUtils.isSameLength(oneArrayFloat, nullArrayInt)); - assertFalse(ArrayUtils.isSameLength(oneArrayFloat, nullArrayShort)); - assertFalse(ArrayUtils.isSameLength(oneArrayFloat, nullArrayChar)); - assertFalse(ArrayUtils.isSameLength(oneArrayFloat, nullArrayByte)); - assertFalse(ArrayUtils.isSameLength(oneArrayFloat, nullArrayDouble)); - assertFalse(ArrayUtils.isSameLength(oneArrayFloat, nullArrayFloat)); - assertFalse(ArrayUtils.isSameLength(oneArrayObject, emptyArrayObject)); - assertFalse(ArrayUtils.isSameLength(oneArrayObject, emptyArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(oneArrayObject, emptyArrayLong)); - assertFalse(ArrayUtils.isSameLength(oneArrayObject, emptyArrayInt)); - assertFalse(ArrayUtils.isSameLength(oneArrayObject, emptyArrayShort)); - assertFalse(ArrayUtils.isSameLength(oneArrayObject, emptyArrayChar)); - assertFalse(ArrayUtils.isSameLength(oneArrayObject, emptyArrayByte)); - assertFalse(ArrayUtils.isSameLength(oneArrayObject, emptyArrayDouble)); - assertFalse(ArrayUtils.isSameLength(oneArrayObject, emptyArrayFloat)); - assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, emptyArrayObject)); - assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, emptyArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, emptyArrayLong)); - assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, emptyArrayInt)); - assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, emptyArrayShort)); - assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, emptyArrayChar)); - assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, emptyArrayByte)); - assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, emptyArrayDouble)); - assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, emptyArrayFloat)); - assertFalse(ArrayUtils.isSameLength(oneArrayLong, emptyArrayObject)); - assertFalse(ArrayUtils.isSameLength(oneArrayLong, emptyArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(oneArrayLong, emptyArrayLong)); - assertFalse(ArrayUtils.isSameLength(oneArrayLong, emptyArrayInt)); - assertFalse(ArrayUtils.isSameLength(oneArrayLong, emptyArrayShort)); - assertFalse(ArrayUtils.isSameLength(oneArrayLong, emptyArrayChar)); - assertFalse(ArrayUtils.isSameLength(oneArrayLong, emptyArrayByte)); - assertFalse(ArrayUtils.isSameLength(oneArrayLong, emptyArrayDouble)); - assertFalse(ArrayUtils.isSameLength(oneArrayLong, emptyArrayFloat)); - assertFalse(ArrayUtils.isSameLength(oneArrayInt, emptyArrayObject)); - assertFalse(ArrayUtils.isSameLength(oneArrayInt, emptyArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(oneArrayInt, emptyArrayLong)); - assertFalse(ArrayUtils.isSameLength(oneArrayInt, emptyArrayInt)); - assertFalse(ArrayUtils.isSameLength(oneArrayInt, emptyArrayShort)); - assertFalse(ArrayUtils.isSameLength(oneArrayInt, emptyArrayChar)); - assertFalse(ArrayUtils.isSameLength(oneArrayInt, emptyArrayByte)); - assertFalse(ArrayUtils.isSameLength(oneArrayInt, emptyArrayDouble)); - assertFalse(ArrayUtils.isSameLength(oneArrayInt, emptyArrayFloat)); - assertFalse(ArrayUtils.isSameLength(oneArrayShort, emptyArrayObject)); - assertFalse(ArrayUtils.isSameLength(oneArrayShort, emptyArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(oneArrayShort, emptyArrayLong)); - assertFalse(ArrayUtils.isSameLength(oneArrayShort, emptyArrayInt)); - assertFalse(ArrayUtils.isSameLength(oneArrayShort, emptyArrayShort)); - assertFalse(ArrayUtils.isSameLength(oneArrayShort, emptyArrayChar)); - assertFalse(ArrayUtils.isSameLength(oneArrayShort, emptyArrayByte)); - assertFalse(ArrayUtils.isSameLength(oneArrayShort, emptyArrayDouble)); - assertFalse(ArrayUtils.isSameLength(oneArrayShort, emptyArrayFloat)); - assertFalse(ArrayUtils.isSameLength(oneArrayChar, emptyArrayObject)); - assertFalse(ArrayUtils.isSameLength(oneArrayChar, emptyArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(oneArrayChar, emptyArrayLong)); - assertFalse(ArrayUtils.isSameLength(oneArrayChar, emptyArrayInt)); - assertFalse(ArrayUtils.isSameLength(oneArrayChar, emptyArrayShort)); - assertFalse(ArrayUtils.isSameLength(oneArrayChar, emptyArrayChar)); - assertFalse(ArrayUtils.isSameLength(oneArrayChar, emptyArrayByte)); - assertFalse(ArrayUtils.isSameLength(oneArrayChar, emptyArrayDouble)); - assertFalse(ArrayUtils.isSameLength(oneArrayChar, emptyArrayFloat)); - assertFalse(ArrayUtils.isSameLength(oneArrayByte, emptyArrayObject)); - assertFalse(ArrayUtils.isSameLength(oneArrayByte, emptyArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(oneArrayByte, emptyArrayLong)); - assertFalse(ArrayUtils.isSameLength(oneArrayByte, emptyArrayInt)); - assertFalse(ArrayUtils.isSameLength(oneArrayByte, emptyArrayShort)); - assertFalse(ArrayUtils.isSameLength(oneArrayByte, emptyArrayChar)); - assertFalse(ArrayUtils.isSameLength(oneArrayByte, emptyArrayByte)); - assertFalse(ArrayUtils.isSameLength(oneArrayByte, emptyArrayDouble)); - assertFalse(ArrayUtils.isSameLength(oneArrayByte, emptyArrayFloat)); - assertFalse(ArrayUtils.isSameLength(oneArrayDouble, emptyArrayObject)); - assertFalse(ArrayUtils.isSameLength(oneArrayDouble, emptyArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(oneArrayDouble, emptyArrayLong)); - assertFalse(ArrayUtils.isSameLength(oneArrayDouble, emptyArrayInt)); - assertFalse(ArrayUtils.isSameLength(oneArrayDouble, emptyArrayShort)); - assertFalse(ArrayUtils.isSameLength(oneArrayDouble, emptyArrayChar)); - assertFalse(ArrayUtils.isSameLength(oneArrayDouble, emptyArrayByte)); - assertFalse(ArrayUtils.isSameLength(oneArrayDouble, emptyArrayDouble)); - assertFalse(ArrayUtils.isSameLength(oneArrayDouble, emptyArrayFloat)); - assertFalse(ArrayUtils.isSameLength(oneArrayFloat, emptyArrayObject)); - assertFalse(ArrayUtils.isSameLength(oneArrayFloat, emptyArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(oneArrayFloat, emptyArrayLong)); - assertFalse(ArrayUtils.isSameLength(oneArrayFloat, emptyArrayInt)); - assertFalse(ArrayUtils.isSameLength(oneArrayFloat, emptyArrayShort)); - assertFalse(ArrayUtils.isSameLength(oneArrayFloat, emptyArrayChar)); - assertFalse(ArrayUtils.isSameLength(oneArrayFloat, emptyArrayByte)); - assertFalse(ArrayUtils.isSameLength(oneArrayFloat, emptyArrayDouble)); - assertFalse(ArrayUtils.isSameLength(oneArrayFloat, emptyArrayFloat)); - assertTrue(ArrayUtils.isSameLength(oneArrayObject, oneArrayObject)); - assertTrue(ArrayUtils.isSameLength(oneArrayObject, oneArrayBoolean)); - assertTrue(ArrayUtils.isSameLength(oneArrayObject, oneArrayLong)); - assertTrue(ArrayUtils.isSameLength(oneArrayObject, oneArrayInt)); - assertTrue(ArrayUtils.isSameLength(oneArrayObject, oneArrayShort)); - assertTrue(ArrayUtils.isSameLength(oneArrayObject, oneArrayChar)); - assertTrue(ArrayUtils.isSameLength(oneArrayObject, oneArrayByte)); - assertTrue(ArrayUtils.isSameLength(oneArrayObject, oneArrayDouble)); - assertTrue(ArrayUtils.isSameLength(oneArrayObject, oneArrayFloat)); - assertTrue(ArrayUtils.isSameLength(oneArrayBoolean, oneArrayObject)); - assertTrue(ArrayUtils.isSameLength(oneArrayBoolean, oneArrayBoolean)); - assertTrue(ArrayUtils.isSameLength(oneArrayBoolean, oneArrayLong)); - assertTrue(ArrayUtils.isSameLength(oneArrayBoolean, oneArrayInt)); - assertTrue(ArrayUtils.isSameLength(oneArrayBoolean, oneArrayShort)); - assertTrue(ArrayUtils.isSameLength(oneArrayBoolean, oneArrayChar)); - assertTrue(ArrayUtils.isSameLength(oneArrayBoolean, oneArrayByte)); - assertTrue(ArrayUtils.isSameLength(oneArrayBoolean, oneArrayDouble)); - assertTrue(ArrayUtils.isSameLength(oneArrayBoolean, oneArrayFloat)); - assertTrue(ArrayUtils.isSameLength(oneArrayLong, oneArrayObject)); - assertTrue(ArrayUtils.isSameLength(oneArrayLong, oneArrayBoolean)); - assertTrue(ArrayUtils.isSameLength(oneArrayLong, oneArrayLong)); - assertTrue(ArrayUtils.isSameLength(oneArrayLong, oneArrayInt)); - assertTrue(ArrayUtils.isSameLength(oneArrayLong, oneArrayShort)); - assertTrue(ArrayUtils.isSameLength(oneArrayLong, oneArrayChar)); - assertTrue(ArrayUtils.isSameLength(oneArrayLong, oneArrayByte)); - assertTrue(ArrayUtils.isSameLength(oneArrayLong, oneArrayDouble)); - assertTrue(ArrayUtils.isSameLength(oneArrayLong, oneArrayFloat)); - assertTrue(ArrayUtils.isSameLength(oneArrayInt, oneArrayObject)); - assertTrue(ArrayUtils.isSameLength(oneArrayInt, oneArrayBoolean)); - assertTrue(ArrayUtils.isSameLength(oneArrayInt, oneArrayLong)); - assertTrue(ArrayUtils.isSameLength(oneArrayInt, oneArrayInt)); - assertTrue(ArrayUtils.isSameLength(oneArrayInt, oneArrayShort)); - assertTrue(ArrayUtils.isSameLength(oneArrayInt, oneArrayChar)); - assertTrue(ArrayUtils.isSameLength(oneArrayInt, oneArrayByte)); - assertTrue(ArrayUtils.isSameLength(oneArrayInt, oneArrayDouble)); - assertTrue(ArrayUtils.isSameLength(oneArrayInt, oneArrayFloat)); - assertTrue(ArrayUtils.isSameLength(oneArrayShort, oneArrayObject)); - assertTrue(ArrayUtils.isSameLength(oneArrayShort, oneArrayBoolean)); - assertTrue(ArrayUtils.isSameLength(oneArrayShort, oneArrayLong)); - assertTrue(ArrayUtils.isSameLength(oneArrayShort, oneArrayInt)); - assertTrue(ArrayUtils.isSameLength(oneArrayShort, oneArrayShort)); - assertTrue(ArrayUtils.isSameLength(oneArrayShort, oneArrayChar)); - assertTrue(ArrayUtils.isSameLength(oneArrayShort, oneArrayByte)); - assertTrue(ArrayUtils.isSameLength(oneArrayShort, oneArrayDouble)); - assertTrue(ArrayUtils.isSameLength(oneArrayShort, oneArrayFloat)); - assertTrue(ArrayUtils.isSameLength(oneArrayChar, oneArrayObject)); - assertTrue(ArrayUtils.isSameLength(oneArrayChar, oneArrayBoolean)); - assertTrue(ArrayUtils.isSameLength(oneArrayChar, oneArrayLong)); - assertTrue(ArrayUtils.isSameLength(oneArrayChar, oneArrayInt)); - assertTrue(ArrayUtils.isSameLength(oneArrayChar, oneArrayShort)); - assertTrue(ArrayUtils.isSameLength(oneArrayChar, oneArrayChar)); - assertTrue(ArrayUtils.isSameLength(oneArrayChar, oneArrayByte)); - assertTrue(ArrayUtils.isSameLength(oneArrayChar, oneArrayDouble)); - assertTrue(ArrayUtils.isSameLength(oneArrayChar, oneArrayFloat)); - assertTrue(ArrayUtils.isSameLength(oneArrayByte, oneArrayObject)); - assertTrue(ArrayUtils.isSameLength(oneArrayByte, oneArrayBoolean)); - assertTrue(ArrayUtils.isSameLength(oneArrayByte, oneArrayLong)); - assertTrue(ArrayUtils.isSameLength(oneArrayByte, oneArrayInt)); - assertTrue(ArrayUtils.isSameLength(oneArrayByte, oneArrayShort)); - assertTrue(ArrayUtils.isSameLength(oneArrayByte, oneArrayChar)); - assertTrue(ArrayUtils.isSameLength(oneArrayByte, oneArrayByte)); - assertTrue(ArrayUtils.isSameLength(oneArrayByte, oneArrayDouble)); - assertTrue(ArrayUtils.isSameLength(oneArrayByte, oneArrayFloat)); - assertTrue(ArrayUtils.isSameLength(oneArrayDouble, oneArrayObject)); - assertTrue(ArrayUtils.isSameLength(oneArrayDouble, oneArrayBoolean)); - assertTrue(ArrayUtils.isSameLength(oneArrayDouble, oneArrayLong)); - assertTrue(ArrayUtils.isSameLength(oneArrayDouble, oneArrayInt)); - assertTrue(ArrayUtils.isSameLength(oneArrayDouble, oneArrayShort)); - assertTrue(ArrayUtils.isSameLength(oneArrayDouble, oneArrayChar)); - assertTrue(ArrayUtils.isSameLength(oneArrayDouble, oneArrayByte)); - assertTrue(ArrayUtils.isSameLength(oneArrayDouble, oneArrayDouble)); - assertTrue(ArrayUtils.isSameLength(oneArrayDouble, oneArrayFloat)); - assertTrue(ArrayUtils.isSameLength(oneArrayFloat, oneArrayObject)); - assertTrue(ArrayUtils.isSameLength(oneArrayFloat, oneArrayBoolean)); - assertTrue(ArrayUtils.isSameLength(oneArrayFloat, oneArrayLong)); - assertTrue(ArrayUtils.isSameLength(oneArrayFloat, oneArrayInt)); - assertTrue(ArrayUtils.isSameLength(oneArrayFloat, oneArrayShort)); - assertTrue(ArrayUtils.isSameLength(oneArrayFloat, oneArrayChar)); - assertTrue(ArrayUtils.isSameLength(oneArrayFloat, oneArrayByte)); - assertTrue(ArrayUtils.isSameLength(oneArrayFloat, oneArrayDouble)); - assertTrue(ArrayUtils.isSameLength(oneArrayFloat, oneArrayFloat)); - assertFalse(ArrayUtils.isSameLength(oneArrayObject, twoArrayObject)); - assertFalse(ArrayUtils.isSameLength(oneArrayObject, twoArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(oneArrayObject, twoArrayLong)); - assertFalse(ArrayUtils.isSameLength(oneArrayObject, twoArrayInt)); - assertFalse(ArrayUtils.isSameLength(oneArrayObject, twoArrayShort)); - assertFalse(ArrayUtils.isSameLength(oneArrayObject, twoArrayChar)); - assertFalse(ArrayUtils.isSameLength(oneArrayObject, twoArrayByte)); - assertFalse(ArrayUtils.isSameLength(oneArrayObject, twoArrayDouble)); - assertFalse(ArrayUtils.isSameLength(oneArrayObject, twoArrayFloat)); - assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, twoArrayObject)); - assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, twoArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, twoArrayLong)); - assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, twoArrayInt)); - assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, twoArrayShort)); - assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, twoArrayChar)); - assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, twoArrayByte)); - assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, twoArrayDouble)); - assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, twoArrayFloat)); - assertFalse(ArrayUtils.isSameLength(oneArrayLong, twoArrayObject)); - assertFalse(ArrayUtils.isSameLength(oneArrayLong, twoArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(oneArrayLong, twoArrayLong)); - assertFalse(ArrayUtils.isSameLength(oneArrayLong, twoArrayInt)); - assertFalse(ArrayUtils.isSameLength(oneArrayLong, twoArrayShort)); - assertFalse(ArrayUtils.isSameLength(oneArrayLong, twoArrayChar)); - assertFalse(ArrayUtils.isSameLength(oneArrayLong, twoArrayByte)); - assertFalse(ArrayUtils.isSameLength(oneArrayLong, twoArrayDouble)); - assertFalse(ArrayUtils.isSameLength(oneArrayLong, twoArrayFloat)); - assertFalse(ArrayUtils.isSameLength(oneArrayInt, twoArrayObject)); - assertFalse(ArrayUtils.isSameLength(oneArrayInt, twoArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(oneArrayInt, twoArrayLong)); - assertFalse(ArrayUtils.isSameLength(oneArrayInt, twoArrayInt)); - assertFalse(ArrayUtils.isSameLength(oneArrayInt, twoArrayShort)); - assertFalse(ArrayUtils.isSameLength(oneArrayInt, twoArrayChar)); - assertFalse(ArrayUtils.isSameLength(oneArrayInt, twoArrayByte)); - assertFalse(ArrayUtils.isSameLength(oneArrayInt, twoArrayDouble)); - assertFalse(ArrayUtils.isSameLength(oneArrayInt, twoArrayFloat)); - assertFalse(ArrayUtils.isSameLength(oneArrayShort, twoArrayObject)); - assertFalse(ArrayUtils.isSameLength(oneArrayShort, twoArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(oneArrayShort, twoArrayLong)); - assertFalse(ArrayUtils.isSameLength(oneArrayShort, twoArrayInt)); - assertFalse(ArrayUtils.isSameLength(oneArrayShort, twoArrayShort)); - assertFalse(ArrayUtils.isSameLength(oneArrayShort, twoArrayChar)); - assertFalse(ArrayUtils.isSameLength(oneArrayShort, twoArrayByte)); - assertFalse(ArrayUtils.isSameLength(oneArrayShort, twoArrayDouble)); - assertFalse(ArrayUtils.isSameLength(oneArrayShort, twoArrayFloat)); - assertFalse(ArrayUtils.isSameLength(oneArrayChar, twoArrayObject)); - assertFalse(ArrayUtils.isSameLength(oneArrayChar, twoArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(oneArrayChar, twoArrayLong)); - assertFalse(ArrayUtils.isSameLength(oneArrayChar, twoArrayInt)); - assertFalse(ArrayUtils.isSameLength(oneArrayChar, twoArrayShort)); - assertFalse(ArrayUtils.isSameLength(oneArrayChar, twoArrayChar)); - assertFalse(ArrayUtils.isSameLength(oneArrayChar, twoArrayByte)); - assertFalse(ArrayUtils.isSameLength(oneArrayChar, twoArrayDouble)); - assertFalse(ArrayUtils.isSameLength(oneArrayChar, twoArrayFloat)); - assertFalse(ArrayUtils.isSameLength(oneArrayByte, twoArrayObject)); - assertFalse(ArrayUtils.isSameLength(oneArrayByte, twoArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(oneArrayByte, twoArrayLong)); - assertFalse(ArrayUtils.isSameLength(oneArrayByte, twoArrayInt)); - assertFalse(ArrayUtils.isSameLength(oneArrayByte, twoArrayShort)); - assertFalse(ArrayUtils.isSameLength(oneArrayByte, twoArrayChar)); - assertFalse(ArrayUtils.isSameLength(oneArrayByte, twoArrayByte)); - assertFalse(ArrayUtils.isSameLength(oneArrayByte, twoArrayDouble)); - assertFalse(ArrayUtils.isSameLength(oneArrayByte, twoArrayFloat)); - assertFalse(ArrayUtils.isSameLength(oneArrayDouble, twoArrayObject)); - assertFalse(ArrayUtils.isSameLength(oneArrayDouble, twoArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(oneArrayDouble, twoArrayLong)); - assertFalse(ArrayUtils.isSameLength(oneArrayDouble, twoArrayInt)); - assertFalse(ArrayUtils.isSameLength(oneArrayDouble, twoArrayShort)); - assertFalse(ArrayUtils.isSameLength(oneArrayDouble, twoArrayChar)); - assertFalse(ArrayUtils.isSameLength(oneArrayDouble, twoArrayByte)); - assertFalse(ArrayUtils.isSameLength(oneArrayDouble, twoArrayDouble)); - assertFalse(ArrayUtils.isSameLength(oneArrayDouble, twoArrayFloat)); - assertFalse(ArrayUtils.isSameLength(oneArrayFloat, twoArrayObject)); - assertFalse(ArrayUtils.isSameLength(oneArrayFloat, twoArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(oneArrayFloat, twoArrayLong)); - assertFalse(ArrayUtils.isSameLength(oneArrayFloat, twoArrayInt)); - assertFalse(ArrayUtils.isSameLength(oneArrayFloat, twoArrayShort)); - assertFalse(ArrayUtils.isSameLength(oneArrayFloat, twoArrayChar)); - assertFalse(ArrayUtils.isSameLength(oneArrayFloat, twoArrayByte)); - assertFalse(ArrayUtils.isSameLength(oneArrayFloat, twoArrayDouble)); - assertFalse(ArrayUtils.isSameLength(oneArrayFloat, twoArrayFloat)); - assertFalse(ArrayUtils.isSameLength(twoArrayObject, nullArrayObject)); - assertFalse(ArrayUtils.isSameLength(twoArrayObject, nullArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(twoArrayObject, nullArrayLong)); - assertFalse(ArrayUtils.isSameLength(twoArrayObject, nullArrayInt)); - assertFalse(ArrayUtils.isSameLength(twoArrayObject, nullArrayShort)); - assertFalse(ArrayUtils.isSameLength(twoArrayObject, nullArrayChar)); - assertFalse(ArrayUtils.isSameLength(twoArrayObject, nullArrayByte)); - assertFalse(ArrayUtils.isSameLength(twoArrayObject, nullArrayDouble)); - assertFalse(ArrayUtils.isSameLength(twoArrayObject, nullArrayFloat)); - assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, nullArrayObject)); - assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, nullArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, nullArrayLong)); - assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, nullArrayInt)); - assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, nullArrayShort)); - assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, nullArrayChar)); - assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, nullArrayByte)); - assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, nullArrayDouble)); - assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, nullArrayFloat)); - assertFalse(ArrayUtils.isSameLength(twoArrayLong, nullArrayObject)); - assertFalse(ArrayUtils.isSameLength(twoArrayLong, nullArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(twoArrayLong, nullArrayLong)); - assertFalse(ArrayUtils.isSameLength(twoArrayLong, nullArrayInt)); - assertFalse(ArrayUtils.isSameLength(twoArrayLong, nullArrayShort)); - assertFalse(ArrayUtils.isSameLength(twoArrayLong, nullArrayChar)); - assertFalse(ArrayUtils.isSameLength(twoArrayLong, nullArrayByte)); - assertFalse(ArrayUtils.isSameLength(twoArrayLong, nullArrayDouble)); - assertFalse(ArrayUtils.isSameLength(twoArrayLong, nullArrayFloat)); - assertFalse(ArrayUtils.isSameLength(twoArrayInt, nullArrayObject)); - assertFalse(ArrayUtils.isSameLength(twoArrayInt, nullArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(twoArrayInt, nullArrayLong)); - assertFalse(ArrayUtils.isSameLength(twoArrayInt, nullArrayInt)); - assertFalse(ArrayUtils.isSameLength(twoArrayInt, nullArrayShort)); - assertFalse(ArrayUtils.isSameLength(twoArrayInt, nullArrayChar)); - assertFalse(ArrayUtils.isSameLength(twoArrayInt, nullArrayByte)); - assertFalse(ArrayUtils.isSameLength(twoArrayInt, nullArrayDouble)); - assertFalse(ArrayUtils.isSameLength(twoArrayInt, nullArrayFloat)); - assertFalse(ArrayUtils.isSameLength(twoArrayShort, nullArrayObject)); - assertFalse(ArrayUtils.isSameLength(twoArrayShort, nullArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(twoArrayShort, nullArrayLong)); - assertFalse(ArrayUtils.isSameLength(twoArrayShort, nullArrayInt)); - assertFalse(ArrayUtils.isSameLength(twoArrayShort, nullArrayShort)); - assertFalse(ArrayUtils.isSameLength(twoArrayShort, nullArrayChar)); - assertFalse(ArrayUtils.isSameLength(twoArrayShort, nullArrayByte)); - assertFalse(ArrayUtils.isSameLength(twoArrayShort, nullArrayDouble)); - assertFalse(ArrayUtils.isSameLength(twoArrayShort, nullArrayFloat)); - assertFalse(ArrayUtils.isSameLength(twoArrayChar, nullArrayObject)); - assertFalse(ArrayUtils.isSameLength(twoArrayChar, nullArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(twoArrayChar, nullArrayLong)); - assertFalse(ArrayUtils.isSameLength(twoArrayChar, nullArrayInt)); - assertFalse(ArrayUtils.isSameLength(twoArrayChar, nullArrayShort)); - assertFalse(ArrayUtils.isSameLength(twoArrayChar, nullArrayChar)); - assertFalse(ArrayUtils.isSameLength(twoArrayChar, nullArrayByte)); - assertFalse(ArrayUtils.isSameLength(twoArrayChar, nullArrayDouble)); - assertFalse(ArrayUtils.isSameLength(twoArrayChar, nullArrayFloat)); - assertFalse(ArrayUtils.isSameLength(twoArrayByte, nullArrayObject)); - assertFalse(ArrayUtils.isSameLength(twoArrayByte, nullArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(twoArrayByte, nullArrayLong)); - assertFalse(ArrayUtils.isSameLength(twoArrayByte, nullArrayInt)); - assertFalse(ArrayUtils.isSameLength(twoArrayByte, nullArrayShort)); - assertFalse(ArrayUtils.isSameLength(twoArrayByte, nullArrayChar)); - assertFalse(ArrayUtils.isSameLength(twoArrayByte, nullArrayByte)); - assertFalse(ArrayUtils.isSameLength(twoArrayByte, nullArrayDouble)); - assertFalse(ArrayUtils.isSameLength(twoArrayByte, nullArrayFloat)); - assertFalse(ArrayUtils.isSameLength(twoArrayDouble, nullArrayObject)); - assertFalse(ArrayUtils.isSameLength(twoArrayDouble, nullArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(twoArrayDouble, nullArrayLong)); - assertFalse(ArrayUtils.isSameLength(twoArrayDouble, nullArrayInt)); - assertFalse(ArrayUtils.isSameLength(twoArrayDouble, nullArrayShort)); - assertFalse(ArrayUtils.isSameLength(twoArrayDouble, nullArrayChar)); - assertFalse(ArrayUtils.isSameLength(twoArrayDouble, nullArrayByte)); - assertFalse(ArrayUtils.isSameLength(twoArrayDouble, nullArrayDouble)); - assertFalse(ArrayUtils.isSameLength(twoArrayDouble, nullArrayFloat)); - assertFalse(ArrayUtils.isSameLength(twoArrayFloat, nullArrayObject)); - assertFalse(ArrayUtils.isSameLength(twoArrayFloat, nullArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(twoArrayFloat, nullArrayLong)); - assertFalse(ArrayUtils.isSameLength(twoArrayFloat, nullArrayInt)); - assertFalse(ArrayUtils.isSameLength(twoArrayFloat, nullArrayShort)); - assertFalse(ArrayUtils.isSameLength(twoArrayFloat, nullArrayChar)); - assertFalse(ArrayUtils.isSameLength(twoArrayFloat, nullArrayByte)); - assertFalse(ArrayUtils.isSameLength(twoArrayFloat, nullArrayDouble)); - assertFalse(ArrayUtils.isSameLength(twoArrayFloat, nullArrayFloat)); - assertFalse(ArrayUtils.isSameLength(twoArrayObject, emptyArrayObject)); - assertFalse(ArrayUtils.isSameLength(twoArrayObject, emptyArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(twoArrayObject, emptyArrayLong)); - assertFalse(ArrayUtils.isSameLength(twoArrayObject, emptyArrayInt)); - assertFalse(ArrayUtils.isSameLength(twoArrayObject, emptyArrayShort)); - assertFalse(ArrayUtils.isSameLength(twoArrayObject, emptyArrayChar)); - assertFalse(ArrayUtils.isSameLength(twoArrayObject, emptyArrayByte)); - assertFalse(ArrayUtils.isSameLength(twoArrayObject, emptyArrayDouble)); - assertFalse(ArrayUtils.isSameLength(twoArrayObject, emptyArrayFloat)); - assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, emptyArrayObject)); - assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, emptyArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, emptyArrayLong)); - assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, emptyArrayInt)); - assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, emptyArrayShort)); - assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, emptyArrayChar)); - assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, emptyArrayByte)); - assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, emptyArrayDouble)); - assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, emptyArrayFloat)); - assertFalse(ArrayUtils.isSameLength(twoArrayLong, emptyArrayObject)); - assertFalse(ArrayUtils.isSameLength(twoArrayLong, emptyArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(twoArrayLong, emptyArrayLong)); - assertFalse(ArrayUtils.isSameLength(twoArrayLong, emptyArrayInt)); - assertFalse(ArrayUtils.isSameLength(twoArrayLong, emptyArrayShort)); - assertFalse(ArrayUtils.isSameLength(twoArrayLong, emptyArrayChar)); - assertFalse(ArrayUtils.isSameLength(twoArrayLong, emptyArrayByte)); - assertFalse(ArrayUtils.isSameLength(twoArrayLong, emptyArrayDouble)); - assertFalse(ArrayUtils.isSameLength(twoArrayLong, emptyArrayFloat)); - assertFalse(ArrayUtils.isSameLength(twoArrayInt, emptyArrayObject)); - assertFalse(ArrayUtils.isSameLength(twoArrayInt, emptyArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(twoArrayInt, emptyArrayLong)); - assertFalse(ArrayUtils.isSameLength(twoArrayInt, emptyArrayInt)); - assertFalse(ArrayUtils.isSameLength(twoArrayInt, emptyArrayShort)); - assertFalse(ArrayUtils.isSameLength(twoArrayInt, emptyArrayChar)); - assertFalse(ArrayUtils.isSameLength(twoArrayInt, emptyArrayByte)); - assertFalse(ArrayUtils.isSameLength(twoArrayInt, emptyArrayDouble)); - assertFalse(ArrayUtils.isSameLength(twoArrayInt, emptyArrayFloat)); - assertFalse(ArrayUtils.isSameLength(twoArrayShort, emptyArrayObject)); - assertFalse(ArrayUtils.isSameLength(twoArrayShort, emptyArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(twoArrayShort, emptyArrayLong)); - assertFalse(ArrayUtils.isSameLength(twoArrayShort, emptyArrayInt)); - assertFalse(ArrayUtils.isSameLength(twoArrayShort, emptyArrayShort)); - assertFalse(ArrayUtils.isSameLength(twoArrayShort, emptyArrayChar)); - assertFalse(ArrayUtils.isSameLength(twoArrayShort, emptyArrayByte)); - assertFalse(ArrayUtils.isSameLength(twoArrayShort, emptyArrayDouble)); - assertFalse(ArrayUtils.isSameLength(twoArrayShort, emptyArrayFloat)); - assertFalse(ArrayUtils.isSameLength(twoArrayChar, emptyArrayObject)); - assertFalse(ArrayUtils.isSameLength(twoArrayChar, emptyArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(twoArrayChar, emptyArrayLong)); - assertFalse(ArrayUtils.isSameLength(twoArrayChar, emptyArrayInt)); - assertFalse(ArrayUtils.isSameLength(twoArrayChar, emptyArrayShort)); - assertFalse(ArrayUtils.isSameLength(twoArrayChar, emptyArrayChar)); - assertFalse(ArrayUtils.isSameLength(twoArrayChar, emptyArrayByte)); - assertFalse(ArrayUtils.isSameLength(twoArrayChar, emptyArrayDouble)); - assertFalse(ArrayUtils.isSameLength(twoArrayChar, emptyArrayFloat)); - assertFalse(ArrayUtils.isSameLength(twoArrayByte, emptyArrayObject)); - assertFalse(ArrayUtils.isSameLength(twoArrayByte, emptyArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(twoArrayByte, emptyArrayLong)); - assertFalse(ArrayUtils.isSameLength(twoArrayByte, emptyArrayInt)); - assertFalse(ArrayUtils.isSameLength(twoArrayByte, emptyArrayShort)); - assertFalse(ArrayUtils.isSameLength(twoArrayByte, emptyArrayChar)); - assertFalse(ArrayUtils.isSameLength(twoArrayByte, emptyArrayByte)); - assertFalse(ArrayUtils.isSameLength(twoArrayByte, emptyArrayDouble)); - assertFalse(ArrayUtils.isSameLength(twoArrayByte, emptyArrayFloat)); - assertFalse(ArrayUtils.isSameLength(twoArrayDouble, emptyArrayObject)); - assertFalse(ArrayUtils.isSameLength(twoArrayDouble, emptyArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(twoArrayDouble, emptyArrayLong)); - assertFalse(ArrayUtils.isSameLength(twoArrayDouble, emptyArrayInt)); - assertFalse(ArrayUtils.isSameLength(twoArrayDouble, emptyArrayShort)); - assertFalse(ArrayUtils.isSameLength(twoArrayDouble, emptyArrayChar)); - assertFalse(ArrayUtils.isSameLength(twoArrayDouble, emptyArrayByte)); - assertFalse(ArrayUtils.isSameLength(twoArrayDouble, emptyArrayDouble)); - assertFalse(ArrayUtils.isSameLength(twoArrayDouble, emptyArrayFloat)); - assertFalse(ArrayUtils.isSameLength(twoArrayFloat, emptyArrayObject)); - assertFalse(ArrayUtils.isSameLength(twoArrayFloat, emptyArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(twoArrayFloat, emptyArrayLong)); - assertFalse(ArrayUtils.isSameLength(twoArrayFloat, emptyArrayInt)); - assertFalse(ArrayUtils.isSameLength(twoArrayFloat, emptyArrayShort)); - assertFalse(ArrayUtils.isSameLength(twoArrayFloat, emptyArrayChar)); - assertFalse(ArrayUtils.isSameLength(twoArrayFloat, emptyArrayByte)); - assertFalse(ArrayUtils.isSameLength(twoArrayFloat, emptyArrayDouble)); - assertFalse(ArrayUtils.isSameLength(twoArrayFloat, emptyArrayFloat)); - assertFalse(ArrayUtils.isSameLength(twoArrayObject, oneArrayObject)); - assertFalse(ArrayUtils.isSameLength(twoArrayObject, oneArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(twoArrayObject, oneArrayLong)); - assertFalse(ArrayUtils.isSameLength(twoArrayObject, oneArrayInt)); - assertFalse(ArrayUtils.isSameLength(twoArrayObject, oneArrayShort)); - assertFalse(ArrayUtils.isSameLength(twoArrayObject, oneArrayChar)); - assertFalse(ArrayUtils.isSameLength(twoArrayObject, oneArrayByte)); - assertFalse(ArrayUtils.isSameLength(twoArrayObject, oneArrayDouble)); - assertFalse(ArrayUtils.isSameLength(twoArrayObject, oneArrayFloat)); - assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, oneArrayObject)); - assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, oneArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, oneArrayLong)); - assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, oneArrayInt)); - assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, oneArrayShort)); - assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, oneArrayChar)); - assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, oneArrayByte)); - assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, oneArrayDouble)); - assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, oneArrayFloat)); - assertFalse(ArrayUtils.isSameLength(twoArrayLong, oneArrayObject)); - assertFalse(ArrayUtils.isSameLength(twoArrayLong, oneArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(twoArrayLong, oneArrayLong)); - assertFalse(ArrayUtils.isSameLength(twoArrayLong, oneArrayInt)); - assertFalse(ArrayUtils.isSameLength(twoArrayLong, oneArrayShort)); - assertFalse(ArrayUtils.isSameLength(twoArrayLong, oneArrayChar)); - assertFalse(ArrayUtils.isSameLength(twoArrayLong, oneArrayByte)); - assertFalse(ArrayUtils.isSameLength(twoArrayLong, oneArrayDouble)); - assertFalse(ArrayUtils.isSameLength(twoArrayLong, oneArrayFloat)); - assertFalse(ArrayUtils.isSameLength(twoArrayInt, oneArrayObject)); - assertFalse(ArrayUtils.isSameLength(twoArrayInt, oneArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(twoArrayInt, oneArrayLong)); - assertFalse(ArrayUtils.isSameLength(twoArrayInt, oneArrayInt)); - assertFalse(ArrayUtils.isSameLength(twoArrayInt, oneArrayShort)); - assertFalse(ArrayUtils.isSameLength(twoArrayInt, oneArrayChar)); - assertFalse(ArrayUtils.isSameLength(twoArrayInt, oneArrayByte)); - assertFalse(ArrayUtils.isSameLength(twoArrayInt, oneArrayDouble)); - assertFalse(ArrayUtils.isSameLength(twoArrayInt, oneArrayFloat)); - assertFalse(ArrayUtils.isSameLength(twoArrayShort, oneArrayObject)); - assertFalse(ArrayUtils.isSameLength(twoArrayShort, oneArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(twoArrayShort, oneArrayLong)); - assertFalse(ArrayUtils.isSameLength(twoArrayShort, oneArrayInt)); - assertFalse(ArrayUtils.isSameLength(twoArrayShort, oneArrayShort)); - assertFalse(ArrayUtils.isSameLength(twoArrayShort, oneArrayChar)); - assertFalse(ArrayUtils.isSameLength(twoArrayShort, oneArrayByte)); - assertFalse(ArrayUtils.isSameLength(twoArrayShort, oneArrayDouble)); - assertFalse(ArrayUtils.isSameLength(twoArrayShort, oneArrayFloat)); - assertFalse(ArrayUtils.isSameLength(twoArrayChar, oneArrayObject)); - assertFalse(ArrayUtils.isSameLength(twoArrayChar, oneArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(twoArrayChar, oneArrayLong)); - assertFalse(ArrayUtils.isSameLength(twoArrayChar, oneArrayInt)); - assertFalse(ArrayUtils.isSameLength(twoArrayChar, oneArrayShort)); - assertFalse(ArrayUtils.isSameLength(twoArrayChar, oneArrayChar)); - assertFalse(ArrayUtils.isSameLength(twoArrayChar, oneArrayByte)); - assertFalse(ArrayUtils.isSameLength(twoArrayChar, oneArrayDouble)); - assertFalse(ArrayUtils.isSameLength(twoArrayChar, oneArrayFloat)); - assertFalse(ArrayUtils.isSameLength(twoArrayByte, oneArrayObject)); - assertFalse(ArrayUtils.isSameLength(twoArrayByte, oneArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(twoArrayByte, oneArrayLong)); - assertFalse(ArrayUtils.isSameLength(twoArrayByte, oneArrayInt)); - assertFalse(ArrayUtils.isSameLength(twoArrayByte, oneArrayShort)); - assertFalse(ArrayUtils.isSameLength(twoArrayByte, oneArrayChar)); - assertFalse(ArrayUtils.isSameLength(twoArrayByte, oneArrayByte)); - assertFalse(ArrayUtils.isSameLength(twoArrayByte, oneArrayDouble)); - assertFalse(ArrayUtils.isSameLength(twoArrayByte, oneArrayFloat)); - assertFalse(ArrayUtils.isSameLength(twoArrayDouble, oneArrayObject)); - assertFalse(ArrayUtils.isSameLength(twoArrayDouble, oneArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(twoArrayDouble, oneArrayLong)); - assertFalse(ArrayUtils.isSameLength(twoArrayDouble, oneArrayInt)); - assertFalse(ArrayUtils.isSameLength(twoArrayDouble, oneArrayShort)); - assertFalse(ArrayUtils.isSameLength(twoArrayDouble, oneArrayChar)); - assertFalse(ArrayUtils.isSameLength(twoArrayDouble, oneArrayByte)); - assertFalse(ArrayUtils.isSameLength(twoArrayDouble, oneArrayDouble)); - assertFalse(ArrayUtils.isSameLength(twoArrayDouble, oneArrayFloat)); - assertFalse(ArrayUtils.isSameLength(twoArrayFloat, oneArrayObject)); - assertFalse(ArrayUtils.isSameLength(twoArrayFloat, oneArrayBoolean)); - assertFalse(ArrayUtils.isSameLength(twoArrayFloat, oneArrayLong)); - assertFalse(ArrayUtils.isSameLength(twoArrayFloat, oneArrayInt)); - assertFalse(ArrayUtils.isSameLength(twoArrayFloat, oneArrayShort)); - assertFalse(ArrayUtils.isSameLength(twoArrayFloat, oneArrayChar)); - assertFalse(ArrayUtils.isSameLength(twoArrayFloat, oneArrayByte)); - assertFalse(ArrayUtils.isSameLength(twoArrayFloat, oneArrayDouble)); - assertFalse(ArrayUtils.isSameLength(twoArrayFloat, oneArrayFloat)); - assertTrue(ArrayUtils.isSameLength(twoArrayObject, twoArrayObject)); - assertTrue(ArrayUtils.isSameLength(twoArrayObject, twoArrayBoolean)); - assertTrue(ArrayUtils.isSameLength(twoArrayObject, twoArrayLong)); - assertTrue(ArrayUtils.isSameLength(twoArrayObject, twoArrayInt)); - assertTrue(ArrayUtils.isSameLength(twoArrayObject, twoArrayShort)); - assertTrue(ArrayUtils.isSameLength(twoArrayObject, twoArrayChar)); - assertTrue(ArrayUtils.isSameLength(twoArrayObject, twoArrayByte)); - assertTrue(ArrayUtils.isSameLength(twoArrayObject, twoArrayDouble)); - assertTrue(ArrayUtils.isSameLength(twoArrayObject, twoArrayFloat)); - assertTrue(ArrayUtils.isSameLength(twoArrayBoolean, twoArrayObject)); - assertTrue(ArrayUtils.isSameLength(twoArrayBoolean, twoArrayBoolean)); - assertTrue(ArrayUtils.isSameLength(twoArrayBoolean, twoArrayLong)); - assertTrue(ArrayUtils.isSameLength(twoArrayBoolean, twoArrayInt)); - assertTrue(ArrayUtils.isSameLength(twoArrayBoolean, twoArrayShort)); - assertTrue(ArrayUtils.isSameLength(twoArrayBoolean, twoArrayChar)); - assertTrue(ArrayUtils.isSameLength(twoArrayBoolean, twoArrayByte)); - assertTrue(ArrayUtils.isSameLength(twoArrayBoolean, twoArrayDouble)); - assertTrue(ArrayUtils.isSameLength(twoArrayBoolean, twoArrayFloat)); - assertTrue(ArrayUtils.isSameLength(twoArrayLong, twoArrayObject)); - assertTrue(ArrayUtils.isSameLength(twoArrayLong, twoArrayBoolean)); - assertTrue(ArrayUtils.isSameLength(twoArrayLong, twoArrayLong)); - assertTrue(ArrayUtils.isSameLength(twoArrayLong, twoArrayInt)); - assertTrue(ArrayUtils.isSameLength(twoArrayLong, twoArrayShort)); - assertTrue(ArrayUtils.isSameLength(twoArrayLong, twoArrayChar)); - assertTrue(ArrayUtils.isSameLength(twoArrayLong, twoArrayByte)); - assertTrue(ArrayUtils.isSameLength(twoArrayLong, twoArrayDouble)); - assertTrue(ArrayUtils.isSameLength(twoArrayLong, twoArrayFloat)); - assertTrue(ArrayUtils.isSameLength(twoArrayInt, twoArrayObject)); - assertTrue(ArrayUtils.isSameLength(twoArrayInt, twoArrayBoolean)); - assertTrue(ArrayUtils.isSameLength(twoArrayInt, twoArrayLong)); - assertTrue(ArrayUtils.isSameLength(twoArrayInt, twoArrayInt)); - assertTrue(ArrayUtils.isSameLength(twoArrayInt, twoArrayShort)); - assertTrue(ArrayUtils.isSameLength(twoArrayInt, twoArrayChar)); - assertTrue(ArrayUtils.isSameLength(twoArrayInt, twoArrayByte)); - assertTrue(ArrayUtils.isSameLength(twoArrayInt, twoArrayDouble)); - assertTrue(ArrayUtils.isSameLength(twoArrayInt, twoArrayFloat)); - assertTrue(ArrayUtils.isSameLength(twoArrayShort, twoArrayObject)); - assertTrue(ArrayUtils.isSameLength(twoArrayShort, twoArrayBoolean)); - assertTrue(ArrayUtils.isSameLength(twoArrayShort, twoArrayLong)); - assertTrue(ArrayUtils.isSameLength(twoArrayShort, twoArrayInt)); - assertTrue(ArrayUtils.isSameLength(twoArrayShort, twoArrayShort)); - assertTrue(ArrayUtils.isSameLength(twoArrayShort, twoArrayChar)); - assertTrue(ArrayUtils.isSameLength(twoArrayShort, twoArrayByte)); - assertTrue(ArrayUtils.isSameLength(twoArrayShort, twoArrayDouble)); - assertTrue(ArrayUtils.isSameLength(twoArrayShort, twoArrayFloat)); - assertTrue(ArrayUtils.isSameLength(twoArrayChar, twoArrayObject)); - assertTrue(ArrayUtils.isSameLength(twoArrayChar, twoArrayBoolean)); - assertTrue(ArrayUtils.isSameLength(twoArrayChar, twoArrayLong)); - assertTrue(ArrayUtils.isSameLength(twoArrayChar, twoArrayInt)); - assertTrue(ArrayUtils.isSameLength(twoArrayChar, twoArrayShort)); - assertTrue(ArrayUtils.isSameLength(twoArrayChar, twoArrayChar)); - assertTrue(ArrayUtils.isSameLength(twoArrayChar, twoArrayByte)); - assertTrue(ArrayUtils.isSameLength(twoArrayChar, twoArrayDouble)); - assertTrue(ArrayUtils.isSameLength(twoArrayChar, twoArrayFloat)); - assertTrue(ArrayUtils.isSameLength(twoArrayByte, twoArrayObject)); - assertTrue(ArrayUtils.isSameLength(twoArrayByte, twoArrayBoolean)); - assertTrue(ArrayUtils.isSameLength(twoArrayByte, twoArrayLong)); - assertTrue(ArrayUtils.isSameLength(twoArrayByte, twoArrayInt)); - assertTrue(ArrayUtils.isSameLength(twoArrayByte, twoArrayShort)); - assertTrue(ArrayUtils.isSameLength(twoArrayByte, twoArrayChar)); - assertTrue(ArrayUtils.isSameLength(twoArrayByte, twoArrayByte)); - assertTrue(ArrayUtils.isSameLength(twoArrayByte, twoArrayDouble)); - assertTrue(ArrayUtils.isSameLength(twoArrayByte, twoArrayFloat)); - assertTrue(ArrayUtils.isSameLength(twoArrayDouble, twoArrayObject)); - assertTrue(ArrayUtils.isSameLength(twoArrayDouble, twoArrayBoolean)); - assertTrue(ArrayUtils.isSameLength(twoArrayDouble, twoArrayLong)); - assertTrue(ArrayUtils.isSameLength(twoArrayDouble, twoArrayInt)); - assertTrue(ArrayUtils.isSameLength(twoArrayDouble, twoArrayShort)); - assertTrue(ArrayUtils.isSameLength(twoArrayDouble, twoArrayChar)); - assertTrue(ArrayUtils.isSameLength(twoArrayDouble, twoArrayByte)); - assertTrue(ArrayUtils.isSameLength(twoArrayDouble, twoArrayDouble)); - assertTrue(ArrayUtils.isSameLength(twoArrayDouble, twoArrayFloat)); - assertTrue(ArrayUtils.isSameLength(twoArrayFloat, twoArrayObject)); - assertTrue(ArrayUtils.isSameLength(twoArrayFloat, twoArrayBoolean)); - assertTrue(ArrayUtils.isSameLength(twoArrayFloat, twoArrayLong)); - assertTrue(ArrayUtils.isSameLength(twoArrayFloat, twoArrayInt)); - assertTrue(ArrayUtils.isSameLength(twoArrayFloat, twoArrayShort)); - assertTrue(ArrayUtils.isSameLength(twoArrayFloat, twoArrayChar)); - assertTrue(ArrayUtils.isSameLength(twoArrayFloat, twoArrayByte)); - assertTrue(ArrayUtils.isSameLength(twoArrayFloat, twoArrayDouble)); - assertTrue(ArrayUtils.isSameLength(twoArrayFloat, twoArrayFloat)); + public void testLastIndexOfInt() { + int[] array = null; + assertEquals(-1, ArrayUtils.lastIndexOf(array, 0)); + array = new int[]{0, 1, 2, 3, 0}; + assertEquals(4, ArrayUtils.lastIndexOf(array, 0)); + assertEquals(1, ArrayUtils.lastIndexOf(array, 1)); + assertEquals(2, ArrayUtils.lastIndexOf(array, 2)); + assertEquals(3, ArrayUtils.lastIndexOf(array, 3)); + assertEquals(-1, ArrayUtils.lastIndexOf(array, 99)); + } + + @Test + public void testLastIndexOfIntWithStartIndex() { + int[] array = null; + assertEquals(-1, ArrayUtils.lastIndexOf(array, 0, 2)); + array = new int[]{0, 1, 2, 3, 0}; + assertEquals(0, ArrayUtils.lastIndexOf(array, 0, 2)); + assertEquals(1, ArrayUtils.lastIndexOf(array, 1, 2)); + assertEquals(2, ArrayUtils.lastIndexOf(array, 2, 2)); + assertEquals(-1, ArrayUtils.lastIndexOf(array, 3, 2)); + assertEquals(-1, ArrayUtils.lastIndexOf(array, 3, -1)); + assertEquals(-1, ArrayUtils.lastIndexOf(array, 99)); + assertEquals(4, ArrayUtils.lastIndexOf(array, 0, 88)); + } + + @Test + public void testLastIndexOfLong() { + long[] array = null; + assertEquals(-1, ArrayUtils.lastIndexOf(array, 0)); + array = new long[]{0, 1, 2, 3, 0}; + assertEquals(4, ArrayUtils.lastIndexOf(array, 0)); + assertEquals(1, ArrayUtils.lastIndexOf(array, 1)); + assertEquals(2, ArrayUtils.lastIndexOf(array, 2)); + assertEquals(3, ArrayUtils.lastIndexOf(array, 3)); + assertEquals(-1, ArrayUtils.lastIndexOf(array, 99)); + } + + @Test + public void testLastIndexOfLongWithStartIndex() { + long[] array = null; + assertEquals(-1, ArrayUtils.lastIndexOf(array, 0, 2)); + array = new long[]{0, 1, 2, 3, 0}; + assertEquals(0, ArrayUtils.lastIndexOf(array, 0, 2)); + assertEquals(1, ArrayUtils.lastIndexOf(array, 1, 2)); + assertEquals(2, ArrayUtils.lastIndexOf(array, 2, 2)); + assertEquals(-1, ArrayUtils.lastIndexOf(array, 3, 2)); + assertEquals(-1, ArrayUtils.lastIndexOf(array, 3, -1)); + assertEquals(-1, ArrayUtils.lastIndexOf(array, 99, 4)); + assertEquals(4, ArrayUtils.lastIndexOf(array, 0, 88)); + } + + @Test + public void testLastIndexOfShort() { + short[] array = null; + assertEquals(-1, ArrayUtils.lastIndexOf(array, (short) 0)); + array = new short[]{0, 1, 2, 3, 0}; + assertEquals(4, ArrayUtils.lastIndexOf(array, (short) 0)); + assertEquals(1, ArrayUtils.lastIndexOf(array, (short) 1)); + assertEquals(2, ArrayUtils.lastIndexOf(array, (short) 2)); + assertEquals(3, ArrayUtils.lastIndexOf(array, (short) 3)); + assertEquals(-1, ArrayUtils.lastIndexOf(array, (short) 99)); + } + + @Test + public void testLastIndexOfShortWithStartIndex() { + short[] array = null; + assertEquals(-1, ArrayUtils.lastIndexOf(array, (short) 0, 2)); + array = new short[]{0, 1, 2, 3, 0}; + assertEquals(0, ArrayUtils.lastIndexOf(array, (short) 0, 2)); + assertEquals(1, ArrayUtils.lastIndexOf(array, (short) 1, 2)); + assertEquals(2, ArrayUtils.lastIndexOf(array, (short) 2, 2)); + assertEquals(-1, ArrayUtils.lastIndexOf(array, (short) 3, 2)); + assertEquals(-1, ArrayUtils.lastIndexOf(array, (short) 3, -1)); + assertEquals(-1, ArrayUtils.lastIndexOf(array, (short) 99)); + assertEquals(4, ArrayUtils.lastIndexOf(array, (short) 0, 88)); + } + + @Test + public void testLastIndexOfWithStartIndex() { + final Object[] array = new Object[]{"0", "1", "2", "3", null, "0"}; + assertEquals(-1, ArrayUtils.lastIndexOf(null, null, 2)); + assertEquals(-1, ArrayUtils.lastIndexOf(null, "0", 2)); + assertEquals(0, ArrayUtils.lastIndexOf(array, "0", 2)); + assertEquals(1, ArrayUtils.lastIndexOf(array, "1", 2)); + assertEquals(2, ArrayUtils.lastIndexOf(array, "2", 2)); + assertEquals(-1, ArrayUtils.lastIndexOf(array, "3", 2)); + assertEquals(-1, ArrayUtils.lastIndexOf(array, "3", -1)); + assertEquals(4, ArrayUtils.lastIndexOf(array, null, 5)); + assertEquals(-1, ArrayUtils.lastIndexOf(array, null, 2)); + assertEquals(-1, ArrayUtils.lastIndexOf(array, "notInArray", 5)); + + assertEquals(-1, ArrayUtils.lastIndexOf(array, null, -1)); + assertEquals(5, ArrayUtils.lastIndexOf(array, "0", 88)); + } + + @Test + public void testNullToEmptyBoolean() { + final boolean[] original = new boolean[]{true, false}; + assertEquals(original, ArrayUtils.nullToEmpty(original)); + } + + @Test + public void testNullToEmptyBooleanEmptyArray() { + final boolean[] empty = new boolean[]{}; + final boolean[] result = ArrayUtils.nullToEmpty(empty); + assertEquals(ArrayUtils.EMPTY_BOOLEAN_ARRAY, result); + assertNotSame(empty, result); + } + + @Test + public void testNullToEmptyBooleanNull() { + assertEquals(ArrayUtils.EMPTY_BOOLEAN_ARRAY, ArrayUtils.nullToEmpty((boolean[]) null)); + } + + @Test + public void testNullToEmptyBooleanObject() { + final Boolean[] original = new Boolean[]{Boolean.TRUE, Boolean.FALSE}; + assertArrayEquals(original, ArrayUtils.nullToEmpty(original)); + } + + @Test + public void testNullToEmptyBooleanObjectEmptyArray() { + final Boolean[] empty = new Boolean[]{}; + final Boolean[] result = ArrayUtils.nullToEmpty(empty); + assertArrayEquals(ArrayUtils.EMPTY_BOOLEAN_OBJECT_ARRAY, result); + assertNotSame(empty, result); + } + + @Test + public void testNullToEmptyBooleanObjectNull() { + assertArrayEquals(ArrayUtils.EMPTY_BOOLEAN_OBJECT_ARRAY, ArrayUtils.nullToEmpty((Boolean[]) null)); + } + + @Test + public void testNullToEmptyByte() { + final byte[] original = new byte[]{0x0F, 0x0E}; + assertEquals(original, ArrayUtils.nullToEmpty(original)); + } + + @Test + public void testNullToEmptyByteEmptyArray() { + final byte[] empty = new byte[]{}; + final byte[] result = ArrayUtils.nullToEmpty(empty); + assertEquals(ArrayUtils.EMPTY_BYTE_ARRAY, result); + assertNotSame(empty, result); + } + + @Test + public void testNullToEmptyByteNull() { + assertEquals(ArrayUtils.EMPTY_BYTE_ARRAY, ArrayUtils.nullToEmpty((byte[]) null)); + } + + @Test + public void testNullToEmptyByteObject() { + final Byte[] original = new Byte[]{0x0F, 0x0E}; + assertArrayEquals(original, ArrayUtils.nullToEmpty(original)); + } + + @Test + public void testNullToEmptyByteObjectEmptyArray() { + final Byte[] empty = new Byte[]{}; + final Byte[] result = ArrayUtils.nullToEmpty(empty); + assertArrayEquals(ArrayUtils.EMPTY_BYTE_OBJECT_ARRAY, result); + assertNotSame(empty, result); + } + + @Test + public void testNullToEmptyByteObjectNull() { + assertArrayEquals(ArrayUtils.EMPTY_BYTE_OBJECT_ARRAY, ArrayUtils.nullToEmpty((Byte[]) null)); + } + + @Test + public void testNullToEmptyChar() { + final char[] original = new char[]{'a', 'b'}; + assertEquals(original, ArrayUtils.nullToEmpty(original)); + } + + @Test + public void testNullToEmptyCharEmptyArray() { + final char[] empty = new char[]{}; + final char[] result = ArrayUtils.nullToEmpty(empty); + assertEquals(ArrayUtils.EMPTY_CHAR_ARRAY, result); + assertNotSame(empty, result); + } + + @Test + public void testNullToEmptyCharNull() { + assertEquals(ArrayUtils.EMPTY_CHAR_ARRAY, ArrayUtils.nullToEmpty((char[]) null)); + } + + @Test + public void testNullToEmptyCharObject() { + final Character[] original = new Character[]{'a', 'b'}; + assertArrayEquals(original, ArrayUtils.nullToEmpty(original)); + } + + @Test + public void testNullToEmptyCharObjectEmptyArray() { + final Character[] empty = new Character[]{}; + final Character[] result = ArrayUtils.nullToEmpty(empty); + assertArrayEquals(ArrayUtils.EMPTY_CHARACTER_OBJECT_ARRAY, result); + assertNotSame(empty, result); + } + + @Test + public void testNUllToEmptyCharObjectNull() { + assertArrayEquals(ArrayUtils.EMPTY_CHARACTER_OBJECT_ARRAY, ArrayUtils.nullToEmpty((Character[]) null)); + } + + @Test + public void testNullToEmptyClass() { + final Class[] original = {Object.class, String.class}; + assertArrayEquals(original, ArrayUtils.nullToEmpty(original)); + } + + @Test + public void testNullToEmptyClassEmptyArray() { + final Class[] empty = {}; + final Class[] result = ArrayUtils.nullToEmpty(empty); + assertArrayEquals(ArrayUtils.EMPTY_CLASS_ARRAY, result); + assertNotSame(empty, result); + } + + @Test + public void testNullToEmptyClassNull() { + assertArrayEquals(ArrayUtils.EMPTY_CLASS_ARRAY, ArrayUtils.nullToEmpty((Class[]) null)); } - //----------------------------------------------------------------------- @Test - public void testSameType() { - assertThrows(IllegalArgumentException.class, () -> ArrayUtils.isSameType(null, null)); - assertThrows(IllegalArgumentException.class, () -> ArrayUtils.isSameType(null, new Object[0])); - assertThrows(IllegalArgumentException.class, () -> ArrayUtils.isSameType(new Object[0], null)); + public void testNullToEmptyDouble() { + final double[] original = new double[]{1L, 2L}; + assertEquals(original, ArrayUtils.nullToEmpty(original)); + } - assertTrue(ArrayUtils.isSameType(new Object[0], new Object[0])); - assertFalse(ArrayUtils.isSameType(new String[0], new Object[0])); - assertTrue(ArrayUtils.isSameType(new String[0][0], new String[0][0])); - assertFalse(ArrayUtils.isSameType(new String[0], new String[0][0])); - assertFalse(ArrayUtils.isSameType(new String[0][0], new String[0])); + @Test + public void testNullToEmptyDoubleEmptyArray() { + final double[] empty = new double[]{}; + final double[] result = ArrayUtils.nullToEmpty(empty); + assertEquals(ArrayUtils.EMPTY_DOUBLE_ARRAY, result); + assertNotSame(empty, result); } - //----------------------------------------------------------------------- @Test - public void testReverse() { - final StringBuffer str1 = new StringBuffer("pick"); - final String str2 = "a"; - final String[] str3 = new String[]{"stick"}; - final String str4 = "up"; + public void testNullToEmptyDoubleNull() { + assertEquals(ArrayUtils.EMPTY_DOUBLE_ARRAY, ArrayUtils.nullToEmpty((double[]) null)); + } - Object[] array = new Object[]{str1, str2, str3}; - ArrayUtils.reverse(array); - assertEquals(array[0], str3); - assertEquals(array[1], str2); - assertEquals(array[2], str1); + @Test + public void testNullToEmptyDoubleObject() { + final Double[] original = new Double[]{1D, 2D}; + assertArrayEquals(original, ArrayUtils.nullToEmpty(original)); + } - array = new Object[]{str1, str2, str3, str4}; - ArrayUtils.reverse(array); - assertEquals(array[0], str4); - assertEquals(array[1], str3); - assertEquals(array[2], str2); - assertEquals(array[3], str1); + @Test + public void testNullToEmptyDoubleObjectEmptyArray() { + final Double[] empty = new Double[]{}; + final Double[] result = ArrayUtils.nullToEmpty(empty); + assertArrayEquals(ArrayUtils.EMPTY_DOUBLE_OBJECT_ARRAY, result); + assertNotSame(empty, result); + } - array = null; - ArrayUtils.reverse(array); - assertArrayEquals(null, array); + @Test + public void testNullToEmptyDoubleObjectNull() { + assertArrayEquals(ArrayUtils.EMPTY_DOUBLE_OBJECT_ARRAY, ArrayUtils.nullToEmpty((Double[]) null)); } @Test - public void testReverseLong() { - long[] array = new long[]{1L, 2L, 3L}; - ArrayUtils.reverse(array); - assertEquals(array[0], 3L); - assertEquals(array[1], 2L); - assertEquals(array[2], 1L); + public void testNullToEmptyFloat() { + final float[] original = new float[]{2.6f, 3.8f}; + assertEquals(original, ArrayUtils.nullToEmpty(original)); + } - array = null; - ArrayUtils.reverse(array); - assertNull(array); + @Test + public void testNullToEmptyFloatEmptyArray() { + final float[] empty = new float[]{}; + final float[] result = ArrayUtils.nullToEmpty(empty); + assertEquals(ArrayUtils.EMPTY_FLOAT_ARRAY, result); + assertNotSame(empty, result); } @Test - public void testReverseInt() { - int[] array = new int[]{1, 2, 3}; - ArrayUtils.reverse(array); - assertEquals(array[0], 3); - assertEquals(array[1], 2); - assertEquals(array[2], 1); + public void testNullToEmptyFloatNull() { + assertEquals(ArrayUtils.EMPTY_FLOAT_ARRAY, ArrayUtils.nullToEmpty((float[]) null)); + } - array = null; - ArrayUtils.reverse(array); - assertNull(array); + @Test + public void testNullToEmptyFloatObject() { + final Float[] original = new Float[]{2.6f, 3.8f}; + assertArrayEquals(original, ArrayUtils.nullToEmpty(original)); + } + + @Test + public void testNullToEmptyFloatObjectEmptyArray() { + final Float[] empty = new Float[]{}; + final Float[] result = ArrayUtils.nullToEmpty(empty); + assertArrayEquals(ArrayUtils.EMPTY_FLOAT_OBJECT_ARRAY, result); + assertNotSame(empty, result); + } + + @Test + public void testNullToEmptyFloatObjectNull() { + assertArrayEquals(ArrayUtils.EMPTY_FLOAT_OBJECT_ARRAY, ArrayUtils.nullToEmpty((Float[]) null)); + } + + @Test + public void testNullToEmptyGeneric() { + final TestClass[] input = new TestClass[]{new TestClass(), new TestClass()}; + final TestClass[] output = ArrayUtils.nullToEmpty(input, TestClass[].class); + + assertSame(input, output); + } + + @Test + public void testNullToEmptyGenericEmpty() { + final TestClass[] input = new TestClass[]{}; + final TestClass[] output = ArrayUtils.nullToEmpty(input, TestClass[].class); + + assertSame(input, output); + } + + @Test + public void testNullToEmptyGenericNull() { + final TestClass[] output = ArrayUtils.nullToEmpty(null, TestClass[].class); + + assertNotNull(output); + assertEquals(0, output.length); + } + + @Test + public void testNullToEmptyGenericNullType() { + final TestClass[] input = new TestClass[]{}; + assertThrows(IllegalArgumentException.class, () -> ArrayUtils.nullToEmpty(input, null)); + } + + @Test + public void testNullToEmptyInt() { + final int[] original = new int[]{1, 2}; + assertEquals(original, ArrayUtils.nullToEmpty(original)); + } + + @Test + public void testNullToEmptyIntEmptyArray() { + final int[] empty = new int[]{}; + final int[] result = ArrayUtils.nullToEmpty(empty); + assertEquals(ArrayUtils.EMPTY_INT_ARRAY, result); + assertNotSame(empty, result); + } + + @Test + public void testNullToEmptyIntNull() { + assertEquals(ArrayUtils.EMPTY_INT_ARRAY, ArrayUtils.nullToEmpty((int[]) null)); + } + + @Test + public void testNullToEmptyIntObject() { + final Integer[] original = new Integer[]{1, 2}; + assertArrayEquals(original, ArrayUtils.nullToEmpty(original)); + } + + @Test + public void testNullToEmptyIntObjectEmptyArray() { + final Integer[] empty = new Integer[]{}; + final Integer[] result = ArrayUtils.nullToEmpty(empty); + assertArrayEquals(ArrayUtils.EMPTY_INTEGER_OBJECT_ARRAY, result); + assertNotSame(empty, result); + } + + @Test + public void testNullToEmptyIntObjectNull() { + assertArrayEquals(ArrayUtils.EMPTY_INTEGER_OBJECT_ARRAY, ArrayUtils.nullToEmpty((Integer[]) null)); + } + + @Test + public void testNullToEmptyLong() { + final long[] original = new long[]{1L, 2L}; + assertEquals(original, ArrayUtils.nullToEmpty(original)); + } + + @Test + public void testNullToEmptyLongEmptyArray() { + final long[] empty = new long[]{}; + final long[] result = ArrayUtils.nullToEmpty(empty); + assertEquals(ArrayUtils.EMPTY_LONG_ARRAY, result); + assertNotSame(empty, result); + } + + @Test + public void testNullToEmptyLongNull() { + assertEquals(ArrayUtils.EMPTY_LONG_ARRAY, ArrayUtils.nullToEmpty((long[]) null)); + } + + @Test + public void testNullToEmptyLongObject() { + @SuppressWarnings("boxing") final Long[] original = new Long[]{1L, 2L}; + assertArrayEquals(original, ArrayUtils.nullToEmpty(original)); + } + + @Test + public void testNullToEmptyLongObjectEmptyArray() { + final Long[] empty = new Long[]{}; + final Long[] result = ArrayUtils.nullToEmpty(empty); + assertArrayEquals(ArrayUtils.EMPTY_LONG_OBJECT_ARRAY, result); + assertNotSame(empty, result); + } + + @Test + public void testNullToEmptyLongObjectNull() { + assertArrayEquals(ArrayUtils.EMPTY_LONG_OBJECT_ARRAY, ArrayUtils.nullToEmpty((Long[]) null)); + } + + @Test + public void testNullToEmptyObject() { + final Object[] original = new Object[]{Boolean.TRUE, Boolean.FALSE}; + assertArrayEquals(original, ArrayUtils.nullToEmpty(original)); + } + + @Test + public void testNullToEmptyObjectEmptyArray() { + final Object[] empty = new Object[]{}; + final Object[] result = ArrayUtils.nullToEmpty(empty); + assertArrayEquals(ArrayUtils.EMPTY_OBJECT_ARRAY, result); + assertNotSame(empty, result); + } + + @Test + public void testNullToEmptyObjectNull() { + assertArrayEquals(ArrayUtils.EMPTY_OBJECT_ARRAY, ArrayUtils.nullToEmpty((Object[]) null)); + } + + @Test + public void testNullToEmptyShort() { + final short[] original = new short[]{1, 2}; + assertEquals(original, ArrayUtils.nullToEmpty(original)); + } + + @Test + public void testNullToEmptyShortEmptyArray() { + final short[] empty = new short[]{}; + final short[] result = ArrayUtils.nullToEmpty(empty); + assertEquals(ArrayUtils.EMPTY_SHORT_ARRAY, result); + assertNotSame(empty, result); + } + + @Test + public void testNullToEmptyShortNull() { + assertEquals(ArrayUtils.EMPTY_SHORT_ARRAY, ArrayUtils.nullToEmpty((short[]) null)); + } + + @Test + public void testNullToEmptyShortObject() { + @SuppressWarnings("boxing") final Short[] original = new Short[]{1, 2}; + assertArrayEquals(original, ArrayUtils.nullToEmpty(original)); } @Test - public void testReverseShort() { - short[] array = new short[]{1, 2, 3}; - ArrayUtils.reverse(array); - assertEquals(array[0], 3); - assertEquals(array[1], 2); - assertEquals(array[2], 1); - - array = null; - ArrayUtils.reverse(array); - assertNull(array); + public void testNullToEmptyShortObjectEmptyArray() { + final Short[] empty = new Short[]{}; + final Short[] result = ArrayUtils.nullToEmpty(empty); + assertArrayEquals(ArrayUtils.EMPTY_SHORT_OBJECT_ARRAY, result); + assertNotSame(empty, result); } @Test - public void testReverseChar() { - char[] array = new char[]{'a', 'f', 'C'}; - ArrayUtils.reverse(array); - assertEquals(array[0], 'C'); - assertEquals(array[1], 'f'); - assertEquals(array[2], 'a'); + public void testNullToEmptyShortObjectNull() { + assertArrayEquals(ArrayUtils.EMPTY_SHORT_OBJECT_ARRAY, ArrayUtils.nullToEmpty((Short[]) null)); + } - array = null; - ArrayUtils.reverse(array); - assertNull(array); + @Test + public void testNullToEmptyString() { + final String[] original = new String[]{"abc", "def"}; + assertArrayEquals(original, ArrayUtils.nullToEmpty(original)); } @Test - public void testReverseByte() { - byte[] array = new byte[]{2, 3, 4}; - ArrayUtils.reverse(array); - assertEquals(array[0], 4); - assertEquals(array[1], 3); - assertEquals(array[2], 2); + public void testNullToEmptyStringEmptyArray() { + final String[] empty = new String[]{}; + final String[] result = ArrayUtils.nullToEmpty(empty); + assertArrayEquals(ArrayUtils.EMPTY_STRING_ARRAY, result); + assertNotSame(empty, result); + } - array = null; - ArrayUtils.reverse(array); - assertNull(array); + @Test + public void testNullToEmptyStringNull() { + assertArrayEquals(ArrayUtils.EMPTY_STRING_ARRAY, ArrayUtils.nullToEmpty((String[]) null)); } + //----------------------------------------------------------------------- @Test - public void testReverseDouble() { - double[] array = new double[]{0.3d, 0.4d, 0.5d}; - ArrayUtils.reverse(array); - assertEquals(0.5d, array[0]); - assertEquals(0.4d, array[1]); - assertEquals(0.3d, array[2]); + public void testReverse() { + final StringBuffer str1 = new StringBuffer("pick"); + final String str2 = "a"; + final String[] str3 = new String[]{"stick"}; + final String str4 = "up"; - array = null; + Object[] array = new Object[]{str1, str2, str3}; ArrayUtils.reverse(array); - assertNull(array); - } + assertEquals(array[0], str3); + assertEquals(array[1], str2); + assertEquals(array[2], str1); - @Test - public void testReverseFloat() { - float[] array = new float[]{0.3f, 0.4f, 0.5f}; + array = new Object[]{str1, str2, str3, str4}; ArrayUtils.reverse(array); - assertEquals(0.5f, array[0]); - assertEquals(0.4f, array[1]); - assertEquals(0.3f, array[2]); + assertEquals(array[0], str4); + assertEquals(array[1], str3); + assertEquals(array[2], str2); + assertEquals(array[3], str1); array = null; ArrayUtils.reverse(array); - assertNull(array); + assertArrayEquals(null, array); } @Test @@ -2918,123 +2321,40 @@ public void testReverseBooleanRange() { } @Test - public void testReverseByteRange() { - byte[] array = new byte[]{1, 2, 3}; - // The whole array - ArrayUtils.reverse(array, 0, 3); - assertEquals(3, array[0]); - assertEquals(2, array[1]); - assertEquals(1, array[2]); - // a range - array = new byte[]{1, 2, 3}; - ArrayUtils.reverse(array, 0, 2); - assertEquals(2, array[0]); - assertEquals(1, array[1]); - assertEquals(3, array[2]); - // a range with a negative start - array = new byte[]{1, 2, 3}; - ArrayUtils.reverse(array, -1, 3); - assertEquals(3, array[0]); - assertEquals(2, array[1]); - assertEquals(1, array[2]); - // a range with a large stop index - array = new byte[]{1, 2, 3}; - ArrayUtils.reverse(array, -1, array.length + 1000); - assertEquals(3, array[0]); - assertEquals(2, array[1]); - assertEquals(1, array[2]); - // null - array = null; - ArrayUtils.reverse(array, 0, 3); - assertNull(array); - } - - @Test - public void testReverseCharRange() { - char[] array = new char[]{1, 2, 3}; - // The whole array - ArrayUtils.reverse(array, 0, 3); - assertEquals(3, array[0]); - assertEquals(2, array[1]); - assertEquals(1, array[2]); - // a range - array = new char[]{1, 2, 3}; - ArrayUtils.reverse(array, 0, 2); - assertEquals(2, array[0]); - assertEquals(1, array[1]); - assertEquals(3, array[2]); - // a range with a negative start - array = new char[]{1, 2, 3}; - ArrayUtils.reverse(array, -1, 3); - assertEquals(3, array[0]); - assertEquals(2, array[1]); - assertEquals(1, array[2]); - // a range with a large stop index - array = new char[]{1, 2, 3}; - ArrayUtils.reverse(array, -1, array.length + 1000); - assertEquals(3, array[0]); - assertEquals(2, array[1]); - assertEquals(1, array[2]); - // null - array = null; - ArrayUtils.reverse(array, 0, 3); - assertNull(array); - } + public void testReverseByte() { + byte[] array = new byte[]{2, 3, 4}; + ArrayUtils.reverse(array); + assertEquals(array[0], 4); + assertEquals(array[1], 3); + assertEquals(array[2], 2); - @Test - public void testReverseDoubleRange() { - double[] array = new double[]{1, 2, 3}; - // The whole array - ArrayUtils.reverse(array, 0, 3); - assertEquals(3, array[0]); - assertEquals(2, array[1]); - assertEquals(1, array[2]); - // a range - array = new double[]{1, 2, 3}; - ArrayUtils.reverse(array, 0, 2); - assertEquals(2, array[0]); - assertEquals(1, array[1]); - assertEquals(3, array[2]); - // a range with a negative start - array = new double[]{1, 2, 3}; - ArrayUtils.reverse(array, -1, 3); - assertEquals(3, array[0]); - assertEquals(2, array[1]); - assertEquals(1, array[2]); - // a range with a large stop index - array = new double[]{1, 2, 3}; - ArrayUtils.reverse(array, -1, array.length + 1000); - assertEquals(3, array[0]); - assertEquals(2, array[1]); - assertEquals(1, array[2]); - // null array = null; - ArrayUtils.reverse(array, 0, 3); + ArrayUtils.reverse(array); assertNull(array); } @Test - public void testReverseFloatRange() { - float[] array = new float[]{1, 2, 3}; + public void testReverseByteRange() { + byte[] array = new byte[]{1, 2, 3}; // The whole array ArrayUtils.reverse(array, 0, 3); assertEquals(3, array[0]); assertEquals(2, array[1]); assertEquals(1, array[2]); // a range - array = new float[]{1, 2, 3}; + array = new byte[]{1, 2, 3}; ArrayUtils.reverse(array, 0, 2); assertEquals(2, array[0]); assertEquals(1, array[1]); assertEquals(3, array[2]); // a range with a negative start - array = new float[]{1, 2, 3}; + array = new byte[]{1, 2, 3}; ArrayUtils.reverse(array, -1, 3); assertEquals(3, array[0]); assertEquals(2, array[1]); assertEquals(1, array[2]); // a range with a large stop index - array = new float[]{1, 2, 3}; + array = new byte[]{1, 2, 3}; ArrayUtils.reverse(array, -1, array.length + 1000); assertEquals(3, array[0]); assertEquals(2, array[1]); @@ -3046,91 +2366,40 @@ public void testReverseFloatRange() { } @Test - public void testReverseIntRange() { - int[] array = new int[]{1, 2, 3}; - // The whole array - ArrayUtils.reverse(array, 0, 3); - assertEquals(3, array[0]); - assertEquals(2, array[1]); - assertEquals(1, array[2]); - // a range - array = new int[]{1, 2, 3}; - ArrayUtils.reverse(array, 0, 2); - assertEquals(2, array[0]); - assertEquals(1, array[1]); - assertEquals(3, array[2]); - // a range with a negative start - array = new int[]{1, 2, 3}; - ArrayUtils.reverse(array, -1, 3); - assertEquals(3, array[0]); - assertEquals(2, array[1]); - assertEquals(1, array[2]); - // a range with a large stop index - array = new int[]{1, 2, 3}; - ArrayUtils.reverse(array, -1, array.length + 1000); - assertEquals(3, array[0]); - assertEquals(2, array[1]); - assertEquals(1, array[2]); - // null - array = null; - ArrayUtils.reverse(array, 0, 3); - assertNull(array); - } + public void testReverseChar() { + char[] array = new char[]{'a', 'f', 'C'}; + ArrayUtils.reverse(array); + assertEquals(array[0], 'C'); + assertEquals(array[1], 'f'); + assertEquals(array[2], 'a'); - @Test - public void testReverseLongRange() { - long[] array = new long[]{1, 2, 3}; - // The whole array - ArrayUtils.reverse(array, 0, 3); - assertEquals(3, array[0]); - assertEquals(2, array[1]); - assertEquals(1, array[2]); - // a range - array = new long[]{1, 2, 3}; - ArrayUtils.reverse(array, 0, 2); - assertEquals(2, array[0]); - assertEquals(1, array[1]); - assertEquals(3, array[2]); - // a range with a negative start - array = new long[]{1, 2, 3}; - ArrayUtils.reverse(array, -1, 3); - assertEquals(3, array[0]); - assertEquals(2, array[1]); - assertEquals(1, array[2]); - // a range with a large stop index - array = new long[]{1, 2, 3}; - ArrayUtils.reverse(array, -1, array.length + 1000); - assertEquals(3, array[0]); - assertEquals(2, array[1]); - assertEquals(1, array[2]); - // null array = null; - ArrayUtils.reverse(array, 0, 3); + ArrayUtils.reverse(array); assertNull(array); } @Test - public void testReverseShortRange() { - short[] array = new short[]{1, 2, 3}; + public void testReverseCharRange() { + char[] array = new char[]{1, 2, 3}; // The whole array ArrayUtils.reverse(array, 0, 3); assertEquals(3, array[0]); assertEquals(2, array[1]); assertEquals(1, array[2]); // a range - array = new short[]{1, 2, 3}; + array = new char[]{1, 2, 3}; ArrayUtils.reverse(array, 0, 2); assertEquals(2, array[0]); assertEquals(1, array[1]); assertEquals(3, array[2]); // a range with a negative start - array = new short[]{1, 2, 3}; + array = new char[]{1, 2, 3}; ArrayUtils.reverse(array, -1, 3); assertEquals(3, array[0]); assertEquals(2, array[1]); assertEquals(1, array[2]); // a range with a large stop index - array = new short[]{1, 2, 3}; + array = new char[]{1, 2, 3}; ArrayUtils.reverse(array, -1, array.length + 1000); assertEquals(3, array[0]); assertEquals(2, array[1]); @@ -3142,753 +2411,1889 @@ public void testReverseShortRange() { } @Test - public void testReverseObjectRange() { - String[] array = new String[]{"1", "2", "3"}; - // The whole array - ArrayUtils.reverse(array, 0, 3); - assertEquals("3", array[0]); - assertEquals("2", array[1]); - assertEquals("1", array[2]); - // a range - array = new String[]{"1", "2", "3"}; - ArrayUtils.reverse(array, 0, 2); - assertEquals("2", array[0]); - assertEquals("1", array[1]); - assertEquals("3", array[2]); - // a range with a negative start - array = new String[]{"1", "2", "3"}; - ArrayUtils.reverse(array, -1, 3); - assertEquals("3", array[0]); - assertEquals("2", array[1]); - assertEquals("1", array[2]); - // a range with a large stop index - array = new String[]{"1", "2", "3"}; - ArrayUtils.reverse(array, -1, array.length + 1000); - assertEquals("3", array[0]); - assertEquals("2", array[1]); - assertEquals("1", array[2]); - // null + public void testReverseDouble() { + double[] array = new double[]{0.3d, 0.4d, 0.5d}; + ArrayUtils.reverse(array); + assertEquals(0.5d, array[0]); + assertEquals(0.4d, array[1]); + assertEquals(0.3d, array[2]); + array = null; - ArrayUtils.reverse(array, 0, 3); + ArrayUtils.reverse(array); assertNull(array); } - //----------------------------------------------------------------------- - @Test - public void testSwapChar() { - char[] array = new char[]{1, 2, 3}; - ArrayUtils.swap(array, 0, 2); - assertArrayEquals(new char[]{3, 2, 1}, array); - - array = new char[]{1, 2, 3}; - ArrayUtils.swap(array, 0, 0); - assertArrayEquals(new char[]{1, 2, 3}, array); - - array = new char[]{1, 2, 3}; - ArrayUtils.swap(array, 1, 0); - assertArrayEquals(new char[]{2, 1, 3}, array); - } - @Test - public void testSwapCharRange() { - char[] array = new char[]{1, 2, 3, 4}; - ArrayUtils.swap(array, 0, 2, 2); + public void testReverseDoubleRange() { + double[] array = new double[]{1, 2, 3}; + // The whole array + ArrayUtils.reverse(array, 0, 3); assertEquals(3, array[0]); - assertEquals(4, array[1]); - assertEquals(1, array[2]); - assertEquals(2, array[3]); - - array = new char[]{1, 2, 3}; - ArrayUtils.swap(array, 0, 3); - assertEquals(1, array[0]); assertEquals(2, array[1]); + assertEquals(1, array[2]); + // a range + array = new double[]{1, 2, 3}; + ArrayUtils.reverse(array, 0, 2); + assertEquals(2, array[0]); + assertEquals(1, array[1]); assertEquals(3, array[2]); - - array = new char[]{1, 2, 3}; - ArrayUtils.swap(array, 0, 2, 2); + // a range with a negative start + array = new double[]{1, 2, 3}; + ArrayUtils.reverse(array, -1, 3); assertEquals(3, array[0]); assertEquals(2, array[1]); assertEquals(1, array[2]); - - array = new char[]{1, 2, 3}; - ArrayUtils.swap(array, -1, 2, 2); + // a range with a large stop index + array = new double[]{1, 2, 3}; + ArrayUtils.reverse(array, -1, array.length + 1000); assertEquals(3, array[0]); assertEquals(2, array[1]); assertEquals(1, array[2]); - - array = new char[]{1, 2, 3}; - ArrayUtils.swap(array, 0, -1, 2); - assertEquals(1, array[0]); - assertEquals(2, array[1]); - assertEquals(3, array[2]); - - array = new char[]{1, 2, 3}; - ArrayUtils.swap(array, -1, -1, 2); - assertEquals(1, array[0]); - assertEquals(2, array[1]); - assertEquals(3, array[2]); + // null + array = null; + ArrayUtils.reverse(array, 0, 3); + assertNull(array); } @Test - public void testSwapByte() { - final byte[] array = new byte[]{1, 2, 3}; - ArrayUtils.swap(array, 0, 2); - assertEquals(3, array[0]); - assertEquals(2, array[1]); - assertEquals(1, array[2]); - } + public void testReverseFloat() { + float[] array = new float[]{0.3f, 0.4f, 0.5f}; + ArrayUtils.reverse(array); + assertEquals(0.5f, array[0]); + assertEquals(0.4f, array[1]); + assertEquals(0.3f, array[2]); - @Test - public void testSwapNullByteArray() { - final byte[] array = null; - ArrayUtils.swap(array, 0, 2); + array = null; + ArrayUtils.reverse(array); assertNull(array); } @Test - public void testSwapEmptyByteArray() { - final byte[] array = new byte[0]; - ArrayUtils.swap(array, 0, 2); - assertEquals(0, array.length); - } - - @Test - public void testSwapByteRange() { - byte[] array = new byte[]{1, 2, 3, 4}; - ArrayUtils.swap(array, 0, 2, 2); + public void testReverseFloatRange() { + float[] array = new float[]{1, 2, 3}; + // The whole array + ArrayUtils.reverse(array, 0, 3); assertEquals(3, array[0]); - assertEquals(4, array[1]); - assertEquals(1, array[2]); - assertEquals(2, array[3]); - - array = new byte[]{1, 2, 3}; - ArrayUtils.swap(array, 0, 3); - assertEquals(1, array[0]); assertEquals(2, array[1]); + assertEquals(1, array[2]); + // a range + array = new float[]{1, 2, 3}; + ArrayUtils.reverse(array, 0, 2); + assertEquals(2, array[0]); + assertEquals(1, array[1]); assertEquals(3, array[2]); - - array = new byte[]{1, 2, 3}; - ArrayUtils.swap(array, 0, 2, 2); + // a range with a negative start + array = new float[]{1, 2, 3}; + ArrayUtils.reverse(array, -1, 3); assertEquals(3, array[0]); assertEquals(2, array[1]); assertEquals(1, array[2]); - - array = new byte[]{1, 2, 3}; - ArrayUtils.swap(array, -1, 2, 2); + // a range with a large stop index + array = new float[]{1, 2, 3}; + ArrayUtils.reverse(array, -1, array.length + 1000); assertEquals(3, array[0]); assertEquals(2, array[1]); assertEquals(1, array[2]); - - array = new byte[]{1, 2, 3}; - ArrayUtils.swap(array, 0, -1, 2); - assertEquals(1, array[0]); - assertEquals(2, array[1]); - assertEquals(3, array[2]); - - array = new byte[]{1, 2, 3}; - ArrayUtils.swap(array, -1, -1, 2); - assertEquals(1, array[0]); - assertEquals(2, array[1]); - assertEquals(3, array[2]); + // null + array = null; + ArrayUtils.reverse(array, 0, 3); + assertNull(array); } @Test - public void testSwapFloat() { - final float[] array = new float[]{1, 2, 3}; - ArrayUtils.swap(array, 0, 2); - assertEquals(3, array[0]); - assertEquals(2, array[1]); - assertEquals(1, array[2]); - } + public void testReverseInt() { + int[] array = new int[]{1, 2, 3}; + ArrayUtils.reverse(array); + assertEquals(array[0], 3); + assertEquals(array[1], 2); + assertEquals(array[2], 1); - @Test - public void testSwapNullFloatArray() { - final float[] array = null; - ArrayUtils.swap(array, 0, 2); + array = null; + ArrayUtils.reverse(array); assertNull(array); } @Test - public void testSwapEmptyFloatArray() { - final float[] array = new float[0]; - ArrayUtils.swap(array, 0, 2); - assertEquals(0, array.length); - } - - @Test - public void testSwapFloatRange() { - float[] array = new float[]{1, 2, 3, 4}; - ArrayUtils.swap(array, 0, 2, 2); - assertEquals(3, array[0]); - assertEquals(4, array[1]); - assertEquals(1, array[2]); - assertEquals(2, array[3]); - - array = new float[]{1, 2, 3}; - ArrayUtils.swap(array, 0, 3); - assertEquals(1, array[0]); - assertEquals(2, array[1]); - assertEquals(3, array[2]); - - array = new float[]{1, 2, 3}; - ArrayUtils.swap(array, 0, 2, 2); + public void testReverseIntRange() { + int[] array = new int[]{1, 2, 3}; + // The whole array + ArrayUtils.reverse(array, 0, 3); assertEquals(3, array[0]); assertEquals(2, array[1]); assertEquals(1, array[2]); - - array = new float[]{1, 2, 3}; - ArrayUtils.swap(array, -1, 2, 2); + // a range + array = new int[]{1, 2, 3}; + ArrayUtils.reverse(array, 0, 2); + assertEquals(2, array[0]); + assertEquals(1, array[1]); + assertEquals(3, array[2]); + // a range with a negative start + array = new int[]{1, 2, 3}; + ArrayUtils.reverse(array, -1, 3); assertEquals(3, array[0]); assertEquals(2, array[1]); assertEquals(1, array[2]); - - array = new float[]{1, 2, 3}; - ArrayUtils.swap(array, 0, -1, 2); - assertEquals(1, array[0]); - assertEquals(2, array[1]); - assertEquals(3, array[2]); - - array = new float[]{1, 2, 3}; - ArrayUtils.swap(array, -1, -1, 2); - assertEquals(1, array[0]); - assertEquals(2, array[1]); - assertEquals(3, array[2]); - } - - @Test - public void testSwapDouble() { - final double[] array = new double[]{1, 2, 3}; - ArrayUtils.swap(array, 0, 2); + // a range with a large stop index + array = new int[]{1, 2, 3}; + ArrayUtils.reverse(array, -1, array.length + 1000); assertEquals(3, array[0]); assertEquals(2, array[1]); assertEquals(1, array[2]); - } - - @Test - public void testSwapNullDoubleArray() { - final double[] array = null; - ArrayUtils.swap(array, 0, 2); + // null + array = null; + ArrayUtils.reverse(array, 0, 3); assertNull(array); } @Test - public void testSwapEmptyDoubleArray() { - final double[] array = new double[0]; - ArrayUtils.swap(array, 0, 2); - assertEquals(0, array.length); + public void testReverseLong() { + long[] array = new long[]{1L, 2L, 3L}; + ArrayUtils.reverse(array); + assertEquals(array[0], 3L); + assertEquals(array[1], 2L); + assertEquals(array[2], 1L); + + array = null; + ArrayUtils.reverse(array); + assertNull(array); } @Test - public void testSwapDoubleRange() { - double[] array = new double[]{1, 2, 3, 4}; - ArrayUtils.swap(array, 0, 2, 2); - assertEquals(3, array[0]); - assertEquals(4, array[1]); - assertEquals(1, array[2]); - assertEquals(2, array[3]); - - array = new double[]{1, 2, 3}; - ArrayUtils.swap(array, 0, 3); - assertEquals(1, array[0]); - assertEquals(2, array[1]); - assertEquals(3, array[2]); - - array = new double[]{1, 2, 3}; - ArrayUtils.swap(array, 0, 2, 2); + public void testReverseLongRange() { + long[] array = new long[]{1, 2, 3}; + // The whole array + ArrayUtils.reverse(array, 0, 3); assertEquals(3, array[0]); assertEquals(2, array[1]); assertEquals(1, array[2]); - - array = new double[]{1, 2, 3}; - ArrayUtils.swap(array, -1, 2, 2); + // a range + array = new long[]{1, 2, 3}; + ArrayUtils.reverse(array, 0, 2); + assertEquals(2, array[0]); + assertEquals(1, array[1]); + assertEquals(3, array[2]); + // a range with a negative start + array = new long[]{1, 2, 3}; + ArrayUtils.reverse(array, -1, 3); assertEquals(3, array[0]); assertEquals(2, array[1]); assertEquals(1, array[2]); - - array = new double[]{1, 2, 3}; - ArrayUtils.swap(array, 0, -1, 2); - assertEquals(1, array[0]); - assertEquals(2, array[1]); - assertEquals(3, array[2]); - - array = new double[]{1, 2, 3}; - ArrayUtils.swap(array, -1, -1, 2); - assertEquals(1, array[0]); - assertEquals(2, array[1]); - assertEquals(3, array[2]); - } - - @Test - public void testSwapInt() { - final int[] array = new int[]{1, 2, 3}; - ArrayUtils.swap(array, 0, 2); + // a range with a large stop index + array = new long[]{1, 2, 3}; + ArrayUtils.reverse(array, -1, array.length + 1000); assertEquals(3, array[0]); assertEquals(2, array[1]); assertEquals(1, array[2]); + // null + array = null; + ArrayUtils.reverse(array, 0, 3); + assertNull(array); } @Test - public void testSwapNullIntArray() { - final int[] array = null; - ArrayUtils.swap(array, 0, 2); + public void testReverseObjectRange() { + String[] array = new String[]{"1", "2", "3"}; + // The whole array + ArrayUtils.reverse(array, 0, 3); + assertEquals("3", array[0]); + assertEquals("2", array[1]); + assertEquals("1", array[2]); + // a range + array = new String[]{"1", "2", "3"}; + ArrayUtils.reverse(array, 0, 2); + assertEquals("2", array[0]); + assertEquals("1", array[1]); + assertEquals("3", array[2]); + // a range with a negative start + array = new String[]{"1", "2", "3"}; + ArrayUtils.reverse(array, -1, 3); + assertEquals("3", array[0]); + assertEquals("2", array[1]); + assertEquals("1", array[2]); + // a range with a large stop index + array = new String[]{"1", "2", "3"}; + ArrayUtils.reverse(array, -1, array.length + 1000); + assertEquals("3", array[0]); + assertEquals("2", array[1]); + assertEquals("1", array[2]); + // null + array = null; + ArrayUtils.reverse(array, 0, 3); assertNull(array); } @Test - public void testSwapEmptyIntArray() { - final int[] array = new int[0]; - ArrayUtils.swap(array, 0, 2); - assertEquals(0, array.length); + public void testReverseShort() { + short[] array = new short[]{1, 2, 3}; + ArrayUtils.reverse(array); + assertEquals(array[0], 3); + assertEquals(array[1], 2); + assertEquals(array[2], 1); + + array = null; + ArrayUtils.reverse(array); + assertNull(array); } @Test - public void testSwapIntRange() { - int[] array = new int[]{1, 2, 3, 4}; - ArrayUtils.swap(array, 0, 2, 2); + public void testReverseShortRange() { + short[] array = new short[]{1, 2, 3}; + // The whole array + ArrayUtils.reverse(array, 0, 3); assertEquals(3, array[0]); - assertEquals(4, array[1]); - assertEquals(1, array[2]); - assertEquals(2, array[3]); - - array = new int[]{1, 2, 3}; - ArrayUtils.swap(array, 3, 0); - assertEquals(1, array[0]); assertEquals(2, array[1]); + assertEquals(1, array[2]); + // a range + array = new short[]{1, 2, 3}; + ArrayUtils.reverse(array, 0, 2); + assertEquals(2, array[0]); + assertEquals(1, array[1]); assertEquals(3, array[2]); - - array = new int[]{1, 2, 3}; - ArrayUtils.swap(array, 0, 2, 2); + // a range with a negative start + array = new short[]{1, 2, 3}; + ArrayUtils.reverse(array, -1, 3); assertEquals(3, array[0]); assertEquals(2, array[1]); assertEquals(1, array[2]); - - array = new int[]{1, 2, 3}; - ArrayUtils.swap(array, -1, 2, 2); + // a range with a large stop index + array = new short[]{1, 2, 3}; + ArrayUtils.reverse(array, -1, array.length + 1000); assertEquals(3, array[0]); assertEquals(2, array[1]); assertEquals(1, array[2]); - - array = new int[]{1, 2, 3}; - ArrayUtils.swap(array, 0, -1, 2); - assertEquals(1, array[0]); - assertEquals(2, array[1]); - assertEquals(3, array[2]); - - array = new int[]{1, 2, 3}; - ArrayUtils.swap(array, -1, -1, 2); - assertEquals(1, array[0]); - assertEquals(2, array[1]); - assertEquals(3, array[2]); + // null + array = null; + ArrayUtils.reverse(array, 0, 3); + assertNull(array); } + //----------------------------------------------------------------------- @Test - public void testSwapIntExchangedOffsets() { - int[] array; - array = new int[]{1, 2, 3}; - ArrayUtils.swap(array, 0, 1, 2); - assertArrayEquals(new int[]{2, 3, 1}, array); + public void testSameLength() { + final Object[] nullArray = null; + final Object[] emptyArray = new Object[0]; + final Object[] oneArray = new Object[]{"pick"}; + final Object[] twoArray = new Object[]{"pick", "stick"}; - array = new int[]{1, 2, 3}; - ArrayUtils.swap(array, 1, 0, 2); - assertArrayEquals(new int[]{2, 3, 1}, array); - } + assertTrue(ArrayUtils.isSameLength(nullArray, nullArray)); + assertTrue(ArrayUtils.isSameLength(nullArray, emptyArray)); + assertFalse(ArrayUtils.isSameLength(nullArray, oneArray)); + assertFalse(ArrayUtils.isSameLength(nullArray, twoArray)); - @Test - public void testSwapShort() { - final short[] array = new short[]{1, 2, 3}; - ArrayUtils.swap(array, 0, 2); - assertEquals(3, array[0]); - assertEquals(2, array[1]); - assertEquals(1, array[2]); - } + assertTrue(ArrayUtils.isSameLength(emptyArray, nullArray)); + assertTrue(ArrayUtils.isSameLength(emptyArray, emptyArray)); + assertFalse(ArrayUtils.isSameLength(emptyArray, oneArray)); + assertFalse(ArrayUtils.isSameLength(emptyArray, twoArray)); - @Test - public void testSwapNullShortArray() { - final short[] array = null; - ArrayUtils.swap(array, 0, 2); - assertNull(array); + assertFalse(ArrayUtils.isSameLength(oneArray, nullArray)); + assertFalse(ArrayUtils.isSameLength(oneArray, emptyArray)); + assertTrue(ArrayUtils.isSameLength(oneArray, oneArray)); + assertFalse(ArrayUtils.isSameLength(oneArray, twoArray)); + + assertFalse(ArrayUtils.isSameLength(twoArray, nullArray)); + assertFalse(ArrayUtils.isSameLength(twoArray, emptyArray)); + assertFalse(ArrayUtils.isSameLength(twoArray, oneArray)); + assertTrue(ArrayUtils.isSameLength(twoArray, twoArray)); } @Test - public void testSwapEmptyShortArray() { - final short[] array = new short[0]; - ArrayUtils.swap(array, 0, 2); - assertEquals(0, array.length); + public void testSameLengthAll() { + final Object[] nullArrayObject = null; + final Object[] emptyArrayObject = new Object[0]; + final Object[] oneArrayObject = new Object[]{"pick"}; + final Object[] twoArrayObject = new Object[]{"pick", "stick"}; + final boolean[] nullArrayBoolean = null; + final boolean[] emptyArrayBoolean = new boolean[0]; + final boolean[] oneArrayBoolean = new boolean[]{true}; + final boolean[] twoArrayBoolean = new boolean[]{true, false}; + final long[] nullArrayLong = null; + final long[] emptyArrayLong = new long[0]; + final long[] oneArrayLong = new long[]{0L}; + final long[] twoArrayLong = new long[]{0L, 76L}; + final int[] nullArrayInt = null; + final int[] emptyArrayInt = new int[0]; + final int[] oneArrayInt = new int[]{4}; + final int[] twoArrayInt = new int[]{5, 7}; + final short[] nullArrayShort = null; + final short[] emptyArrayShort = new short[0]; + final short[] oneArrayShort = new short[]{4}; + final short[] twoArrayShort = new short[]{6, 8}; + final char[] nullArrayChar = null; + final char[] emptyArrayChar = new char[0]; + final char[] oneArrayChar = new char[]{'f'}; + final char[] twoArrayChar = new char[]{'d', 't'}; + final byte[] nullArrayByte = null; + final byte[] emptyArrayByte = new byte[0]; + final byte[] oneArrayByte = new byte[]{3}; + final byte[] twoArrayByte = new byte[]{4, 6}; + final double[] nullArrayDouble = null; + final double[] emptyArrayDouble = new double[0]; + final double[] oneArrayDouble = new double[]{1.3d}; + final double[] twoArrayDouble = new double[]{4.5d, 6.3d}; + final float[] nullArrayFloat = null; + final float[] emptyArrayFloat = new float[0]; + final float[] oneArrayFloat = new float[]{2.5f}; + final float[] twoArrayFloat = new float[]{6.4f, 5.8f}; + assertTrue(ArrayUtils.isSameLength(nullArrayObject, nullArrayObject)); + assertTrue(ArrayUtils.isSameLength(nullArrayObject, nullArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(nullArrayObject, nullArrayLong)); + assertTrue(ArrayUtils.isSameLength(nullArrayObject, nullArrayInt)); + assertTrue(ArrayUtils.isSameLength(nullArrayObject, nullArrayShort)); + assertTrue(ArrayUtils.isSameLength(nullArrayObject, nullArrayChar)); + assertTrue(ArrayUtils.isSameLength(nullArrayObject, nullArrayByte)); + assertTrue(ArrayUtils.isSameLength(nullArrayObject, nullArrayDouble)); + assertTrue(ArrayUtils.isSameLength(nullArrayObject, nullArrayFloat)); + assertTrue(ArrayUtils.isSameLength(nullArrayBoolean, nullArrayObject)); + assertTrue(ArrayUtils.isSameLength(nullArrayBoolean, nullArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(nullArrayBoolean, nullArrayLong)); + assertTrue(ArrayUtils.isSameLength(nullArrayBoolean, nullArrayInt)); + assertTrue(ArrayUtils.isSameLength(nullArrayBoolean, nullArrayShort)); + assertTrue(ArrayUtils.isSameLength(nullArrayBoolean, nullArrayChar)); + assertTrue(ArrayUtils.isSameLength(nullArrayBoolean, nullArrayByte)); + assertTrue(ArrayUtils.isSameLength(nullArrayBoolean, nullArrayDouble)); + assertTrue(ArrayUtils.isSameLength(nullArrayBoolean, nullArrayFloat)); + assertTrue(ArrayUtils.isSameLength(nullArrayLong, nullArrayObject)); + assertTrue(ArrayUtils.isSameLength(nullArrayLong, nullArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(nullArrayLong, nullArrayLong)); + assertTrue(ArrayUtils.isSameLength(nullArrayLong, nullArrayInt)); + assertTrue(ArrayUtils.isSameLength(nullArrayLong, nullArrayShort)); + assertTrue(ArrayUtils.isSameLength(nullArrayLong, nullArrayChar)); + assertTrue(ArrayUtils.isSameLength(nullArrayLong, nullArrayByte)); + assertTrue(ArrayUtils.isSameLength(nullArrayLong, nullArrayDouble)); + assertTrue(ArrayUtils.isSameLength(nullArrayLong, nullArrayFloat)); + assertTrue(ArrayUtils.isSameLength(nullArrayInt, nullArrayObject)); + assertTrue(ArrayUtils.isSameLength(nullArrayInt, nullArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(nullArrayInt, nullArrayLong)); + assertTrue(ArrayUtils.isSameLength(nullArrayInt, nullArrayInt)); + assertTrue(ArrayUtils.isSameLength(nullArrayInt, nullArrayShort)); + assertTrue(ArrayUtils.isSameLength(nullArrayInt, nullArrayChar)); + assertTrue(ArrayUtils.isSameLength(nullArrayInt, nullArrayByte)); + assertTrue(ArrayUtils.isSameLength(nullArrayInt, nullArrayDouble)); + assertTrue(ArrayUtils.isSameLength(nullArrayInt, nullArrayFloat)); + assertTrue(ArrayUtils.isSameLength(nullArrayShort, nullArrayObject)); + assertTrue(ArrayUtils.isSameLength(nullArrayShort, nullArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(nullArrayShort, nullArrayLong)); + assertTrue(ArrayUtils.isSameLength(nullArrayShort, nullArrayInt)); + assertTrue(ArrayUtils.isSameLength(nullArrayShort, nullArrayShort)); + assertTrue(ArrayUtils.isSameLength(nullArrayShort, nullArrayChar)); + assertTrue(ArrayUtils.isSameLength(nullArrayShort, nullArrayByte)); + assertTrue(ArrayUtils.isSameLength(nullArrayShort, nullArrayDouble)); + assertTrue(ArrayUtils.isSameLength(nullArrayShort, nullArrayFloat)); + assertTrue(ArrayUtils.isSameLength(nullArrayChar, nullArrayObject)); + assertTrue(ArrayUtils.isSameLength(nullArrayChar, nullArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(nullArrayChar, nullArrayLong)); + assertTrue(ArrayUtils.isSameLength(nullArrayChar, nullArrayInt)); + assertTrue(ArrayUtils.isSameLength(nullArrayChar, nullArrayShort)); + assertTrue(ArrayUtils.isSameLength(nullArrayChar, nullArrayChar)); + assertTrue(ArrayUtils.isSameLength(nullArrayChar, nullArrayByte)); + assertTrue(ArrayUtils.isSameLength(nullArrayChar, nullArrayDouble)); + assertTrue(ArrayUtils.isSameLength(nullArrayChar, nullArrayFloat)); + assertTrue(ArrayUtils.isSameLength(nullArrayByte, nullArrayObject)); + assertTrue(ArrayUtils.isSameLength(nullArrayByte, nullArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(nullArrayByte, nullArrayLong)); + assertTrue(ArrayUtils.isSameLength(nullArrayByte, nullArrayInt)); + assertTrue(ArrayUtils.isSameLength(nullArrayByte, nullArrayShort)); + assertTrue(ArrayUtils.isSameLength(nullArrayByte, nullArrayChar)); + assertTrue(ArrayUtils.isSameLength(nullArrayByte, nullArrayByte)); + assertTrue(ArrayUtils.isSameLength(nullArrayByte, nullArrayDouble)); + assertTrue(ArrayUtils.isSameLength(nullArrayByte, nullArrayFloat)); + assertTrue(ArrayUtils.isSameLength(nullArrayDouble, nullArrayObject)); + assertTrue(ArrayUtils.isSameLength(nullArrayDouble, nullArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(nullArrayDouble, nullArrayLong)); + assertTrue(ArrayUtils.isSameLength(nullArrayDouble, nullArrayInt)); + assertTrue(ArrayUtils.isSameLength(nullArrayDouble, nullArrayShort)); + assertTrue(ArrayUtils.isSameLength(nullArrayDouble, nullArrayChar)); + assertTrue(ArrayUtils.isSameLength(nullArrayDouble, nullArrayByte)); + assertTrue(ArrayUtils.isSameLength(nullArrayDouble, nullArrayDouble)); + assertTrue(ArrayUtils.isSameLength(nullArrayDouble, nullArrayFloat)); + assertTrue(ArrayUtils.isSameLength(nullArrayFloat, nullArrayObject)); + assertTrue(ArrayUtils.isSameLength(nullArrayFloat, nullArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(nullArrayFloat, nullArrayLong)); + assertTrue(ArrayUtils.isSameLength(nullArrayFloat, nullArrayInt)); + assertTrue(ArrayUtils.isSameLength(nullArrayFloat, nullArrayShort)); + assertTrue(ArrayUtils.isSameLength(nullArrayFloat, nullArrayChar)); + assertTrue(ArrayUtils.isSameLength(nullArrayFloat, nullArrayByte)); + assertTrue(ArrayUtils.isSameLength(nullArrayFloat, nullArrayDouble)); + assertTrue(ArrayUtils.isSameLength(nullArrayFloat, nullArrayFloat)); + assertTrue(ArrayUtils.isSameLength(nullArrayObject, emptyArrayObject)); + assertTrue(ArrayUtils.isSameLength(nullArrayObject, emptyArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(nullArrayObject, emptyArrayLong)); + assertTrue(ArrayUtils.isSameLength(nullArrayObject, emptyArrayInt)); + assertTrue(ArrayUtils.isSameLength(nullArrayObject, emptyArrayShort)); + assertTrue(ArrayUtils.isSameLength(nullArrayObject, emptyArrayChar)); + assertTrue(ArrayUtils.isSameLength(nullArrayObject, emptyArrayByte)); + assertTrue(ArrayUtils.isSameLength(nullArrayObject, emptyArrayDouble)); + assertTrue(ArrayUtils.isSameLength(nullArrayObject, emptyArrayFloat)); + assertTrue(ArrayUtils.isSameLength(nullArrayBoolean, emptyArrayObject)); + assertTrue(ArrayUtils.isSameLength(nullArrayBoolean, emptyArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(nullArrayBoolean, emptyArrayLong)); + assertTrue(ArrayUtils.isSameLength(nullArrayBoolean, emptyArrayInt)); + assertTrue(ArrayUtils.isSameLength(nullArrayBoolean, emptyArrayShort)); + assertTrue(ArrayUtils.isSameLength(nullArrayBoolean, emptyArrayChar)); + assertTrue(ArrayUtils.isSameLength(nullArrayBoolean, emptyArrayByte)); + assertTrue(ArrayUtils.isSameLength(nullArrayBoolean, emptyArrayDouble)); + assertTrue(ArrayUtils.isSameLength(nullArrayBoolean, emptyArrayFloat)); + assertTrue(ArrayUtils.isSameLength(nullArrayLong, emptyArrayObject)); + assertTrue(ArrayUtils.isSameLength(nullArrayLong, emptyArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(nullArrayLong, emptyArrayLong)); + assertTrue(ArrayUtils.isSameLength(nullArrayLong, emptyArrayInt)); + assertTrue(ArrayUtils.isSameLength(nullArrayLong, emptyArrayShort)); + assertTrue(ArrayUtils.isSameLength(nullArrayLong, emptyArrayChar)); + assertTrue(ArrayUtils.isSameLength(nullArrayLong, emptyArrayByte)); + assertTrue(ArrayUtils.isSameLength(nullArrayLong, emptyArrayDouble)); + assertTrue(ArrayUtils.isSameLength(nullArrayLong, emptyArrayFloat)); + assertTrue(ArrayUtils.isSameLength(nullArrayInt, emptyArrayObject)); + assertTrue(ArrayUtils.isSameLength(nullArrayInt, emptyArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(nullArrayInt, emptyArrayLong)); + assertTrue(ArrayUtils.isSameLength(nullArrayInt, emptyArrayInt)); + assertTrue(ArrayUtils.isSameLength(nullArrayInt, emptyArrayShort)); + assertTrue(ArrayUtils.isSameLength(nullArrayInt, emptyArrayChar)); + assertTrue(ArrayUtils.isSameLength(nullArrayInt, emptyArrayByte)); + assertTrue(ArrayUtils.isSameLength(nullArrayInt, emptyArrayDouble)); + assertTrue(ArrayUtils.isSameLength(nullArrayInt, emptyArrayFloat)); + assertTrue(ArrayUtils.isSameLength(nullArrayShort, emptyArrayObject)); + assertTrue(ArrayUtils.isSameLength(nullArrayShort, emptyArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(nullArrayShort, emptyArrayLong)); + assertTrue(ArrayUtils.isSameLength(nullArrayShort, emptyArrayInt)); + assertTrue(ArrayUtils.isSameLength(nullArrayShort, emptyArrayShort)); + assertTrue(ArrayUtils.isSameLength(nullArrayShort, emptyArrayChar)); + assertTrue(ArrayUtils.isSameLength(nullArrayShort, emptyArrayByte)); + assertTrue(ArrayUtils.isSameLength(nullArrayShort, emptyArrayDouble)); + assertTrue(ArrayUtils.isSameLength(nullArrayShort, emptyArrayFloat)); + assertTrue(ArrayUtils.isSameLength(nullArrayChar, emptyArrayObject)); + assertTrue(ArrayUtils.isSameLength(nullArrayChar, emptyArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(nullArrayChar, emptyArrayLong)); + assertTrue(ArrayUtils.isSameLength(nullArrayChar, emptyArrayInt)); + assertTrue(ArrayUtils.isSameLength(nullArrayChar, emptyArrayShort)); + assertTrue(ArrayUtils.isSameLength(nullArrayChar, emptyArrayChar)); + assertTrue(ArrayUtils.isSameLength(nullArrayChar, emptyArrayByte)); + assertTrue(ArrayUtils.isSameLength(nullArrayChar, emptyArrayDouble)); + assertTrue(ArrayUtils.isSameLength(nullArrayChar, emptyArrayFloat)); + assertTrue(ArrayUtils.isSameLength(nullArrayByte, emptyArrayObject)); + assertTrue(ArrayUtils.isSameLength(nullArrayByte, emptyArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(nullArrayByte, emptyArrayLong)); + assertTrue(ArrayUtils.isSameLength(nullArrayByte, emptyArrayInt)); + assertTrue(ArrayUtils.isSameLength(nullArrayByte, emptyArrayShort)); + assertTrue(ArrayUtils.isSameLength(nullArrayByte, emptyArrayChar)); + assertTrue(ArrayUtils.isSameLength(nullArrayByte, emptyArrayByte)); + assertTrue(ArrayUtils.isSameLength(nullArrayByte, emptyArrayDouble)); + assertTrue(ArrayUtils.isSameLength(nullArrayByte, emptyArrayFloat)); + assertTrue(ArrayUtils.isSameLength(nullArrayDouble, emptyArrayObject)); + assertTrue(ArrayUtils.isSameLength(nullArrayDouble, emptyArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(nullArrayDouble, emptyArrayLong)); + assertTrue(ArrayUtils.isSameLength(nullArrayDouble, emptyArrayInt)); + assertTrue(ArrayUtils.isSameLength(nullArrayDouble, emptyArrayShort)); + assertTrue(ArrayUtils.isSameLength(nullArrayDouble, emptyArrayChar)); + assertTrue(ArrayUtils.isSameLength(nullArrayDouble, emptyArrayByte)); + assertTrue(ArrayUtils.isSameLength(nullArrayDouble, emptyArrayDouble)); + assertTrue(ArrayUtils.isSameLength(nullArrayDouble, emptyArrayFloat)); + assertTrue(ArrayUtils.isSameLength(nullArrayFloat, emptyArrayObject)); + assertTrue(ArrayUtils.isSameLength(nullArrayFloat, emptyArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(nullArrayFloat, emptyArrayLong)); + assertTrue(ArrayUtils.isSameLength(nullArrayFloat, emptyArrayInt)); + assertTrue(ArrayUtils.isSameLength(nullArrayFloat, emptyArrayShort)); + assertTrue(ArrayUtils.isSameLength(nullArrayFloat, emptyArrayChar)); + assertTrue(ArrayUtils.isSameLength(nullArrayFloat, emptyArrayByte)); + assertTrue(ArrayUtils.isSameLength(nullArrayFloat, emptyArrayDouble)); + assertTrue(ArrayUtils.isSameLength(nullArrayFloat, emptyArrayFloat)); + assertFalse(ArrayUtils.isSameLength(nullArrayObject, oneArrayObject)); + assertFalse(ArrayUtils.isSameLength(nullArrayObject, oneArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(nullArrayObject, oneArrayLong)); + assertFalse(ArrayUtils.isSameLength(nullArrayObject, oneArrayInt)); + assertFalse(ArrayUtils.isSameLength(nullArrayObject, oneArrayShort)); + assertFalse(ArrayUtils.isSameLength(nullArrayObject, oneArrayChar)); + assertFalse(ArrayUtils.isSameLength(nullArrayObject, oneArrayByte)); + assertFalse(ArrayUtils.isSameLength(nullArrayObject, oneArrayDouble)); + assertFalse(ArrayUtils.isSameLength(nullArrayObject, oneArrayFloat)); + assertFalse(ArrayUtils.isSameLength(nullArrayBoolean, oneArrayObject)); + assertFalse(ArrayUtils.isSameLength(nullArrayBoolean, oneArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(nullArrayBoolean, oneArrayLong)); + assertFalse(ArrayUtils.isSameLength(nullArrayBoolean, oneArrayInt)); + assertFalse(ArrayUtils.isSameLength(nullArrayBoolean, oneArrayShort)); + assertFalse(ArrayUtils.isSameLength(nullArrayBoolean, oneArrayChar)); + assertFalse(ArrayUtils.isSameLength(nullArrayBoolean, oneArrayByte)); + assertFalse(ArrayUtils.isSameLength(nullArrayBoolean, oneArrayDouble)); + assertFalse(ArrayUtils.isSameLength(nullArrayBoolean, oneArrayFloat)); + assertFalse(ArrayUtils.isSameLength(nullArrayLong, oneArrayObject)); + assertFalse(ArrayUtils.isSameLength(nullArrayLong, oneArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(nullArrayLong, oneArrayLong)); + assertFalse(ArrayUtils.isSameLength(nullArrayLong, oneArrayInt)); + assertFalse(ArrayUtils.isSameLength(nullArrayLong, oneArrayShort)); + assertFalse(ArrayUtils.isSameLength(nullArrayLong, oneArrayChar)); + assertFalse(ArrayUtils.isSameLength(nullArrayLong, oneArrayByte)); + assertFalse(ArrayUtils.isSameLength(nullArrayLong, oneArrayDouble)); + assertFalse(ArrayUtils.isSameLength(nullArrayLong, oneArrayFloat)); + assertFalse(ArrayUtils.isSameLength(nullArrayInt, oneArrayObject)); + assertFalse(ArrayUtils.isSameLength(nullArrayInt, oneArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(nullArrayInt, oneArrayLong)); + assertFalse(ArrayUtils.isSameLength(nullArrayInt, oneArrayInt)); + assertFalse(ArrayUtils.isSameLength(nullArrayInt, oneArrayShort)); + assertFalse(ArrayUtils.isSameLength(nullArrayInt, oneArrayChar)); + assertFalse(ArrayUtils.isSameLength(nullArrayInt, oneArrayByte)); + assertFalse(ArrayUtils.isSameLength(nullArrayInt, oneArrayDouble)); + assertFalse(ArrayUtils.isSameLength(nullArrayInt, oneArrayFloat)); + assertFalse(ArrayUtils.isSameLength(nullArrayShort, oneArrayObject)); + assertFalse(ArrayUtils.isSameLength(nullArrayShort, oneArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(nullArrayShort, oneArrayLong)); + assertFalse(ArrayUtils.isSameLength(nullArrayShort, oneArrayInt)); + assertFalse(ArrayUtils.isSameLength(nullArrayShort, oneArrayShort)); + assertFalse(ArrayUtils.isSameLength(nullArrayShort, oneArrayChar)); + assertFalse(ArrayUtils.isSameLength(nullArrayShort, oneArrayByte)); + assertFalse(ArrayUtils.isSameLength(nullArrayShort, oneArrayDouble)); + assertFalse(ArrayUtils.isSameLength(nullArrayShort, oneArrayFloat)); + assertFalse(ArrayUtils.isSameLength(nullArrayChar, oneArrayObject)); + assertFalse(ArrayUtils.isSameLength(nullArrayChar, oneArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(nullArrayChar, oneArrayLong)); + assertFalse(ArrayUtils.isSameLength(nullArrayChar, oneArrayInt)); + assertFalse(ArrayUtils.isSameLength(nullArrayChar, oneArrayShort)); + assertFalse(ArrayUtils.isSameLength(nullArrayChar, oneArrayChar)); + assertFalse(ArrayUtils.isSameLength(nullArrayChar, oneArrayByte)); + assertFalse(ArrayUtils.isSameLength(nullArrayChar, oneArrayDouble)); + assertFalse(ArrayUtils.isSameLength(nullArrayChar, oneArrayFloat)); + assertFalse(ArrayUtils.isSameLength(nullArrayByte, oneArrayObject)); + assertFalse(ArrayUtils.isSameLength(nullArrayByte, oneArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(nullArrayByte, oneArrayLong)); + assertFalse(ArrayUtils.isSameLength(nullArrayByte, oneArrayInt)); + assertFalse(ArrayUtils.isSameLength(nullArrayByte, oneArrayShort)); + assertFalse(ArrayUtils.isSameLength(nullArrayByte, oneArrayChar)); + assertFalse(ArrayUtils.isSameLength(nullArrayByte, oneArrayByte)); + assertFalse(ArrayUtils.isSameLength(nullArrayByte, oneArrayDouble)); + assertFalse(ArrayUtils.isSameLength(nullArrayByte, oneArrayFloat)); + assertFalse(ArrayUtils.isSameLength(nullArrayDouble, oneArrayObject)); + assertFalse(ArrayUtils.isSameLength(nullArrayDouble, oneArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(nullArrayDouble, oneArrayLong)); + assertFalse(ArrayUtils.isSameLength(nullArrayDouble, oneArrayInt)); + assertFalse(ArrayUtils.isSameLength(nullArrayDouble, oneArrayShort)); + assertFalse(ArrayUtils.isSameLength(nullArrayDouble, oneArrayChar)); + assertFalse(ArrayUtils.isSameLength(nullArrayDouble, oneArrayByte)); + assertFalse(ArrayUtils.isSameLength(nullArrayDouble, oneArrayDouble)); + assertFalse(ArrayUtils.isSameLength(nullArrayDouble, oneArrayFloat)); + assertFalse(ArrayUtils.isSameLength(nullArrayFloat, oneArrayObject)); + assertFalse(ArrayUtils.isSameLength(nullArrayFloat, oneArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(nullArrayFloat, oneArrayLong)); + assertFalse(ArrayUtils.isSameLength(nullArrayFloat, oneArrayInt)); + assertFalse(ArrayUtils.isSameLength(nullArrayFloat, oneArrayShort)); + assertFalse(ArrayUtils.isSameLength(nullArrayFloat, oneArrayChar)); + assertFalse(ArrayUtils.isSameLength(nullArrayFloat, oneArrayByte)); + assertFalse(ArrayUtils.isSameLength(nullArrayFloat, oneArrayDouble)); + assertFalse(ArrayUtils.isSameLength(nullArrayFloat, oneArrayFloat)); + assertFalse(ArrayUtils.isSameLength(nullArrayObject, twoArrayObject)); + assertFalse(ArrayUtils.isSameLength(nullArrayObject, twoArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(nullArrayObject, twoArrayLong)); + assertFalse(ArrayUtils.isSameLength(nullArrayObject, twoArrayInt)); + assertFalse(ArrayUtils.isSameLength(nullArrayObject, twoArrayShort)); + assertFalse(ArrayUtils.isSameLength(nullArrayObject, twoArrayChar)); + assertFalse(ArrayUtils.isSameLength(nullArrayObject, twoArrayByte)); + assertFalse(ArrayUtils.isSameLength(nullArrayObject, twoArrayDouble)); + assertFalse(ArrayUtils.isSameLength(nullArrayObject, twoArrayFloat)); + assertFalse(ArrayUtils.isSameLength(nullArrayBoolean, twoArrayObject)); + assertFalse(ArrayUtils.isSameLength(nullArrayBoolean, twoArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(nullArrayBoolean, twoArrayLong)); + assertFalse(ArrayUtils.isSameLength(nullArrayBoolean, twoArrayInt)); + assertFalse(ArrayUtils.isSameLength(nullArrayBoolean, twoArrayShort)); + assertFalse(ArrayUtils.isSameLength(nullArrayBoolean, twoArrayChar)); + assertFalse(ArrayUtils.isSameLength(nullArrayBoolean, twoArrayByte)); + assertFalse(ArrayUtils.isSameLength(nullArrayBoolean, twoArrayDouble)); + assertFalse(ArrayUtils.isSameLength(nullArrayBoolean, twoArrayFloat)); + assertFalse(ArrayUtils.isSameLength(nullArrayLong, twoArrayObject)); + assertFalse(ArrayUtils.isSameLength(nullArrayLong, twoArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(nullArrayLong, twoArrayLong)); + assertFalse(ArrayUtils.isSameLength(nullArrayLong, twoArrayInt)); + assertFalse(ArrayUtils.isSameLength(nullArrayLong, twoArrayShort)); + assertFalse(ArrayUtils.isSameLength(nullArrayLong, twoArrayChar)); + assertFalse(ArrayUtils.isSameLength(nullArrayLong, twoArrayByte)); + assertFalse(ArrayUtils.isSameLength(nullArrayLong, twoArrayDouble)); + assertFalse(ArrayUtils.isSameLength(nullArrayLong, twoArrayFloat)); + assertFalse(ArrayUtils.isSameLength(nullArrayInt, twoArrayObject)); + assertFalse(ArrayUtils.isSameLength(nullArrayInt, twoArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(nullArrayInt, twoArrayLong)); + assertFalse(ArrayUtils.isSameLength(nullArrayInt, twoArrayInt)); + assertFalse(ArrayUtils.isSameLength(nullArrayInt, twoArrayShort)); + assertFalse(ArrayUtils.isSameLength(nullArrayInt, twoArrayChar)); + assertFalse(ArrayUtils.isSameLength(nullArrayInt, twoArrayByte)); + assertFalse(ArrayUtils.isSameLength(nullArrayInt, twoArrayDouble)); + assertFalse(ArrayUtils.isSameLength(nullArrayInt, twoArrayFloat)); + assertFalse(ArrayUtils.isSameLength(nullArrayShort, twoArrayObject)); + assertFalse(ArrayUtils.isSameLength(nullArrayShort, twoArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(nullArrayShort, twoArrayLong)); + assertFalse(ArrayUtils.isSameLength(nullArrayShort, twoArrayInt)); + assertFalse(ArrayUtils.isSameLength(nullArrayShort, twoArrayShort)); + assertFalse(ArrayUtils.isSameLength(nullArrayShort, twoArrayChar)); + assertFalse(ArrayUtils.isSameLength(nullArrayShort, twoArrayByte)); + assertFalse(ArrayUtils.isSameLength(nullArrayShort, twoArrayDouble)); + assertFalse(ArrayUtils.isSameLength(nullArrayShort, twoArrayFloat)); + assertFalse(ArrayUtils.isSameLength(nullArrayChar, twoArrayObject)); + assertFalse(ArrayUtils.isSameLength(nullArrayChar, twoArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(nullArrayChar, twoArrayLong)); + assertFalse(ArrayUtils.isSameLength(nullArrayChar, twoArrayInt)); + assertFalse(ArrayUtils.isSameLength(nullArrayChar, twoArrayShort)); + assertFalse(ArrayUtils.isSameLength(nullArrayChar, twoArrayChar)); + assertFalse(ArrayUtils.isSameLength(nullArrayChar, twoArrayByte)); + assertFalse(ArrayUtils.isSameLength(nullArrayChar, twoArrayDouble)); + assertFalse(ArrayUtils.isSameLength(nullArrayChar, twoArrayFloat)); + assertFalse(ArrayUtils.isSameLength(nullArrayByte, twoArrayObject)); + assertFalse(ArrayUtils.isSameLength(nullArrayByte, twoArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(nullArrayByte, twoArrayLong)); + assertFalse(ArrayUtils.isSameLength(nullArrayByte, twoArrayInt)); + assertFalse(ArrayUtils.isSameLength(nullArrayByte, twoArrayShort)); + assertFalse(ArrayUtils.isSameLength(nullArrayByte, twoArrayChar)); + assertFalse(ArrayUtils.isSameLength(nullArrayByte, twoArrayByte)); + assertFalse(ArrayUtils.isSameLength(nullArrayByte, twoArrayDouble)); + assertFalse(ArrayUtils.isSameLength(nullArrayByte, twoArrayFloat)); + assertFalse(ArrayUtils.isSameLength(nullArrayDouble, twoArrayObject)); + assertFalse(ArrayUtils.isSameLength(nullArrayDouble, twoArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(nullArrayDouble, twoArrayLong)); + assertFalse(ArrayUtils.isSameLength(nullArrayDouble, twoArrayInt)); + assertFalse(ArrayUtils.isSameLength(nullArrayDouble, twoArrayShort)); + assertFalse(ArrayUtils.isSameLength(nullArrayDouble, twoArrayChar)); + assertFalse(ArrayUtils.isSameLength(nullArrayDouble, twoArrayByte)); + assertFalse(ArrayUtils.isSameLength(nullArrayDouble, twoArrayDouble)); + assertFalse(ArrayUtils.isSameLength(nullArrayDouble, twoArrayFloat)); + assertFalse(ArrayUtils.isSameLength(nullArrayFloat, twoArrayObject)); + assertFalse(ArrayUtils.isSameLength(nullArrayFloat, twoArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(nullArrayFloat, twoArrayLong)); + assertFalse(ArrayUtils.isSameLength(nullArrayFloat, twoArrayInt)); + assertFalse(ArrayUtils.isSameLength(nullArrayFloat, twoArrayShort)); + assertFalse(ArrayUtils.isSameLength(nullArrayFloat, twoArrayChar)); + assertFalse(ArrayUtils.isSameLength(nullArrayFloat, twoArrayByte)); + assertFalse(ArrayUtils.isSameLength(nullArrayFloat, twoArrayDouble)); + assertFalse(ArrayUtils.isSameLength(nullArrayFloat, twoArrayFloat)); + assertTrue(ArrayUtils.isSameLength(emptyArrayObject, nullArrayObject)); + assertTrue(ArrayUtils.isSameLength(emptyArrayObject, nullArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(emptyArrayObject, nullArrayLong)); + assertTrue(ArrayUtils.isSameLength(emptyArrayObject, nullArrayInt)); + assertTrue(ArrayUtils.isSameLength(emptyArrayObject, nullArrayShort)); + assertTrue(ArrayUtils.isSameLength(emptyArrayObject, nullArrayChar)); + assertTrue(ArrayUtils.isSameLength(emptyArrayObject, nullArrayByte)); + assertTrue(ArrayUtils.isSameLength(emptyArrayObject, nullArrayDouble)); + assertTrue(ArrayUtils.isSameLength(emptyArrayObject, nullArrayFloat)); + assertTrue(ArrayUtils.isSameLength(emptyArrayBoolean, nullArrayObject)); + assertTrue(ArrayUtils.isSameLength(emptyArrayBoolean, nullArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(emptyArrayBoolean, nullArrayLong)); + assertTrue(ArrayUtils.isSameLength(emptyArrayBoolean, nullArrayInt)); + assertTrue(ArrayUtils.isSameLength(emptyArrayBoolean, nullArrayShort)); + assertTrue(ArrayUtils.isSameLength(emptyArrayBoolean, nullArrayChar)); + assertTrue(ArrayUtils.isSameLength(emptyArrayBoolean, nullArrayByte)); + assertTrue(ArrayUtils.isSameLength(emptyArrayBoolean, nullArrayDouble)); + assertTrue(ArrayUtils.isSameLength(emptyArrayBoolean, nullArrayFloat)); + assertTrue(ArrayUtils.isSameLength(emptyArrayLong, nullArrayObject)); + assertTrue(ArrayUtils.isSameLength(emptyArrayLong, nullArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(emptyArrayLong, nullArrayLong)); + assertTrue(ArrayUtils.isSameLength(emptyArrayLong, nullArrayInt)); + assertTrue(ArrayUtils.isSameLength(emptyArrayLong, nullArrayShort)); + assertTrue(ArrayUtils.isSameLength(emptyArrayLong, nullArrayChar)); + assertTrue(ArrayUtils.isSameLength(emptyArrayLong, nullArrayByte)); + assertTrue(ArrayUtils.isSameLength(emptyArrayLong, nullArrayDouble)); + assertTrue(ArrayUtils.isSameLength(emptyArrayLong, nullArrayFloat)); + assertTrue(ArrayUtils.isSameLength(emptyArrayInt, nullArrayObject)); + assertTrue(ArrayUtils.isSameLength(emptyArrayInt, nullArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(emptyArrayInt, nullArrayLong)); + assertTrue(ArrayUtils.isSameLength(emptyArrayInt, nullArrayInt)); + assertTrue(ArrayUtils.isSameLength(emptyArrayInt, nullArrayShort)); + assertTrue(ArrayUtils.isSameLength(emptyArrayInt, nullArrayChar)); + assertTrue(ArrayUtils.isSameLength(emptyArrayInt, nullArrayByte)); + assertTrue(ArrayUtils.isSameLength(emptyArrayInt, nullArrayDouble)); + assertTrue(ArrayUtils.isSameLength(emptyArrayInt, nullArrayFloat)); + assertTrue(ArrayUtils.isSameLength(emptyArrayShort, nullArrayObject)); + assertTrue(ArrayUtils.isSameLength(emptyArrayShort, nullArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(emptyArrayShort, nullArrayLong)); + assertTrue(ArrayUtils.isSameLength(emptyArrayShort, nullArrayInt)); + assertTrue(ArrayUtils.isSameLength(emptyArrayShort, nullArrayShort)); + assertTrue(ArrayUtils.isSameLength(emptyArrayShort, nullArrayChar)); + assertTrue(ArrayUtils.isSameLength(emptyArrayShort, nullArrayByte)); + assertTrue(ArrayUtils.isSameLength(emptyArrayShort, nullArrayDouble)); + assertTrue(ArrayUtils.isSameLength(emptyArrayShort, nullArrayFloat)); + assertTrue(ArrayUtils.isSameLength(emptyArrayChar, nullArrayObject)); + assertTrue(ArrayUtils.isSameLength(emptyArrayChar, nullArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(emptyArrayChar, nullArrayLong)); + assertTrue(ArrayUtils.isSameLength(emptyArrayChar, nullArrayInt)); + assertTrue(ArrayUtils.isSameLength(emptyArrayChar, nullArrayShort)); + assertTrue(ArrayUtils.isSameLength(emptyArrayChar, nullArrayChar)); + assertTrue(ArrayUtils.isSameLength(emptyArrayChar, nullArrayByte)); + assertTrue(ArrayUtils.isSameLength(emptyArrayChar, nullArrayDouble)); + assertTrue(ArrayUtils.isSameLength(emptyArrayChar, nullArrayFloat)); + assertTrue(ArrayUtils.isSameLength(emptyArrayByte, nullArrayObject)); + assertTrue(ArrayUtils.isSameLength(emptyArrayByte, nullArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(emptyArrayByte, nullArrayLong)); + assertTrue(ArrayUtils.isSameLength(emptyArrayByte, nullArrayInt)); + assertTrue(ArrayUtils.isSameLength(emptyArrayByte, nullArrayShort)); + assertTrue(ArrayUtils.isSameLength(emptyArrayByte, nullArrayChar)); + assertTrue(ArrayUtils.isSameLength(emptyArrayByte, nullArrayByte)); + assertTrue(ArrayUtils.isSameLength(emptyArrayByte, nullArrayDouble)); + assertTrue(ArrayUtils.isSameLength(emptyArrayByte, nullArrayFloat)); + assertTrue(ArrayUtils.isSameLength(emptyArrayDouble, nullArrayObject)); + assertTrue(ArrayUtils.isSameLength(emptyArrayDouble, nullArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(emptyArrayDouble, nullArrayLong)); + assertTrue(ArrayUtils.isSameLength(emptyArrayDouble, nullArrayInt)); + assertTrue(ArrayUtils.isSameLength(emptyArrayDouble, nullArrayShort)); + assertTrue(ArrayUtils.isSameLength(emptyArrayDouble, nullArrayChar)); + assertTrue(ArrayUtils.isSameLength(emptyArrayDouble, nullArrayByte)); + assertTrue(ArrayUtils.isSameLength(emptyArrayDouble, nullArrayDouble)); + assertTrue(ArrayUtils.isSameLength(emptyArrayDouble, nullArrayFloat)); + assertTrue(ArrayUtils.isSameLength(emptyArrayFloat, nullArrayObject)); + assertTrue(ArrayUtils.isSameLength(emptyArrayFloat, nullArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(emptyArrayFloat, nullArrayLong)); + assertTrue(ArrayUtils.isSameLength(emptyArrayFloat, nullArrayInt)); + assertTrue(ArrayUtils.isSameLength(emptyArrayFloat, nullArrayShort)); + assertTrue(ArrayUtils.isSameLength(emptyArrayFloat, nullArrayChar)); + assertTrue(ArrayUtils.isSameLength(emptyArrayFloat, nullArrayByte)); + assertTrue(ArrayUtils.isSameLength(emptyArrayFloat, nullArrayDouble)); + assertTrue(ArrayUtils.isSameLength(emptyArrayFloat, nullArrayFloat)); + assertTrue(ArrayUtils.isSameLength(emptyArrayObject, emptyArrayObject)); + assertTrue(ArrayUtils.isSameLength(emptyArrayObject, emptyArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(emptyArrayObject, emptyArrayLong)); + assertTrue(ArrayUtils.isSameLength(emptyArrayObject, emptyArrayInt)); + assertTrue(ArrayUtils.isSameLength(emptyArrayObject, emptyArrayShort)); + assertTrue(ArrayUtils.isSameLength(emptyArrayObject, emptyArrayChar)); + assertTrue(ArrayUtils.isSameLength(emptyArrayObject, emptyArrayByte)); + assertTrue(ArrayUtils.isSameLength(emptyArrayObject, emptyArrayDouble)); + assertTrue(ArrayUtils.isSameLength(emptyArrayObject, emptyArrayFloat)); + assertTrue(ArrayUtils.isSameLength(emptyArrayBoolean, emptyArrayObject)); + assertTrue(ArrayUtils.isSameLength(emptyArrayBoolean, emptyArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(emptyArrayBoolean, emptyArrayLong)); + assertTrue(ArrayUtils.isSameLength(emptyArrayBoolean, emptyArrayInt)); + assertTrue(ArrayUtils.isSameLength(emptyArrayBoolean, emptyArrayShort)); + assertTrue(ArrayUtils.isSameLength(emptyArrayBoolean, emptyArrayChar)); + assertTrue(ArrayUtils.isSameLength(emptyArrayBoolean, emptyArrayByte)); + assertTrue(ArrayUtils.isSameLength(emptyArrayBoolean, emptyArrayDouble)); + assertTrue(ArrayUtils.isSameLength(emptyArrayBoolean, emptyArrayFloat)); + assertTrue(ArrayUtils.isSameLength(emptyArrayLong, emptyArrayObject)); + assertTrue(ArrayUtils.isSameLength(emptyArrayLong, emptyArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(emptyArrayLong, emptyArrayLong)); + assertTrue(ArrayUtils.isSameLength(emptyArrayLong, emptyArrayInt)); + assertTrue(ArrayUtils.isSameLength(emptyArrayLong, emptyArrayShort)); + assertTrue(ArrayUtils.isSameLength(emptyArrayLong, emptyArrayChar)); + assertTrue(ArrayUtils.isSameLength(emptyArrayLong, emptyArrayByte)); + assertTrue(ArrayUtils.isSameLength(emptyArrayLong, emptyArrayDouble)); + assertTrue(ArrayUtils.isSameLength(emptyArrayLong, emptyArrayFloat)); + assertTrue(ArrayUtils.isSameLength(emptyArrayInt, emptyArrayObject)); + assertTrue(ArrayUtils.isSameLength(emptyArrayInt, emptyArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(emptyArrayInt, emptyArrayLong)); + assertTrue(ArrayUtils.isSameLength(emptyArrayInt, emptyArrayInt)); + assertTrue(ArrayUtils.isSameLength(emptyArrayInt, emptyArrayShort)); + assertTrue(ArrayUtils.isSameLength(emptyArrayInt, emptyArrayChar)); + assertTrue(ArrayUtils.isSameLength(emptyArrayInt, emptyArrayByte)); + assertTrue(ArrayUtils.isSameLength(emptyArrayInt, emptyArrayDouble)); + assertTrue(ArrayUtils.isSameLength(emptyArrayInt, emptyArrayFloat)); + assertTrue(ArrayUtils.isSameLength(emptyArrayShort, emptyArrayObject)); + assertTrue(ArrayUtils.isSameLength(emptyArrayShort, emptyArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(emptyArrayShort, emptyArrayLong)); + assertTrue(ArrayUtils.isSameLength(emptyArrayShort, emptyArrayInt)); + assertTrue(ArrayUtils.isSameLength(emptyArrayShort, emptyArrayShort)); + assertTrue(ArrayUtils.isSameLength(emptyArrayShort, emptyArrayChar)); + assertTrue(ArrayUtils.isSameLength(emptyArrayShort, emptyArrayByte)); + assertTrue(ArrayUtils.isSameLength(emptyArrayShort, emptyArrayDouble)); + assertTrue(ArrayUtils.isSameLength(emptyArrayShort, emptyArrayFloat)); + assertTrue(ArrayUtils.isSameLength(emptyArrayChar, emptyArrayObject)); + assertTrue(ArrayUtils.isSameLength(emptyArrayChar, emptyArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(emptyArrayChar, emptyArrayLong)); + assertTrue(ArrayUtils.isSameLength(emptyArrayChar, emptyArrayInt)); + assertTrue(ArrayUtils.isSameLength(emptyArrayChar, emptyArrayShort)); + assertTrue(ArrayUtils.isSameLength(emptyArrayChar, emptyArrayChar)); + assertTrue(ArrayUtils.isSameLength(emptyArrayChar, emptyArrayByte)); + assertTrue(ArrayUtils.isSameLength(emptyArrayChar, emptyArrayDouble)); + assertTrue(ArrayUtils.isSameLength(emptyArrayChar, emptyArrayFloat)); + assertTrue(ArrayUtils.isSameLength(emptyArrayByte, emptyArrayObject)); + assertTrue(ArrayUtils.isSameLength(emptyArrayByte, emptyArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(emptyArrayByte, emptyArrayLong)); + assertTrue(ArrayUtils.isSameLength(emptyArrayByte, emptyArrayInt)); + assertTrue(ArrayUtils.isSameLength(emptyArrayByte, emptyArrayShort)); + assertTrue(ArrayUtils.isSameLength(emptyArrayByte, emptyArrayChar)); + assertTrue(ArrayUtils.isSameLength(emptyArrayByte, emptyArrayByte)); + assertTrue(ArrayUtils.isSameLength(emptyArrayByte, emptyArrayDouble)); + assertTrue(ArrayUtils.isSameLength(emptyArrayByte, emptyArrayFloat)); + assertTrue(ArrayUtils.isSameLength(emptyArrayDouble, emptyArrayObject)); + assertTrue(ArrayUtils.isSameLength(emptyArrayDouble, emptyArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(emptyArrayDouble, emptyArrayLong)); + assertTrue(ArrayUtils.isSameLength(emptyArrayDouble, emptyArrayInt)); + assertTrue(ArrayUtils.isSameLength(emptyArrayDouble, emptyArrayShort)); + assertTrue(ArrayUtils.isSameLength(emptyArrayDouble, emptyArrayChar)); + assertTrue(ArrayUtils.isSameLength(emptyArrayDouble, emptyArrayByte)); + assertTrue(ArrayUtils.isSameLength(emptyArrayDouble, emptyArrayDouble)); + assertTrue(ArrayUtils.isSameLength(emptyArrayDouble, emptyArrayFloat)); + assertTrue(ArrayUtils.isSameLength(emptyArrayFloat, emptyArrayObject)); + assertTrue(ArrayUtils.isSameLength(emptyArrayFloat, emptyArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(emptyArrayFloat, emptyArrayLong)); + assertTrue(ArrayUtils.isSameLength(emptyArrayFloat, emptyArrayInt)); + assertTrue(ArrayUtils.isSameLength(emptyArrayFloat, emptyArrayShort)); + assertTrue(ArrayUtils.isSameLength(emptyArrayFloat, emptyArrayChar)); + assertTrue(ArrayUtils.isSameLength(emptyArrayFloat, emptyArrayByte)); + assertTrue(ArrayUtils.isSameLength(emptyArrayFloat, emptyArrayDouble)); + assertTrue(ArrayUtils.isSameLength(emptyArrayFloat, emptyArrayFloat)); + assertFalse(ArrayUtils.isSameLength(emptyArrayObject, oneArrayObject)); + assertFalse(ArrayUtils.isSameLength(emptyArrayObject, oneArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(emptyArrayObject, oneArrayLong)); + assertFalse(ArrayUtils.isSameLength(emptyArrayObject, oneArrayInt)); + assertFalse(ArrayUtils.isSameLength(emptyArrayObject, oneArrayShort)); + assertFalse(ArrayUtils.isSameLength(emptyArrayObject, oneArrayChar)); + assertFalse(ArrayUtils.isSameLength(emptyArrayObject, oneArrayByte)); + assertFalse(ArrayUtils.isSameLength(emptyArrayObject, oneArrayDouble)); + assertFalse(ArrayUtils.isSameLength(emptyArrayObject, oneArrayFloat)); + assertFalse(ArrayUtils.isSameLength(emptyArrayBoolean, oneArrayObject)); + assertFalse(ArrayUtils.isSameLength(emptyArrayBoolean, oneArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(emptyArrayBoolean, oneArrayLong)); + assertFalse(ArrayUtils.isSameLength(emptyArrayBoolean, oneArrayInt)); + assertFalse(ArrayUtils.isSameLength(emptyArrayBoolean, oneArrayShort)); + assertFalse(ArrayUtils.isSameLength(emptyArrayBoolean, oneArrayChar)); + assertFalse(ArrayUtils.isSameLength(emptyArrayBoolean, oneArrayByte)); + assertFalse(ArrayUtils.isSameLength(emptyArrayBoolean, oneArrayDouble)); + assertFalse(ArrayUtils.isSameLength(emptyArrayBoolean, oneArrayFloat)); + assertFalse(ArrayUtils.isSameLength(emptyArrayLong, oneArrayObject)); + assertFalse(ArrayUtils.isSameLength(emptyArrayLong, oneArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(emptyArrayLong, oneArrayLong)); + assertFalse(ArrayUtils.isSameLength(emptyArrayLong, oneArrayInt)); + assertFalse(ArrayUtils.isSameLength(emptyArrayLong, oneArrayShort)); + assertFalse(ArrayUtils.isSameLength(emptyArrayLong, oneArrayChar)); + assertFalse(ArrayUtils.isSameLength(emptyArrayLong, oneArrayByte)); + assertFalse(ArrayUtils.isSameLength(emptyArrayLong, oneArrayDouble)); + assertFalse(ArrayUtils.isSameLength(emptyArrayLong, oneArrayFloat)); + assertFalse(ArrayUtils.isSameLength(emptyArrayInt, oneArrayObject)); + assertFalse(ArrayUtils.isSameLength(emptyArrayInt, oneArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(emptyArrayInt, oneArrayLong)); + assertFalse(ArrayUtils.isSameLength(emptyArrayInt, oneArrayInt)); + assertFalse(ArrayUtils.isSameLength(emptyArrayInt, oneArrayShort)); + assertFalse(ArrayUtils.isSameLength(emptyArrayInt, oneArrayChar)); + assertFalse(ArrayUtils.isSameLength(emptyArrayInt, oneArrayByte)); + assertFalse(ArrayUtils.isSameLength(emptyArrayInt, oneArrayDouble)); + assertFalse(ArrayUtils.isSameLength(emptyArrayInt, oneArrayFloat)); + assertFalse(ArrayUtils.isSameLength(emptyArrayShort, oneArrayObject)); + assertFalse(ArrayUtils.isSameLength(emptyArrayShort, oneArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(emptyArrayShort, oneArrayLong)); + assertFalse(ArrayUtils.isSameLength(emptyArrayShort, oneArrayInt)); + assertFalse(ArrayUtils.isSameLength(emptyArrayShort, oneArrayShort)); + assertFalse(ArrayUtils.isSameLength(emptyArrayShort, oneArrayChar)); + assertFalse(ArrayUtils.isSameLength(emptyArrayShort, oneArrayByte)); + assertFalse(ArrayUtils.isSameLength(emptyArrayShort, oneArrayDouble)); + assertFalse(ArrayUtils.isSameLength(emptyArrayShort, oneArrayFloat)); + assertFalse(ArrayUtils.isSameLength(emptyArrayChar, oneArrayObject)); + assertFalse(ArrayUtils.isSameLength(emptyArrayChar, oneArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(emptyArrayChar, oneArrayLong)); + assertFalse(ArrayUtils.isSameLength(emptyArrayChar, oneArrayInt)); + assertFalse(ArrayUtils.isSameLength(emptyArrayChar, oneArrayShort)); + assertFalse(ArrayUtils.isSameLength(emptyArrayChar, oneArrayChar)); + assertFalse(ArrayUtils.isSameLength(emptyArrayChar, oneArrayByte)); + assertFalse(ArrayUtils.isSameLength(emptyArrayChar, oneArrayDouble)); + assertFalse(ArrayUtils.isSameLength(emptyArrayChar, oneArrayFloat)); + assertFalse(ArrayUtils.isSameLength(emptyArrayByte, oneArrayObject)); + assertFalse(ArrayUtils.isSameLength(emptyArrayByte, oneArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(emptyArrayByte, oneArrayLong)); + assertFalse(ArrayUtils.isSameLength(emptyArrayByte, oneArrayInt)); + assertFalse(ArrayUtils.isSameLength(emptyArrayByte, oneArrayShort)); + assertFalse(ArrayUtils.isSameLength(emptyArrayByte, oneArrayChar)); + assertFalse(ArrayUtils.isSameLength(emptyArrayByte, oneArrayByte)); + assertFalse(ArrayUtils.isSameLength(emptyArrayByte, oneArrayDouble)); + assertFalse(ArrayUtils.isSameLength(emptyArrayByte, oneArrayFloat)); + assertFalse(ArrayUtils.isSameLength(emptyArrayDouble, oneArrayObject)); + assertFalse(ArrayUtils.isSameLength(emptyArrayDouble, oneArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(emptyArrayDouble, oneArrayLong)); + assertFalse(ArrayUtils.isSameLength(emptyArrayDouble, oneArrayInt)); + assertFalse(ArrayUtils.isSameLength(emptyArrayDouble, oneArrayShort)); + assertFalse(ArrayUtils.isSameLength(emptyArrayDouble, oneArrayChar)); + assertFalse(ArrayUtils.isSameLength(emptyArrayDouble, oneArrayByte)); + assertFalse(ArrayUtils.isSameLength(emptyArrayDouble, oneArrayDouble)); + assertFalse(ArrayUtils.isSameLength(emptyArrayDouble, oneArrayFloat)); + assertFalse(ArrayUtils.isSameLength(emptyArrayFloat, oneArrayObject)); + assertFalse(ArrayUtils.isSameLength(emptyArrayFloat, oneArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(emptyArrayFloat, oneArrayLong)); + assertFalse(ArrayUtils.isSameLength(emptyArrayFloat, oneArrayInt)); + assertFalse(ArrayUtils.isSameLength(emptyArrayFloat, oneArrayShort)); + assertFalse(ArrayUtils.isSameLength(emptyArrayFloat, oneArrayChar)); + assertFalse(ArrayUtils.isSameLength(emptyArrayFloat, oneArrayByte)); + assertFalse(ArrayUtils.isSameLength(emptyArrayFloat, oneArrayDouble)); + assertFalse(ArrayUtils.isSameLength(emptyArrayFloat, oneArrayFloat)); + assertFalse(ArrayUtils.isSameLength(emptyArrayObject, twoArrayObject)); + assertFalse(ArrayUtils.isSameLength(emptyArrayObject, twoArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(emptyArrayObject, twoArrayLong)); + assertFalse(ArrayUtils.isSameLength(emptyArrayObject, twoArrayInt)); + assertFalse(ArrayUtils.isSameLength(emptyArrayObject, twoArrayShort)); + assertFalse(ArrayUtils.isSameLength(emptyArrayObject, twoArrayChar)); + assertFalse(ArrayUtils.isSameLength(emptyArrayObject, twoArrayByte)); + assertFalse(ArrayUtils.isSameLength(emptyArrayObject, twoArrayDouble)); + assertFalse(ArrayUtils.isSameLength(emptyArrayObject, twoArrayFloat)); + assertFalse(ArrayUtils.isSameLength(emptyArrayBoolean, twoArrayObject)); + assertFalse(ArrayUtils.isSameLength(emptyArrayBoolean, twoArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(emptyArrayBoolean, twoArrayLong)); + assertFalse(ArrayUtils.isSameLength(emptyArrayBoolean, twoArrayInt)); + assertFalse(ArrayUtils.isSameLength(emptyArrayBoolean, twoArrayShort)); + assertFalse(ArrayUtils.isSameLength(emptyArrayBoolean, twoArrayChar)); + assertFalse(ArrayUtils.isSameLength(emptyArrayBoolean, twoArrayByte)); + assertFalse(ArrayUtils.isSameLength(emptyArrayBoolean, twoArrayDouble)); + assertFalse(ArrayUtils.isSameLength(emptyArrayBoolean, twoArrayFloat)); + assertFalse(ArrayUtils.isSameLength(emptyArrayLong, twoArrayObject)); + assertFalse(ArrayUtils.isSameLength(emptyArrayLong, twoArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(emptyArrayLong, twoArrayLong)); + assertFalse(ArrayUtils.isSameLength(emptyArrayLong, twoArrayInt)); + assertFalse(ArrayUtils.isSameLength(emptyArrayLong, twoArrayShort)); + assertFalse(ArrayUtils.isSameLength(emptyArrayLong, twoArrayChar)); + assertFalse(ArrayUtils.isSameLength(emptyArrayLong, twoArrayByte)); + assertFalse(ArrayUtils.isSameLength(emptyArrayLong, twoArrayDouble)); + assertFalse(ArrayUtils.isSameLength(emptyArrayLong, twoArrayFloat)); + assertFalse(ArrayUtils.isSameLength(emptyArrayInt, twoArrayObject)); + assertFalse(ArrayUtils.isSameLength(emptyArrayInt, twoArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(emptyArrayInt, twoArrayLong)); + assertFalse(ArrayUtils.isSameLength(emptyArrayInt, twoArrayInt)); + assertFalse(ArrayUtils.isSameLength(emptyArrayInt, twoArrayShort)); + assertFalse(ArrayUtils.isSameLength(emptyArrayInt, twoArrayChar)); + assertFalse(ArrayUtils.isSameLength(emptyArrayInt, twoArrayByte)); + assertFalse(ArrayUtils.isSameLength(emptyArrayInt, twoArrayDouble)); + assertFalse(ArrayUtils.isSameLength(emptyArrayInt, twoArrayFloat)); + assertFalse(ArrayUtils.isSameLength(emptyArrayShort, twoArrayObject)); + assertFalse(ArrayUtils.isSameLength(emptyArrayShort, twoArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(emptyArrayShort, twoArrayLong)); + assertFalse(ArrayUtils.isSameLength(emptyArrayShort, twoArrayInt)); + assertFalse(ArrayUtils.isSameLength(emptyArrayShort, twoArrayShort)); + assertFalse(ArrayUtils.isSameLength(emptyArrayShort, twoArrayChar)); + assertFalse(ArrayUtils.isSameLength(emptyArrayShort, twoArrayByte)); + assertFalse(ArrayUtils.isSameLength(emptyArrayShort, twoArrayDouble)); + assertFalse(ArrayUtils.isSameLength(emptyArrayShort, twoArrayFloat)); + assertFalse(ArrayUtils.isSameLength(emptyArrayChar, twoArrayObject)); + assertFalse(ArrayUtils.isSameLength(emptyArrayChar, twoArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(emptyArrayChar, twoArrayLong)); + assertFalse(ArrayUtils.isSameLength(emptyArrayChar, twoArrayInt)); + assertFalse(ArrayUtils.isSameLength(emptyArrayChar, twoArrayShort)); + assertFalse(ArrayUtils.isSameLength(emptyArrayChar, twoArrayChar)); + assertFalse(ArrayUtils.isSameLength(emptyArrayChar, twoArrayByte)); + assertFalse(ArrayUtils.isSameLength(emptyArrayChar, twoArrayDouble)); + assertFalse(ArrayUtils.isSameLength(emptyArrayChar, twoArrayFloat)); + assertFalse(ArrayUtils.isSameLength(emptyArrayByte, twoArrayObject)); + assertFalse(ArrayUtils.isSameLength(emptyArrayByte, twoArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(emptyArrayByte, twoArrayLong)); + assertFalse(ArrayUtils.isSameLength(emptyArrayByte, twoArrayInt)); + assertFalse(ArrayUtils.isSameLength(emptyArrayByte, twoArrayShort)); + assertFalse(ArrayUtils.isSameLength(emptyArrayByte, twoArrayChar)); + assertFalse(ArrayUtils.isSameLength(emptyArrayByte, twoArrayByte)); + assertFalse(ArrayUtils.isSameLength(emptyArrayByte, twoArrayDouble)); + assertFalse(ArrayUtils.isSameLength(emptyArrayByte, twoArrayFloat)); + assertFalse(ArrayUtils.isSameLength(emptyArrayDouble, twoArrayObject)); + assertFalse(ArrayUtils.isSameLength(emptyArrayDouble, twoArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(emptyArrayDouble, twoArrayLong)); + assertFalse(ArrayUtils.isSameLength(emptyArrayDouble, twoArrayInt)); + assertFalse(ArrayUtils.isSameLength(emptyArrayDouble, twoArrayShort)); + assertFalse(ArrayUtils.isSameLength(emptyArrayDouble, twoArrayChar)); + assertFalse(ArrayUtils.isSameLength(emptyArrayDouble, twoArrayByte)); + assertFalse(ArrayUtils.isSameLength(emptyArrayDouble, twoArrayDouble)); + assertFalse(ArrayUtils.isSameLength(emptyArrayDouble, twoArrayFloat)); + assertFalse(ArrayUtils.isSameLength(emptyArrayFloat, twoArrayObject)); + assertFalse(ArrayUtils.isSameLength(emptyArrayFloat, twoArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(emptyArrayFloat, twoArrayLong)); + assertFalse(ArrayUtils.isSameLength(emptyArrayFloat, twoArrayInt)); + assertFalse(ArrayUtils.isSameLength(emptyArrayFloat, twoArrayShort)); + assertFalse(ArrayUtils.isSameLength(emptyArrayFloat, twoArrayChar)); + assertFalse(ArrayUtils.isSameLength(emptyArrayFloat, twoArrayByte)); + assertFalse(ArrayUtils.isSameLength(emptyArrayFloat, twoArrayDouble)); + assertFalse(ArrayUtils.isSameLength(emptyArrayFloat, twoArrayFloat)); + assertFalse(ArrayUtils.isSameLength(oneArrayObject, nullArrayObject)); + assertFalse(ArrayUtils.isSameLength(oneArrayObject, nullArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(oneArrayObject, nullArrayLong)); + assertFalse(ArrayUtils.isSameLength(oneArrayObject, nullArrayInt)); + assertFalse(ArrayUtils.isSameLength(oneArrayObject, nullArrayShort)); + assertFalse(ArrayUtils.isSameLength(oneArrayObject, nullArrayChar)); + assertFalse(ArrayUtils.isSameLength(oneArrayObject, nullArrayByte)); + assertFalse(ArrayUtils.isSameLength(oneArrayObject, nullArrayDouble)); + assertFalse(ArrayUtils.isSameLength(oneArrayObject, nullArrayFloat)); + assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, nullArrayObject)); + assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, nullArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, nullArrayLong)); + assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, nullArrayInt)); + assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, nullArrayShort)); + assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, nullArrayChar)); + assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, nullArrayByte)); + assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, nullArrayDouble)); + assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, nullArrayFloat)); + assertFalse(ArrayUtils.isSameLength(oneArrayLong, nullArrayObject)); + assertFalse(ArrayUtils.isSameLength(oneArrayLong, nullArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(oneArrayLong, nullArrayLong)); + assertFalse(ArrayUtils.isSameLength(oneArrayLong, nullArrayInt)); + assertFalse(ArrayUtils.isSameLength(oneArrayLong, nullArrayShort)); + assertFalse(ArrayUtils.isSameLength(oneArrayLong, nullArrayChar)); + assertFalse(ArrayUtils.isSameLength(oneArrayLong, nullArrayByte)); + assertFalse(ArrayUtils.isSameLength(oneArrayLong, nullArrayDouble)); + assertFalse(ArrayUtils.isSameLength(oneArrayLong, nullArrayFloat)); + assertFalse(ArrayUtils.isSameLength(oneArrayInt, nullArrayObject)); + assertFalse(ArrayUtils.isSameLength(oneArrayInt, nullArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(oneArrayInt, nullArrayLong)); + assertFalse(ArrayUtils.isSameLength(oneArrayInt, nullArrayInt)); + assertFalse(ArrayUtils.isSameLength(oneArrayInt, nullArrayShort)); + assertFalse(ArrayUtils.isSameLength(oneArrayInt, nullArrayChar)); + assertFalse(ArrayUtils.isSameLength(oneArrayInt, nullArrayByte)); + assertFalse(ArrayUtils.isSameLength(oneArrayInt, nullArrayDouble)); + assertFalse(ArrayUtils.isSameLength(oneArrayInt, nullArrayFloat)); + assertFalse(ArrayUtils.isSameLength(oneArrayShort, nullArrayObject)); + assertFalse(ArrayUtils.isSameLength(oneArrayShort, nullArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(oneArrayShort, nullArrayLong)); + assertFalse(ArrayUtils.isSameLength(oneArrayShort, nullArrayInt)); + assertFalse(ArrayUtils.isSameLength(oneArrayShort, nullArrayShort)); + assertFalse(ArrayUtils.isSameLength(oneArrayShort, nullArrayChar)); + assertFalse(ArrayUtils.isSameLength(oneArrayShort, nullArrayByte)); + assertFalse(ArrayUtils.isSameLength(oneArrayShort, nullArrayDouble)); + assertFalse(ArrayUtils.isSameLength(oneArrayShort, nullArrayFloat)); + assertFalse(ArrayUtils.isSameLength(oneArrayChar, nullArrayObject)); + assertFalse(ArrayUtils.isSameLength(oneArrayChar, nullArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(oneArrayChar, nullArrayLong)); + assertFalse(ArrayUtils.isSameLength(oneArrayChar, nullArrayInt)); + assertFalse(ArrayUtils.isSameLength(oneArrayChar, nullArrayShort)); + assertFalse(ArrayUtils.isSameLength(oneArrayChar, nullArrayChar)); + assertFalse(ArrayUtils.isSameLength(oneArrayChar, nullArrayByte)); + assertFalse(ArrayUtils.isSameLength(oneArrayChar, nullArrayDouble)); + assertFalse(ArrayUtils.isSameLength(oneArrayChar, nullArrayFloat)); + assertFalse(ArrayUtils.isSameLength(oneArrayByte, nullArrayObject)); + assertFalse(ArrayUtils.isSameLength(oneArrayByte, nullArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(oneArrayByte, nullArrayLong)); + assertFalse(ArrayUtils.isSameLength(oneArrayByte, nullArrayInt)); + assertFalse(ArrayUtils.isSameLength(oneArrayByte, nullArrayShort)); + assertFalse(ArrayUtils.isSameLength(oneArrayByte, nullArrayChar)); + assertFalse(ArrayUtils.isSameLength(oneArrayByte, nullArrayByte)); + assertFalse(ArrayUtils.isSameLength(oneArrayByte, nullArrayDouble)); + assertFalse(ArrayUtils.isSameLength(oneArrayByte, nullArrayFloat)); + assertFalse(ArrayUtils.isSameLength(oneArrayDouble, nullArrayObject)); + assertFalse(ArrayUtils.isSameLength(oneArrayDouble, nullArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(oneArrayDouble, nullArrayLong)); + assertFalse(ArrayUtils.isSameLength(oneArrayDouble, nullArrayInt)); + assertFalse(ArrayUtils.isSameLength(oneArrayDouble, nullArrayShort)); + assertFalse(ArrayUtils.isSameLength(oneArrayDouble, nullArrayChar)); + assertFalse(ArrayUtils.isSameLength(oneArrayDouble, nullArrayByte)); + assertFalse(ArrayUtils.isSameLength(oneArrayDouble, nullArrayDouble)); + assertFalse(ArrayUtils.isSameLength(oneArrayDouble, nullArrayFloat)); + assertFalse(ArrayUtils.isSameLength(oneArrayFloat, nullArrayObject)); + assertFalse(ArrayUtils.isSameLength(oneArrayFloat, nullArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(oneArrayFloat, nullArrayLong)); + assertFalse(ArrayUtils.isSameLength(oneArrayFloat, nullArrayInt)); + assertFalse(ArrayUtils.isSameLength(oneArrayFloat, nullArrayShort)); + assertFalse(ArrayUtils.isSameLength(oneArrayFloat, nullArrayChar)); + assertFalse(ArrayUtils.isSameLength(oneArrayFloat, nullArrayByte)); + assertFalse(ArrayUtils.isSameLength(oneArrayFloat, nullArrayDouble)); + assertFalse(ArrayUtils.isSameLength(oneArrayFloat, nullArrayFloat)); + assertFalse(ArrayUtils.isSameLength(oneArrayObject, emptyArrayObject)); + assertFalse(ArrayUtils.isSameLength(oneArrayObject, emptyArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(oneArrayObject, emptyArrayLong)); + assertFalse(ArrayUtils.isSameLength(oneArrayObject, emptyArrayInt)); + assertFalse(ArrayUtils.isSameLength(oneArrayObject, emptyArrayShort)); + assertFalse(ArrayUtils.isSameLength(oneArrayObject, emptyArrayChar)); + assertFalse(ArrayUtils.isSameLength(oneArrayObject, emptyArrayByte)); + assertFalse(ArrayUtils.isSameLength(oneArrayObject, emptyArrayDouble)); + assertFalse(ArrayUtils.isSameLength(oneArrayObject, emptyArrayFloat)); + assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, emptyArrayObject)); + assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, emptyArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, emptyArrayLong)); + assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, emptyArrayInt)); + assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, emptyArrayShort)); + assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, emptyArrayChar)); + assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, emptyArrayByte)); + assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, emptyArrayDouble)); + assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, emptyArrayFloat)); + assertFalse(ArrayUtils.isSameLength(oneArrayLong, emptyArrayObject)); + assertFalse(ArrayUtils.isSameLength(oneArrayLong, emptyArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(oneArrayLong, emptyArrayLong)); + assertFalse(ArrayUtils.isSameLength(oneArrayLong, emptyArrayInt)); + assertFalse(ArrayUtils.isSameLength(oneArrayLong, emptyArrayShort)); + assertFalse(ArrayUtils.isSameLength(oneArrayLong, emptyArrayChar)); + assertFalse(ArrayUtils.isSameLength(oneArrayLong, emptyArrayByte)); + assertFalse(ArrayUtils.isSameLength(oneArrayLong, emptyArrayDouble)); + assertFalse(ArrayUtils.isSameLength(oneArrayLong, emptyArrayFloat)); + assertFalse(ArrayUtils.isSameLength(oneArrayInt, emptyArrayObject)); + assertFalse(ArrayUtils.isSameLength(oneArrayInt, emptyArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(oneArrayInt, emptyArrayLong)); + assertFalse(ArrayUtils.isSameLength(oneArrayInt, emptyArrayInt)); + assertFalse(ArrayUtils.isSameLength(oneArrayInt, emptyArrayShort)); + assertFalse(ArrayUtils.isSameLength(oneArrayInt, emptyArrayChar)); + assertFalse(ArrayUtils.isSameLength(oneArrayInt, emptyArrayByte)); + assertFalse(ArrayUtils.isSameLength(oneArrayInt, emptyArrayDouble)); + assertFalse(ArrayUtils.isSameLength(oneArrayInt, emptyArrayFloat)); + assertFalse(ArrayUtils.isSameLength(oneArrayShort, emptyArrayObject)); + assertFalse(ArrayUtils.isSameLength(oneArrayShort, emptyArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(oneArrayShort, emptyArrayLong)); + assertFalse(ArrayUtils.isSameLength(oneArrayShort, emptyArrayInt)); + assertFalse(ArrayUtils.isSameLength(oneArrayShort, emptyArrayShort)); + assertFalse(ArrayUtils.isSameLength(oneArrayShort, emptyArrayChar)); + assertFalse(ArrayUtils.isSameLength(oneArrayShort, emptyArrayByte)); + assertFalse(ArrayUtils.isSameLength(oneArrayShort, emptyArrayDouble)); + assertFalse(ArrayUtils.isSameLength(oneArrayShort, emptyArrayFloat)); + assertFalse(ArrayUtils.isSameLength(oneArrayChar, emptyArrayObject)); + assertFalse(ArrayUtils.isSameLength(oneArrayChar, emptyArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(oneArrayChar, emptyArrayLong)); + assertFalse(ArrayUtils.isSameLength(oneArrayChar, emptyArrayInt)); + assertFalse(ArrayUtils.isSameLength(oneArrayChar, emptyArrayShort)); + assertFalse(ArrayUtils.isSameLength(oneArrayChar, emptyArrayChar)); + assertFalse(ArrayUtils.isSameLength(oneArrayChar, emptyArrayByte)); + assertFalse(ArrayUtils.isSameLength(oneArrayChar, emptyArrayDouble)); + assertFalse(ArrayUtils.isSameLength(oneArrayChar, emptyArrayFloat)); + assertFalse(ArrayUtils.isSameLength(oneArrayByte, emptyArrayObject)); + assertFalse(ArrayUtils.isSameLength(oneArrayByte, emptyArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(oneArrayByte, emptyArrayLong)); + assertFalse(ArrayUtils.isSameLength(oneArrayByte, emptyArrayInt)); + assertFalse(ArrayUtils.isSameLength(oneArrayByte, emptyArrayShort)); + assertFalse(ArrayUtils.isSameLength(oneArrayByte, emptyArrayChar)); + assertFalse(ArrayUtils.isSameLength(oneArrayByte, emptyArrayByte)); + assertFalse(ArrayUtils.isSameLength(oneArrayByte, emptyArrayDouble)); + assertFalse(ArrayUtils.isSameLength(oneArrayByte, emptyArrayFloat)); + assertFalse(ArrayUtils.isSameLength(oneArrayDouble, emptyArrayObject)); + assertFalse(ArrayUtils.isSameLength(oneArrayDouble, emptyArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(oneArrayDouble, emptyArrayLong)); + assertFalse(ArrayUtils.isSameLength(oneArrayDouble, emptyArrayInt)); + assertFalse(ArrayUtils.isSameLength(oneArrayDouble, emptyArrayShort)); + assertFalse(ArrayUtils.isSameLength(oneArrayDouble, emptyArrayChar)); + assertFalse(ArrayUtils.isSameLength(oneArrayDouble, emptyArrayByte)); + assertFalse(ArrayUtils.isSameLength(oneArrayDouble, emptyArrayDouble)); + assertFalse(ArrayUtils.isSameLength(oneArrayDouble, emptyArrayFloat)); + assertFalse(ArrayUtils.isSameLength(oneArrayFloat, emptyArrayObject)); + assertFalse(ArrayUtils.isSameLength(oneArrayFloat, emptyArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(oneArrayFloat, emptyArrayLong)); + assertFalse(ArrayUtils.isSameLength(oneArrayFloat, emptyArrayInt)); + assertFalse(ArrayUtils.isSameLength(oneArrayFloat, emptyArrayShort)); + assertFalse(ArrayUtils.isSameLength(oneArrayFloat, emptyArrayChar)); + assertFalse(ArrayUtils.isSameLength(oneArrayFloat, emptyArrayByte)); + assertFalse(ArrayUtils.isSameLength(oneArrayFloat, emptyArrayDouble)); + assertFalse(ArrayUtils.isSameLength(oneArrayFloat, emptyArrayFloat)); + assertTrue(ArrayUtils.isSameLength(oneArrayObject, oneArrayObject)); + assertTrue(ArrayUtils.isSameLength(oneArrayObject, oneArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(oneArrayObject, oneArrayLong)); + assertTrue(ArrayUtils.isSameLength(oneArrayObject, oneArrayInt)); + assertTrue(ArrayUtils.isSameLength(oneArrayObject, oneArrayShort)); + assertTrue(ArrayUtils.isSameLength(oneArrayObject, oneArrayChar)); + assertTrue(ArrayUtils.isSameLength(oneArrayObject, oneArrayByte)); + assertTrue(ArrayUtils.isSameLength(oneArrayObject, oneArrayDouble)); + assertTrue(ArrayUtils.isSameLength(oneArrayObject, oneArrayFloat)); + assertTrue(ArrayUtils.isSameLength(oneArrayBoolean, oneArrayObject)); + assertTrue(ArrayUtils.isSameLength(oneArrayBoolean, oneArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(oneArrayBoolean, oneArrayLong)); + assertTrue(ArrayUtils.isSameLength(oneArrayBoolean, oneArrayInt)); + assertTrue(ArrayUtils.isSameLength(oneArrayBoolean, oneArrayShort)); + assertTrue(ArrayUtils.isSameLength(oneArrayBoolean, oneArrayChar)); + assertTrue(ArrayUtils.isSameLength(oneArrayBoolean, oneArrayByte)); + assertTrue(ArrayUtils.isSameLength(oneArrayBoolean, oneArrayDouble)); + assertTrue(ArrayUtils.isSameLength(oneArrayBoolean, oneArrayFloat)); + assertTrue(ArrayUtils.isSameLength(oneArrayLong, oneArrayObject)); + assertTrue(ArrayUtils.isSameLength(oneArrayLong, oneArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(oneArrayLong, oneArrayLong)); + assertTrue(ArrayUtils.isSameLength(oneArrayLong, oneArrayInt)); + assertTrue(ArrayUtils.isSameLength(oneArrayLong, oneArrayShort)); + assertTrue(ArrayUtils.isSameLength(oneArrayLong, oneArrayChar)); + assertTrue(ArrayUtils.isSameLength(oneArrayLong, oneArrayByte)); + assertTrue(ArrayUtils.isSameLength(oneArrayLong, oneArrayDouble)); + assertTrue(ArrayUtils.isSameLength(oneArrayLong, oneArrayFloat)); + assertTrue(ArrayUtils.isSameLength(oneArrayInt, oneArrayObject)); + assertTrue(ArrayUtils.isSameLength(oneArrayInt, oneArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(oneArrayInt, oneArrayLong)); + assertTrue(ArrayUtils.isSameLength(oneArrayInt, oneArrayInt)); + assertTrue(ArrayUtils.isSameLength(oneArrayInt, oneArrayShort)); + assertTrue(ArrayUtils.isSameLength(oneArrayInt, oneArrayChar)); + assertTrue(ArrayUtils.isSameLength(oneArrayInt, oneArrayByte)); + assertTrue(ArrayUtils.isSameLength(oneArrayInt, oneArrayDouble)); + assertTrue(ArrayUtils.isSameLength(oneArrayInt, oneArrayFloat)); + assertTrue(ArrayUtils.isSameLength(oneArrayShort, oneArrayObject)); + assertTrue(ArrayUtils.isSameLength(oneArrayShort, oneArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(oneArrayShort, oneArrayLong)); + assertTrue(ArrayUtils.isSameLength(oneArrayShort, oneArrayInt)); + assertTrue(ArrayUtils.isSameLength(oneArrayShort, oneArrayShort)); + assertTrue(ArrayUtils.isSameLength(oneArrayShort, oneArrayChar)); + assertTrue(ArrayUtils.isSameLength(oneArrayShort, oneArrayByte)); + assertTrue(ArrayUtils.isSameLength(oneArrayShort, oneArrayDouble)); + assertTrue(ArrayUtils.isSameLength(oneArrayShort, oneArrayFloat)); + assertTrue(ArrayUtils.isSameLength(oneArrayChar, oneArrayObject)); + assertTrue(ArrayUtils.isSameLength(oneArrayChar, oneArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(oneArrayChar, oneArrayLong)); + assertTrue(ArrayUtils.isSameLength(oneArrayChar, oneArrayInt)); + assertTrue(ArrayUtils.isSameLength(oneArrayChar, oneArrayShort)); + assertTrue(ArrayUtils.isSameLength(oneArrayChar, oneArrayChar)); + assertTrue(ArrayUtils.isSameLength(oneArrayChar, oneArrayByte)); + assertTrue(ArrayUtils.isSameLength(oneArrayChar, oneArrayDouble)); + assertTrue(ArrayUtils.isSameLength(oneArrayChar, oneArrayFloat)); + assertTrue(ArrayUtils.isSameLength(oneArrayByte, oneArrayObject)); + assertTrue(ArrayUtils.isSameLength(oneArrayByte, oneArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(oneArrayByte, oneArrayLong)); + assertTrue(ArrayUtils.isSameLength(oneArrayByte, oneArrayInt)); + assertTrue(ArrayUtils.isSameLength(oneArrayByte, oneArrayShort)); + assertTrue(ArrayUtils.isSameLength(oneArrayByte, oneArrayChar)); + assertTrue(ArrayUtils.isSameLength(oneArrayByte, oneArrayByte)); + assertTrue(ArrayUtils.isSameLength(oneArrayByte, oneArrayDouble)); + assertTrue(ArrayUtils.isSameLength(oneArrayByte, oneArrayFloat)); + assertTrue(ArrayUtils.isSameLength(oneArrayDouble, oneArrayObject)); + assertTrue(ArrayUtils.isSameLength(oneArrayDouble, oneArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(oneArrayDouble, oneArrayLong)); + assertTrue(ArrayUtils.isSameLength(oneArrayDouble, oneArrayInt)); + assertTrue(ArrayUtils.isSameLength(oneArrayDouble, oneArrayShort)); + assertTrue(ArrayUtils.isSameLength(oneArrayDouble, oneArrayChar)); + assertTrue(ArrayUtils.isSameLength(oneArrayDouble, oneArrayByte)); + assertTrue(ArrayUtils.isSameLength(oneArrayDouble, oneArrayDouble)); + assertTrue(ArrayUtils.isSameLength(oneArrayDouble, oneArrayFloat)); + assertTrue(ArrayUtils.isSameLength(oneArrayFloat, oneArrayObject)); + assertTrue(ArrayUtils.isSameLength(oneArrayFloat, oneArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(oneArrayFloat, oneArrayLong)); + assertTrue(ArrayUtils.isSameLength(oneArrayFloat, oneArrayInt)); + assertTrue(ArrayUtils.isSameLength(oneArrayFloat, oneArrayShort)); + assertTrue(ArrayUtils.isSameLength(oneArrayFloat, oneArrayChar)); + assertTrue(ArrayUtils.isSameLength(oneArrayFloat, oneArrayByte)); + assertTrue(ArrayUtils.isSameLength(oneArrayFloat, oneArrayDouble)); + assertTrue(ArrayUtils.isSameLength(oneArrayFloat, oneArrayFloat)); + assertFalse(ArrayUtils.isSameLength(oneArrayObject, twoArrayObject)); + assertFalse(ArrayUtils.isSameLength(oneArrayObject, twoArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(oneArrayObject, twoArrayLong)); + assertFalse(ArrayUtils.isSameLength(oneArrayObject, twoArrayInt)); + assertFalse(ArrayUtils.isSameLength(oneArrayObject, twoArrayShort)); + assertFalse(ArrayUtils.isSameLength(oneArrayObject, twoArrayChar)); + assertFalse(ArrayUtils.isSameLength(oneArrayObject, twoArrayByte)); + assertFalse(ArrayUtils.isSameLength(oneArrayObject, twoArrayDouble)); + assertFalse(ArrayUtils.isSameLength(oneArrayObject, twoArrayFloat)); + assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, twoArrayObject)); + assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, twoArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, twoArrayLong)); + assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, twoArrayInt)); + assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, twoArrayShort)); + assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, twoArrayChar)); + assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, twoArrayByte)); + assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, twoArrayDouble)); + assertFalse(ArrayUtils.isSameLength(oneArrayBoolean, twoArrayFloat)); + assertFalse(ArrayUtils.isSameLength(oneArrayLong, twoArrayObject)); + assertFalse(ArrayUtils.isSameLength(oneArrayLong, twoArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(oneArrayLong, twoArrayLong)); + assertFalse(ArrayUtils.isSameLength(oneArrayLong, twoArrayInt)); + assertFalse(ArrayUtils.isSameLength(oneArrayLong, twoArrayShort)); + assertFalse(ArrayUtils.isSameLength(oneArrayLong, twoArrayChar)); + assertFalse(ArrayUtils.isSameLength(oneArrayLong, twoArrayByte)); + assertFalse(ArrayUtils.isSameLength(oneArrayLong, twoArrayDouble)); + assertFalse(ArrayUtils.isSameLength(oneArrayLong, twoArrayFloat)); + assertFalse(ArrayUtils.isSameLength(oneArrayInt, twoArrayObject)); + assertFalse(ArrayUtils.isSameLength(oneArrayInt, twoArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(oneArrayInt, twoArrayLong)); + assertFalse(ArrayUtils.isSameLength(oneArrayInt, twoArrayInt)); + assertFalse(ArrayUtils.isSameLength(oneArrayInt, twoArrayShort)); + assertFalse(ArrayUtils.isSameLength(oneArrayInt, twoArrayChar)); + assertFalse(ArrayUtils.isSameLength(oneArrayInt, twoArrayByte)); + assertFalse(ArrayUtils.isSameLength(oneArrayInt, twoArrayDouble)); + assertFalse(ArrayUtils.isSameLength(oneArrayInt, twoArrayFloat)); + assertFalse(ArrayUtils.isSameLength(oneArrayShort, twoArrayObject)); + assertFalse(ArrayUtils.isSameLength(oneArrayShort, twoArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(oneArrayShort, twoArrayLong)); + assertFalse(ArrayUtils.isSameLength(oneArrayShort, twoArrayInt)); + assertFalse(ArrayUtils.isSameLength(oneArrayShort, twoArrayShort)); + assertFalse(ArrayUtils.isSameLength(oneArrayShort, twoArrayChar)); + assertFalse(ArrayUtils.isSameLength(oneArrayShort, twoArrayByte)); + assertFalse(ArrayUtils.isSameLength(oneArrayShort, twoArrayDouble)); + assertFalse(ArrayUtils.isSameLength(oneArrayShort, twoArrayFloat)); + assertFalse(ArrayUtils.isSameLength(oneArrayChar, twoArrayObject)); + assertFalse(ArrayUtils.isSameLength(oneArrayChar, twoArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(oneArrayChar, twoArrayLong)); + assertFalse(ArrayUtils.isSameLength(oneArrayChar, twoArrayInt)); + assertFalse(ArrayUtils.isSameLength(oneArrayChar, twoArrayShort)); + assertFalse(ArrayUtils.isSameLength(oneArrayChar, twoArrayChar)); + assertFalse(ArrayUtils.isSameLength(oneArrayChar, twoArrayByte)); + assertFalse(ArrayUtils.isSameLength(oneArrayChar, twoArrayDouble)); + assertFalse(ArrayUtils.isSameLength(oneArrayChar, twoArrayFloat)); + assertFalse(ArrayUtils.isSameLength(oneArrayByte, twoArrayObject)); + assertFalse(ArrayUtils.isSameLength(oneArrayByte, twoArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(oneArrayByte, twoArrayLong)); + assertFalse(ArrayUtils.isSameLength(oneArrayByte, twoArrayInt)); + assertFalse(ArrayUtils.isSameLength(oneArrayByte, twoArrayShort)); + assertFalse(ArrayUtils.isSameLength(oneArrayByte, twoArrayChar)); + assertFalse(ArrayUtils.isSameLength(oneArrayByte, twoArrayByte)); + assertFalse(ArrayUtils.isSameLength(oneArrayByte, twoArrayDouble)); + assertFalse(ArrayUtils.isSameLength(oneArrayByte, twoArrayFloat)); + assertFalse(ArrayUtils.isSameLength(oneArrayDouble, twoArrayObject)); + assertFalse(ArrayUtils.isSameLength(oneArrayDouble, twoArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(oneArrayDouble, twoArrayLong)); + assertFalse(ArrayUtils.isSameLength(oneArrayDouble, twoArrayInt)); + assertFalse(ArrayUtils.isSameLength(oneArrayDouble, twoArrayShort)); + assertFalse(ArrayUtils.isSameLength(oneArrayDouble, twoArrayChar)); + assertFalse(ArrayUtils.isSameLength(oneArrayDouble, twoArrayByte)); + assertFalse(ArrayUtils.isSameLength(oneArrayDouble, twoArrayDouble)); + assertFalse(ArrayUtils.isSameLength(oneArrayDouble, twoArrayFloat)); + assertFalse(ArrayUtils.isSameLength(oneArrayFloat, twoArrayObject)); + assertFalse(ArrayUtils.isSameLength(oneArrayFloat, twoArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(oneArrayFloat, twoArrayLong)); + assertFalse(ArrayUtils.isSameLength(oneArrayFloat, twoArrayInt)); + assertFalse(ArrayUtils.isSameLength(oneArrayFloat, twoArrayShort)); + assertFalse(ArrayUtils.isSameLength(oneArrayFloat, twoArrayChar)); + assertFalse(ArrayUtils.isSameLength(oneArrayFloat, twoArrayByte)); + assertFalse(ArrayUtils.isSameLength(oneArrayFloat, twoArrayDouble)); + assertFalse(ArrayUtils.isSameLength(oneArrayFloat, twoArrayFloat)); + assertFalse(ArrayUtils.isSameLength(twoArrayObject, nullArrayObject)); + assertFalse(ArrayUtils.isSameLength(twoArrayObject, nullArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(twoArrayObject, nullArrayLong)); + assertFalse(ArrayUtils.isSameLength(twoArrayObject, nullArrayInt)); + assertFalse(ArrayUtils.isSameLength(twoArrayObject, nullArrayShort)); + assertFalse(ArrayUtils.isSameLength(twoArrayObject, nullArrayChar)); + assertFalse(ArrayUtils.isSameLength(twoArrayObject, nullArrayByte)); + assertFalse(ArrayUtils.isSameLength(twoArrayObject, nullArrayDouble)); + assertFalse(ArrayUtils.isSameLength(twoArrayObject, nullArrayFloat)); + assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, nullArrayObject)); + assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, nullArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, nullArrayLong)); + assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, nullArrayInt)); + assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, nullArrayShort)); + assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, nullArrayChar)); + assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, nullArrayByte)); + assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, nullArrayDouble)); + assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, nullArrayFloat)); + assertFalse(ArrayUtils.isSameLength(twoArrayLong, nullArrayObject)); + assertFalse(ArrayUtils.isSameLength(twoArrayLong, nullArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(twoArrayLong, nullArrayLong)); + assertFalse(ArrayUtils.isSameLength(twoArrayLong, nullArrayInt)); + assertFalse(ArrayUtils.isSameLength(twoArrayLong, nullArrayShort)); + assertFalse(ArrayUtils.isSameLength(twoArrayLong, nullArrayChar)); + assertFalse(ArrayUtils.isSameLength(twoArrayLong, nullArrayByte)); + assertFalse(ArrayUtils.isSameLength(twoArrayLong, nullArrayDouble)); + assertFalse(ArrayUtils.isSameLength(twoArrayLong, nullArrayFloat)); + assertFalse(ArrayUtils.isSameLength(twoArrayInt, nullArrayObject)); + assertFalse(ArrayUtils.isSameLength(twoArrayInt, nullArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(twoArrayInt, nullArrayLong)); + assertFalse(ArrayUtils.isSameLength(twoArrayInt, nullArrayInt)); + assertFalse(ArrayUtils.isSameLength(twoArrayInt, nullArrayShort)); + assertFalse(ArrayUtils.isSameLength(twoArrayInt, nullArrayChar)); + assertFalse(ArrayUtils.isSameLength(twoArrayInt, nullArrayByte)); + assertFalse(ArrayUtils.isSameLength(twoArrayInt, nullArrayDouble)); + assertFalse(ArrayUtils.isSameLength(twoArrayInt, nullArrayFloat)); + assertFalse(ArrayUtils.isSameLength(twoArrayShort, nullArrayObject)); + assertFalse(ArrayUtils.isSameLength(twoArrayShort, nullArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(twoArrayShort, nullArrayLong)); + assertFalse(ArrayUtils.isSameLength(twoArrayShort, nullArrayInt)); + assertFalse(ArrayUtils.isSameLength(twoArrayShort, nullArrayShort)); + assertFalse(ArrayUtils.isSameLength(twoArrayShort, nullArrayChar)); + assertFalse(ArrayUtils.isSameLength(twoArrayShort, nullArrayByte)); + assertFalse(ArrayUtils.isSameLength(twoArrayShort, nullArrayDouble)); + assertFalse(ArrayUtils.isSameLength(twoArrayShort, nullArrayFloat)); + assertFalse(ArrayUtils.isSameLength(twoArrayChar, nullArrayObject)); + assertFalse(ArrayUtils.isSameLength(twoArrayChar, nullArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(twoArrayChar, nullArrayLong)); + assertFalse(ArrayUtils.isSameLength(twoArrayChar, nullArrayInt)); + assertFalse(ArrayUtils.isSameLength(twoArrayChar, nullArrayShort)); + assertFalse(ArrayUtils.isSameLength(twoArrayChar, nullArrayChar)); + assertFalse(ArrayUtils.isSameLength(twoArrayChar, nullArrayByte)); + assertFalse(ArrayUtils.isSameLength(twoArrayChar, nullArrayDouble)); + assertFalse(ArrayUtils.isSameLength(twoArrayChar, nullArrayFloat)); + assertFalse(ArrayUtils.isSameLength(twoArrayByte, nullArrayObject)); + assertFalse(ArrayUtils.isSameLength(twoArrayByte, nullArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(twoArrayByte, nullArrayLong)); + assertFalse(ArrayUtils.isSameLength(twoArrayByte, nullArrayInt)); + assertFalse(ArrayUtils.isSameLength(twoArrayByte, nullArrayShort)); + assertFalse(ArrayUtils.isSameLength(twoArrayByte, nullArrayChar)); + assertFalse(ArrayUtils.isSameLength(twoArrayByte, nullArrayByte)); + assertFalse(ArrayUtils.isSameLength(twoArrayByte, nullArrayDouble)); + assertFalse(ArrayUtils.isSameLength(twoArrayByte, nullArrayFloat)); + assertFalse(ArrayUtils.isSameLength(twoArrayDouble, nullArrayObject)); + assertFalse(ArrayUtils.isSameLength(twoArrayDouble, nullArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(twoArrayDouble, nullArrayLong)); + assertFalse(ArrayUtils.isSameLength(twoArrayDouble, nullArrayInt)); + assertFalse(ArrayUtils.isSameLength(twoArrayDouble, nullArrayShort)); + assertFalse(ArrayUtils.isSameLength(twoArrayDouble, nullArrayChar)); + assertFalse(ArrayUtils.isSameLength(twoArrayDouble, nullArrayByte)); + assertFalse(ArrayUtils.isSameLength(twoArrayDouble, nullArrayDouble)); + assertFalse(ArrayUtils.isSameLength(twoArrayDouble, nullArrayFloat)); + assertFalse(ArrayUtils.isSameLength(twoArrayFloat, nullArrayObject)); + assertFalse(ArrayUtils.isSameLength(twoArrayFloat, nullArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(twoArrayFloat, nullArrayLong)); + assertFalse(ArrayUtils.isSameLength(twoArrayFloat, nullArrayInt)); + assertFalse(ArrayUtils.isSameLength(twoArrayFloat, nullArrayShort)); + assertFalse(ArrayUtils.isSameLength(twoArrayFloat, nullArrayChar)); + assertFalse(ArrayUtils.isSameLength(twoArrayFloat, nullArrayByte)); + assertFalse(ArrayUtils.isSameLength(twoArrayFloat, nullArrayDouble)); + assertFalse(ArrayUtils.isSameLength(twoArrayFloat, nullArrayFloat)); + assertFalse(ArrayUtils.isSameLength(twoArrayObject, emptyArrayObject)); + assertFalse(ArrayUtils.isSameLength(twoArrayObject, emptyArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(twoArrayObject, emptyArrayLong)); + assertFalse(ArrayUtils.isSameLength(twoArrayObject, emptyArrayInt)); + assertFalse(ArrayUtils.isSameLength(twoArrayObject, emptyArrayShort)); + assertFalse(ArrayUtils.isSameLength(twoArrayObject, emptyArrayChar)); + assertFalse(ArrayUtils.isSameLength(twoArrayObject, emptyArrayByte)); + assertFalse(ArrayUtils.isSameLength(twoArrayObject, emptyArrayDouble)); + assertFalse(ArrayUtils.isSameLength(twoArrayObject, emptyArrayFloat)); + assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, emptyArrayObject)); + assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, emptyArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, emptyArrayLong)); + assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, emptyArrayInt)); + assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, emptyArrayShort)); + assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, emptyArrayChar)); + assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, emptyArrayByte)); + assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, emptyArrayDouble)); + assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, emptyArrayFloat)); + assertFalse(ArrayUtils.isSameLength(twoArrayLong, emptyArrayObject)); + assertFalse(ArrayUtils.isSameLength(twoArrayLong, emptyArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(twoArrayLong, emptyArrayLong)); + assertFalse(ArrayUtils.isSameLength(twoArrayLong, emptyArrayInt)); + assertFalse(ArrayUtils.isSameLength(twoArrayLong, emptyArrayShort)); + assertFalse(ArrayUtils.isSameLength(twoArrayLong, emptyArrayChar)); + assertFalse(ArrayUtils.isSameLength(twoArrayLong, emptyArrayByte)); + assertFalse(ArrayUtils.isSameLength(twoArrayLong, emptyArrayDouble)); + assertFalse(ArrayUtils.isSameLength(twoArrayLong, emptyArrayFloat)); + assertFalse(ArrayUtils.isSameLength(twoArrayInt, emptyArrayObject)); + assertFalse(ArrayUtils.isSameLength(twoArrayInt, emptyArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(twoArrayInt, emptyArrayLong)); + assertFalse(ArrayUtils.isSameLength(twoArrayInt, emptyArrayInt)); + assertFalse(ArrayUtils.isSameLength(twoArrayInt, emptyArrayShort)); + assertFalse(ArrayUtils.isSameLength(twoArrayInt, emptyArrayChar)); + assertFalse(ArrayUtils.isSameLength(twoArrayInt, emptyArrayByte)); + assertFalse(ArrayUtils.isSameLength(twoArrayInt, emptyArrayDouble)); + assertFalse(ArrayUtils.isSameLength(twoArrayInt, emptyArrayFloat)); + assertFalse(ArrayUtils.isSameLength(twoArrayShort, emptyArrayObject)); + assertFalse(ArrayUtils.isSameLength(twoArrayShort, emptyArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(twoArrayShort, emptyArrayLong)); + assertFalse(ArrayUtils.isSameLength(twoArrayShort, emptyArrayInt)); + assertFalse(ArrayUtils.isSameLength(twoArrayShort, emptyArrayShort)); + assertFalse(ArrayUtils.isSameLength(twoArrayShort, emptyArrayChar)); + assertFalse(ArrayUtils.isSameLength(twoArrayShort, emptyArrayByte)); + assertFalse(ArrayUtils.isSameLength(twoArrayShort, emptyArrayDouble)); + assertFalse(ArrayUtils.isSameLength(twoArrayShort, emptyArrayFloat)); + assertFalse(ArrayUtils.isSameLength(twoArrayChar, emptyArrayObject)); + assertFalse(ArrayUtils.isSameLength(twoArrayChar, emptyArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(twoArrayChar, emptyArrayLong)); + assertFalse(ArrayUtils.isSameLength(twoArrayChar, emptyArrayInt)); + assertFalse(ArrayUtils.isSameLength(twoArrayChar, emptyArrayShort)); + assertFalse(ArrayUtils.isSameLength(twoArrayChar, emptyArrayChar)); + assertFalse(ArrayUtils.isSameLength(twoArrayChar, emptyArrayByte)); + assertFalse(ArrayUtils.isSameLength(twoArrayChar, emptyArrayDouble)); + assertFalse(ArrayUtils.isSameLength(twoArrayChar, emptyArrayFloat)); + assertFalse(ArrayUtils.isSameLength(twoArrayByte, emptyArrayObject)); + assertFalse(ArrayUtils.isSameLength(twoArrayByte, emptyArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(twoArrayByte, emptyArrayLong)); + assertFalse(ArrayUtils.isSameLength(twoArrayByte, emptyArrayInt)); + assertFalse(ArrayUtils.isSameLength(twoArrayByte, emptyArrayShort)); + assertFalse(ArrayUtils.isSameLength(twoArrayByte, emptyArrayChar)); + assertFalse(ArrayUtils.isSameLength(twoArrayByte, emptyArrayByte)); + assertFalse(ArrayUtils.isSameLength(twoArrayByte, emptyArrayDouble)); + assertFalse(ArrayUtils.isSameLength(twoArrayByte, emptyArrayFloat)); + assertFalse(ArrayUtils.isSameLength(twoArrayDouble, emptyArrayObject)); + assertFalse(ArrayUtils.isSameLength(twoArrayDouble, emptyArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(twoArrayDouble, emptyArrayLong)); + assertFalse(ArrayUtils.isSameLength(twoArrayDouble, emptyArrayInt)); + assertFalse(ArrayUtils.isSameLength(twoArrayDouble, emptyArrayShort)); + assertFalse(ArrayUtils.isSameLength(twoArrayDouble, emptyArrayChar)); + assertFalse(ArrayUtils.isSameLength(twoArrayDouble, emptyArrayByte)); + assertFalse(ArrayUtils.isSameLength(twoArrayDouble, emptyArrayDouble)); + assertFalse(ArrayUtils.isSameLength(twoArrayDouble, emptyArrayFloat)); + assertFalse(ArrayUtils.isSameLength(twoArrayFloat, emptyArrayObject)); + assertFalse(ArrayUtils.isSameLength(twoArrayFloat, emptyArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(twoArrayFloat, emptyArrayLong)); + assertFalse(ArrayUtils.isSameLength(twoArrayFloat, emptyArrayInt)); + assertFalse(ArrayUtils.isSameLength(twoArrayFloat, emptyArrayShort)); + assertFalse(ArrayUtils.isSameLength(twoArrayFloat, emptyArrayChar)); + assertFalse(ArrayUtils.isSameLength(twoArrayFloat, emptyArrayByte)); + assertFalse(ArrayUtils.isSameLength(twoArrayFloat, emptyArrayDouble)); + assertFalse(ArrayUtils.isSameLength(twoArrayFloat, emptyArrayFloat)); + assertFalse(ArrayUtils.isSameLength(twoArrayObject, oneArrayObject)); + assertFalse(ArrayUtils.isSameLength(twoArrayObject, oneArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(twoArrayObject, oneArrayLong)); + assertFalse(ArrayUtils.isSameLength(twoArrayObject, oneArrayInt)); + assertFalse(ArrayUtils.isSameLength(twoArrayObject, oneArrayShort)); + assertFalse(ArrayUtils.isSameLength(twoArrayObject, oneArrayChar)); + assertFalse(ArrayUtils.isSameLength(twoArrayObject, oneArrayByte)); + assertFalse(ArrayUtils.isSameLength(twoArrayObject, oneArrayDouble)); + assertFalse(ArrayUtils.isSameLength(twoArrayObject, oneArrayFloat)); + assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, oneArrayObject)); + assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, oneArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, oneArrayLong)); + assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, oneArrayInt)); + assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, oneArrayShort)); + assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, oneArrayChar)); + assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, oneArrayByte)); + assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, oneArrayDouble)); + assertFalse(ArrayUtils.isSameLength(twoArrayBoolean, oneArrayFloat)); + assertFalse(ArrayUtils.isSameLength(twoArrayLong, oneArrayObject)); + assertFalse(ArrayUtils.isSameLength(twoArrayLong, oneArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(twoArrayLong, oneArrayLong)); + assertFalse(ArrayUtils.isSameLength(twoArrayLong, oneArrayInt)); + assertFalse(ArrayUtils.isSameLength(twoArrayLong, oneArrayShort)); + assertFalse(ArrayUtils.isSameLength(twoArrayLong, oneArrayChar)); + assertFalse(ArrayUtils.isSameLength(twoArrayLong, oneArrayByte)); + assertFalse(ArrayUtils.isSameLength(twoArrayLong, oneArrayDouble)); + assertFalse(ArrayUtils.isSameLength(twoArrayLong, oneArrayFloat)); + assertFalse(ArrayUtils.isSameLength(twoArrayInt, oneArrayObject)); + assertFalse(ArrayUtils.isSameLength(twoArrayInt, oneArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(twoArrayInt, oneArrayLong)); + assertFalse(ArrayUtils.isSameLength(twoArrayInt, oneArrayInt)); + assertFalse(ArrayUtils.isSameLength(twoArrayInt, oneArrayShort)); + assertFalse(ArrayUtils.isSameLength(twoArrayInt, oneArrayChar)); + assertFalse(ArrayUtils.isSameLength(twoArrayInt, oneArrayByte)); + assertFalse(ArrayUtils.isSameLength(twoArrayInt, oneArrayDouble)); + assertFalse(ArrayUtils.isSameLength(twoArrayInt, oneArrayFloat)); + assertFalse(ArrayUtils.isSameLength(twoArrayShort, oneArrayObject)); + assertFalse(ArrayUtils.isSameLength(twoArrayShort, oneArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(twoArrayShort, oneArrayLong)); + assertFalse(ArrayUtils.isSameLength(twoArrayShort, oneArrayInt)); + assertFalse(ArrayUtils.isSameLength(twoArrayShort, oneArrayShort)); + assertFalse(ArrayUtils.isSameLength(twoArrayShort, oneArrayChar)); + assertFalse(ArrayUtils.isSameLength(twoArrayShort, oneArrayByte)); + assertFalse(ArrayUtils.isSameLength(twoArrayShort, oneArrayDouble)); + assertFalse(ArrayUtils.isSameLength(twoArrayShort, oneArrayFloat)); + assertFalse(ArrayUtils.isSameLength(twoArrayChar, oneArrayObject)); + assertFalse(ArrayUtils.isSameLength(twoArrayChar, oneArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(twoArrayChar, oneArrayLong)); + assertFalse(ArrayUtils.isSameLength(twoArrayChar, oneArrayInt)); + assertFalse(ArrayUtils.isSameLength(twoArrayChar, oneArrayShort)); + assertFalse(ArrayUtils.isSameLength(twoArrayChar, oneArrayChar)); + assertFalse(ArrayUtils.isSameLength(twoArrayChar, oneArrayByte)); + assertFalse(ArrayUtils.isSameLength(twoArrayChar, oneArrayDouble)); + assertFalse(ArrayUtils.isSameLength(twoArrayChar, oneArrayFloat)); + assertFalse(ArrayUtils.isSameLength(twoArrayByte, oneArrayObject)); + assertFalse(ArrayUtils.isSameLength(twoArrayByte, oneArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(twoArrayByte, oneArrayLong)); + assertFalse(ArrayUtils.isSameLength(twoArrayByte, oneArrayInt)); + assertFalse(ArrayUtils.isSameLength(twoArrayByte, oneArrayShort)); + assertFalse(ArrayUtils.isSameLength(twoArrayByte, oneArrayChar)); + assertFalse(ArrayUtils.isSameLength(twoArrayByte, oneArrayByte)); + assertFalse(ArrayUtils.isSameLength(twoArrayByte, oneArrayDouble)); + assertFalse(ArrayUtils.isSameLength(twoArrayByte, oneArrayFloat)); + assertFalse(ArrayUtils.isSameLength(twoArrayDouble, oneArrayObject)); + assertFalse(ArrayUtils.isSameLength(twoArrayDouble, oneArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(twoArrayDouble, oneArrayLong)); + assertFalse(ArrayUtils.isSameLength(twoArrayDouble, oneArrayInt)); + assertFalse(ArrayUtils.isSameLength(twoArrayDouble, oneArrayShort)); + assertFalse(ArrayUtils.isSameLength(twoArrayDouble, oneArrayChar)); + assertFalse(ArrayUtils.isSameLength(twoArrayDouble, oneArrayByte)); + assertFalse(ArrayUtils.isSameLength(twoArrayDouble, oneArrayDouble)); + assertFalse(ArrayUtils.isSameLength(twoArrayDouble, oneArrayFloat)); + assertFalse(ArrayUtils.isSameLength(twoArrayFloat, oneArrayObject)); + assertFalse(ArrayUtils.isSameLength(twoArrayFloat, oneArrayBoolean)); + assertFalse(ArrayUtils.isSameLength(twoArrayFloat, oneArrayLong)); + assertFalse(ArrayUtils.isSameLength(twoArrayFloat, oneArrayInt)); + assertFalse(ArrayUtils.isSameLength(twoArrayFloat, oneArrayShort)); + assertFalse(ArrayUtils.isSameLength(twoArrayFloat, oneArrayChar)); + assertFalse(ArrayUtils.isSameLength(twoArrayFloat, oneArrayByte)); + assertFalse(ArrayUtils.isSameLength(twoArrayFloat, oneArrayDouble)); + assertFalse(ArrayUtils.isSameLength(twoArrayFloat, oneArrayFloat)); + assertTrue(ArrayUtils.isSameLength(twoArrayObject, twoArrayObject)); + assertTrue(ArrayUtils.isSameLength(twoArrayObject, twoArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(twoArrayObject, twoArrayLong)); + assertTrue(ArrayUtils.isSameLength(twoArrayObject, twoArrayInt)); + assertTrue(ArrayUtils.isSameLength(twoArrayObject, twoArrayShort)); + assertTrue(ArrayUtils.isSameLength(twoArrayObject, twoArrayChar)); + assertTrue(ArrayUtils.isSameLength(twoArrayObject, twoArrayByte)); + assertTrue(ArrayUtils.isSameLength(twoArrayObject, twoArrayDouble)); + assertTrue(ArrayUtils.isSameLength(twoArrayObject, twoArrayFloat)); + assertTrue(ArrayUtils.isSameLength(twoArrayBoolean, twoArrayObject)); + assertTrue(ArrayUtils.isSameLength(twoArrayBoolean, twoArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(twoArrayBoolean, twoArrayLong)); + assertTrue(ArrayUtils.isSameLength(twoArrayBoolean, twoArrayInt)); + assertTrue(ArrayUtils.isSameLength(twoArrayBoolean, twoArrayShort)); + assertTrue(ArrayUtils.isSameLength(twoArrayBoolean, twoArrayChar)); + assertTrue(ArrayUtils.isSameLength(twoArrayBoolean, twoArrayByte)); + assertTrue(ArrayUtils.isSameLength(twoArrayBoolean, twoArrayDouble)); + assertTrue(ArrayUtils.isSameLength(twoArrayBoolean, twoArrayFloat)); + assertTrue(ArrayUtils.isSameLength(twoArrayLong, twoArrayObject)); + assertTrue(ArrayUtils.isSameLength(twoArrayLong, twoArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(twoArrayLong, twoArrayLong)); + assertTrue(ArrayUtils.isSameLength(twoArrayLong, twoArrayInt)); + assertTrue(ArrayUtils.isSameLength(twoArrayLong, twoArrayShort)); + assertTrue(ArrayUtils.isSameLength(twoArrayLong, twoArrayChar)); + assertTrue(ArrayUtils.isSameLength(twoArrayLong, twoArrayByte)); + assertTrue(ArrayUtils.isSameLength(twoArrayLong, twoArrayDouble)); + assertTrue(ArrayUtils.isSameLength(twoArrayLong, twoArrayFloat)); + assertTrue(ArrayUtils.isSameLength(twoArrayInt, twoArrayObject)); + assertTrue(ArrayUtils.isSameLength(twoArrayInt, twoArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(twoArrayInt, twoArrayLong)); + assertTrue(ArrayUtils.isSameLength(twoArrayInt, twoArrayInt)); + assertTrue(ArrayUtils.isSameLength(twoArrayInt, twoArrayShort)); + assertTrue(ArrayUtils.isSameLength(twoArrayInt, twoArrayChar)); + assertTrue(ArrayUtils.isSameLength(twoArrayInt, twoArrayByte)); + assertTrue(ArrayUtils.isSameLength(twoArrayInt, twoArrayDouble)); + assertTrue(ArrayUtils.isSameLength(twoArrayInt, twoArrayFloat)); + assertTrue(ArrayUtils.isSameLength(twoArrayShort, twoArrayObject)); + assertTrue(ArrayUtils.isSameLength(twoArrayShort, twoArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(twoArrayShort, twoArrayLong)); + assertTrue(ArrayUtils.isSameLength(twoArrayShort, twoArrayInt)); + assertTrue(ArrayUtils.isSameLength(twoArrayShort, twoArrayShort)); + assertTrue(ArrayUtils.isSameLength(twoArrayShort, twoArrayChar)); + assertTrue(ArrayUtils.isSameLength(twoArrayShort, twoArrayByte)); + assertTrue(ArrayUtils.isSameLength(twoArrayShort, twoArrayDouble)); + assertTrue(ArrayUtils.isSameLength(twoArrayShort, twoArrayFloat)); + assertTrue(ArrayUtils.isSameLength(twoArrayChar, twoArrayObject)); + assertTrue(ArrayUtils.isSameLength(twoArrayChar, twoArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(twoArrayChar, twoArrayLong)); + assertTrue(ArrayUtils.isSameLength(twoArrayChar, twoArrayInt)); + assertTrue(ArrayUtils.isSameLength(twoArrayChar, twoArrayShort)); + assertTrue(ArrayUtils.isSameLength(twoArrayChar, twoArrayChar)); + assertTrue(ArrayUtils.isSameLength(twoArrayChar, twoArrayByte)); + assertTrue(ArrayUtils.isSameLength(twoArrayChar, twoArrayDouble)); + assertTrue(ArrayUtils.isSameLength(twoArrayChar, twoArrayFloat)); + assertTrue(ArrayUtils.isSameLength(twoArrayByte, twoArrayObject)); + assertTrue(ArrayUtils.isSameLength(twoArrayByte, twoArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(twoArrayByte, twoArrayLong)); + assertTrue(ArrayUtils.isSameLength(twoArrayByte, twoArrayInt)); + assertTrue(ArrayUtils.isSameLength(twoArrayByte, twoArrayShort)); + assertTrue(ArrayUtils.isSameLength(twoArrayByte, twoArrayChar)); + assertTrue(ArrayUtils.isSameLength(twoArrayByte, twoArrayByte)); + assertTrue(ArrayUtils.isSameLength(twoArrayByte, twoArrayDouble)); + assertTrue(ArrayUtils.isSameLength(twoArrayByte, twoArrayFloat)); + assertTrue(ArrayUtils.isSameLength(twoArrayDouble, twoArrayObject)); + assertTrue(ArrayUtils.isSameLength(twoArrayDouble, twoArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(twoArrayDouble, twoArrayLong)); + assertTrue(ArrayUtils.isSameLength(twoArrayDouble, twoArrayInt)); + assertTrue(ArrayUtils.isSameLength(twoArrayDouble, twoArrayShort)); + assertTrue(ArrayUtils.isSameLength(twoArrayDouble, twoArrayChar)); + assertTrue(ArrayUtils.isSameLength(twoArrayDouble, twoArrayByte)); + assertTrue(ArrayUtils.isSameLength(twoArrayDouble, twoArrayDouble)); + assertTrue(ArrayUtils.isSameLength(twoArrayDouble, twoArrayFloat)); + assertTrue(ArrayUtils.isSameLength(twoArrayFloat, twoArrayObject)); + assertTrue(ArrayUtils.isSameLength(twoArrayFloat, twoArrayBoolean)); + assertTrue(ArrayUtils.isSameLength(twoArrayFloat, twoArrayLong)); + assertTrue(ArrayUtils.isSameLength(twoArrayFloat, twoArrayInt)); + assertTrue(ArrayUtils.isSameLength(twoArrayFloat, twoArrayShort)); + assertTrue(ArrayUtils.isSameLength(twoArrayFloat, twoArrayChar)); + assertTrue(ArrayUtils.isSameLength(twoArrayFloat, twoArrayByte)); + assertTrue(ArrayUtils.isSameLength(twoArrayFloat, twoArrayDouble)); + assertTrue(ArrayUtils.isSameLength(twoArrayFloat, twoArrayFloat)); } @Test - public void testSwapShortRange() { - short[] array = new short[]{1, 2, 3, 4}; - ArrayUtils.swap(array, 0, 2, 2); - assertEquals(3, array[0]); - assertEquals(4, array[1]); - assertEquals(1, array[2]); - assertEquals(2, array[3]); - - array = new short[]{1, 2, 3}; - ArrayUtils.swap(array, 3, 0); - assertEquals(1, array[0]); - assertEquals(2, array[1]); - assertEquals(3, array[2]); + public void testSameLengthBoolean() { + final boolean[] nullArray = null; + final boolean[] emptyArray = new boolean[0]; + final boolean[] oneArray = new boolean[]{true}; + final boolean[] twoArray = new boolean[]{true, false}; - array = new short[]{1, 2, 3}; - ArrayUtils.swap(array, 0, 2, 2); - assertEquals(3, array[0]); - assertEquals(2, array[1]); - assertEquals(1, array[2]); + assertTrue(ArrayUtils.isSameLength(nullArray, nullArray)); + assertTrue(ArrayUtils.isSameLength(nullArray, emptyArray)); + assertFalse(ArrayUtils.isSameLength(nullArray, oneArray)); + assertFalse(ArrayUtils.isSameLength(nullArray, twoArray)); - array = new short[]{1, 2, 3}; - ArrayUtils.swap(array, -1, 2, 2); - assertEquals(3, array[0]); - assertEquals(2, array[1]); - assertEquals(1, array[2]); + assertTrue(ArrayUtils.isSameLength(emptyArray, nullArray)); + assertTrue(ArrayUtils.isSameLength(emptyArray, emptyArray)); + assertFalse(ArrayUtils.isSameLength(emptyArray, oneArray)); + assertFalse(ArrayUtils.isSameLength(emptyArray, twoArray)); - array = new short[]{1, 2, 3}; - ArrayUtils.swap(array, 0, -1, 2); - assertEquals(1, array[0]); - assertEquals(2, array[1]); - assertEquals(3, array[2]); + assertFalse(ArrayUtils.isSameLength(oneArray, nullArray)); + assertFalse(ArrayUtils.isSameLength(oneArray, emptyArray)); + assertTrue(ArrayUtils.isSameLength(oneArray, oneArray)); + assertFalse(ArrayUtils.isSameLength(oneArray, twoArray)); - array = new short[]{1, 2, 3}; - ArrayUtils.swap(array, -1, -1, 2); - assertEquals(1, array[0]); - assertEquals(2, array[1]); - assertEquals(3, array[2]); + assertFalse(ArrayUtils.isSameLength(twoArray, nullArray)); + assertFalse(ArrayUtils.isSameLength(twoArray, emptyArray)); + assertFalse(ArrayUtils.isSameLength(twoArray, oneArray)); + assertTrue(ArrayUtils.isSameLength(twoArray, twoArray)); } @Test - public void testSwapNullCharArray() { - final char[] array = null; - ArrayUtils.swap(array, 0, 2); - assertNull(array); - } + public void testSameLengthByte() { + final byte[] nullArray = null; + final byte[] emptyArray = new byte[0]; + final byte[] oneArray = new byte[]{3}; + final byte[] twoArray = new byte[]{4, 6}; - @Test - public void testSwapEmptyCharArray() { - final char[] array = new char[0]; - ArrayUtils.swap(array, 0, 2); - assertEquals(0, array.length); - } + assertTrue(ArrayUtils.isSameLength(nullArray, nullArray)); + assertTrue(ArrayUtils.isSameLength(nullArray, emptyArray)); + assertFalse(ArrayUtils.isSameLength(nullArray, oneArray)); + assertFalse(ArrayUtils.isSameLength(nullArray, twoArray)); - @Test - public void testSwapLong() { - final long[] array = new long[]{1, 2, 3}; - ArrayUtils.swap(array, 0, 2); - assertEquals(3, array[0]); - assertEquals(2, array[1]); - assertEquals(1, array[2]); - } + assertTrue(ArrayUtils.isSameLength(emptyArray, nullArray)); + assertTrue(ArrayUtils.isSameLength(emptyArray, emptyArray)); + assertFalse(ArrayUtils.isSameLength(emptyArray, oneArray)); + assertFalse(ArrayUtils.isSameLength(emptyArray, twoArray)); - @Test - public void testSwapNullLongArray() { - final long[] array = null; - ArrayUtils.swap(array, 0, 2); - assertNull(array); - } + assertFalse(ArrayUtils.isSameLength(oneArray, nullArray)); + assertFalse(ArrayUtils.isSameLength(oneArray, emptyArray)); + assertTrue(ArrayUtils.isSameLength(oneArray, oneArray)); + assertFalse(ArrayUtils.isSameLength(oneArray, twoArray)); - @Test - public void testSwapEmptyLongArray() { - final long[] array = new long[0]; - ArrayUtils.swap(array, 0, 2); - assertEquals(0, array.length); + assertFalse(ArrayUtils.isSameLength(twoArray, nullArray)); + assertFalse(ArrayUtils.isSameLength(twoArray, emptyArray)); + assertFalse(ArrayUtils.isSameLength(twoArray, oneArray)); + assertTrue(ArrayUtils.isSameLength(twoArray, twoArray)); } @Test - public void testSwapLongRange() { - long[] array = new long[]{1, 2, 3, 4}; - ArrayUtils.swap(array, 0, 2, 2); - assertEquals(3, array[0]); - assertEquals(4, array[1]); - assertEquals(1, array[2]); - assertEquals(2, array[3]); - - array = new long[]{1, 2, 3}; - ArrayUtils.swap(array, 0, 3); - assertEquals(1, array[0]); - assertEquals(2, array[1]); - assertEquals(3, array[2]); - - array = new long[]{1, 2, 3}; - ArrayUtils.swap(array, 0, 2, 2); - assertEquals(3, array[0]); - assertEquals(2, array[1]); - assertEquals(1, array[2]); - - array = new long[]{1, 2, 3}; - ArrayUtils.swap(array, -1, 2, 2); - assertEquals(3, array[0]); - assertEquals(2, array[1]); - assertEquals(1, array[2]); - - array = new long[]{1, 2, 3}; - ArrayUtils.swap(array, 0, -1, 2); - assertEquals(1, array[0]); - assertEquals(2, array[1]); - assertEquals(3, array[2]); + public void testSameLengthChar() { + final char[] nullArray = null; + final char[] emptyArray = new char[0]; + final char[] oneArray = new char[]{'f'}; + final char[] twoArray = new char[]{'d', 't'}; - array = new long[]{1, 2, 3}; - ArrayUtils.swap(array, -1, -1, 2); - assertEquals(1, array[0]); - assertEquals(2, array[1]); - assertEquals(3, array[2]); - } + assertTrue(ArrayUtils.isSameLength(nullArray, nullArray)); + assertTrue(ArrayUtils.isSameLength(nullArray, emptyArray)); + assertFalse(ArrayUtils.isSameLength(nullArray, oneArray)); + assertFalse(ArrayUtils.isSameLength(nullArray, twoArray)); - @Test - public void testSwapBoolean() { - final boolean[] array = new boolean[]{true, false, false}; - ArrayUtils.swap(array, 0, 2); - assertFalse(array[0]); - assertFalse(array[1]); - assertTrue(array[2]); - } + assertTrue(ArrayUtils.isSameLength(emptyArray, nullArray)); + assertTrue(ArrayUtils.isSameLength(emptyArray, emptyArray)); + assertFalse(ArrayUtils.isSameLength(emptyArray, oneArray)); + assertFalse(ArrayUtils.isSameLength(emptyArray, twoArray)); - @Test - public void testSwapNullBooleanArray() { - final boolean[] array = null; - ArrayUtils.swap(array, 0, 2); - assertNull(array); - } + assertFalse(ArrayUtils.isSameLength(oneArray, nullArray)); + assertFalse(ArrayUtils.isSameLength(oneArray, emptyArray)); + assertTrue(ArrayUtils.isSameLength(oneArray, oneArray)); + assertFalse(ArrayUtils.isSameLength(oneArray, twoArray)); - @Test - public void testSwapEmptyBooleanArray() { - final boolean[] array = new boolean[0]; - ArrayUtils.swap(array, 0, 2); - assertEquals(0, array.length); + assertFalse(ArrayUtils.isSameLength(twoArray, nullArray)); + assertFalse(ArrayUtils.isSameLength(twoArray, emptyArray)); + assertFalse(ArrayUtils.isSameLength(twoArray, oneArray)); + assertTrue(ArrayUtils.isSameLength(twoArray, twoArray)); } @Test - public void testSwapBooleanRange() { - boolean[] array = new boolean[]{false, false, true, true}; - ArrayUtils.swap(array, 0, 2, 2); - assertTrue(array[0]); - assertTrue(array[1]); - assertFalse(array[2]); - assertFalse(array[3]); - - array = new boolean[]{false, true, false}; - ArrayUtils.swap(array, 0, 3); - assertFalse(array[0]); - assertTrue(array[1]); - assertFalse(array[2]); + public void testSameLengthDouble() { + final double[] nullArray = null; + final double[] emptyArray = new double[0]; + final double[] oneArray = new double[]{1.3d}; + final double[] twoArray = new double[]{4.5d, 6.3d}; - array = new boolean[]{true, true, false}; - ArrayUtils.swap(array, 0, 2, 2); - assertFalse(array[0]); - assertTrue(array[1]); - assertTrue(array[2]); + assertTrue(ArrayUtils.isSameLength(nullArray, nullArray)); + assertTrue(ArrayUtils.isSameLength(nullArray, emptyArray)); + assertFalse(ArrayUtils.isSameLength(nullArray, oneArray)); + assertFalse(ArrayUtils.isSameLength(nullArray, twoArray)); - array = new boolean[]{true, true, false}; - ArrayUtils.swap(array, -1, 2, 2); - assertFalse(array[0]); - assertTrue(array[1]); - assertTrue(array[2]); + assertTrue(ArrayUtils.isSameLength(emptyArray, nullArray)); + assertTrue(ArrayUtils.isSameLength(emptyArray, emptyArray)); + assertFalse(ArrayUtils.isSameLength(emptyArray, oneArray)); + assertFalse(ArrayUtils.isSameLength(emptyArray, twoArray)); - array = new boolean[]{true, true, false}; - ArrayUtils.swap(array, 0, -1, 2); - assertTrue(array[0]); - assertTrue(array[1]); - assertFalse(array[2]); + assertFalse(ArrayUtils.isSameLength(oneArray, nullArray)); + assertFalse(ArrayUtils.isSameLength(oneArray, emptyArray)); + assertTrue(ArrayUtils.isSameLength(oneArray, oneArray)); + assertFalse(ArrayUtils.isSameLength(oneArray, twoArray)); - array = new boolean[]{true, true, false}; - ArrayUtils.swap(array, -1, -1, 2); - assertTrue(array[0]); - assertTrue(array[1]); - assertFalse(array[2]); + assertFalse(ArrayUtils.isSameLength(twoArray, nullArray)); + assertFalse(ArrayUtils.isSameLength(twoArray, emptyArray)); + assertFalse(ArrayUtils.isSameLength(twoArray, oneArray)); + assertTrue(ArrayUtils.isSameLength(twoArray, twoArray)); } @Test - public void testSwapObject() { - final String[] array = new String[]{"1", "2", "3"}; - ArrayUtils.swap(array, 0, 2); - assertEquals("3", array[0]); - assertEquals("2", array[1]); - assertEquals("1", array[2]); - } + public void testSameLengthFloat() { + final float[] nullArray = null; + final float[] emptyArray = new float[0]; + final float[] oneArray = new float[]{2.5f}; + final float[] twoArray = new float[]{6.4f, 5.8f}; - @Test - public void testSwapNullObjectArray() { - final String[] array = null; - ArrayUtils.swap(array, 0, 2); - assertNull(array); - } + assertTrue(ArrayUtils.isSameLength(nullArray, nullArray)); + assertTrue(ArrayUtils.isSameLength(nullArray, emptyArray)); + assertFalse(ArrayUtils.isSameLength(nullArray, oneArray)); + assertFalse(ArrayUtils.isSameLength(nullArray, twoArray)); - @Test - public void testSwapEmptyObjectArray() { - final String[] array = new String[0]; - ArrayUtils.swap(array, 0, 2); - assertEquals(0, array.length); + assertTrue(ArrayUtils.isSameLength(emptyArray, nullArray)); + assertTrue(ArrayUtils.isSameLength(emptyArray, emptyArray)); + assertFalse(ArrayUtils.isSameLength(emptyArray, oneArray)); + assertFalse(ArrayUtils.isSameLength(emptyArray, twoArray)); + + assertFalse(ArrayUtils.isSameLength(oneArray, nullArray)); + assertFalse(ArrayUtils.isSameLength(oneArray, emptyArray)); + assertTrue(ArrayUtils.isSameLength(oneArray, oneArray)); + assertFalse(ArrayUtils.isSameLength(oneArray, twoArray)); + + assertFalse(ArrayUtils.isSameLength(twoArray, nullArray)); + assertFalse(ArrayUtils.isSameLength(twoArray, emptyArray)); + assertFalse(ArrayUtils.isSameLength(twoArray, oneArray)); + assertTrue(ArrayUtils.isSameLength(twoArray, twoArray)); } @Test - public void testSwapObjectRange() { - String[] array = new String[]{"1", "2", "3", "4"}; - ArrayUtils.swap(array, 0, 2, 2); - assertEquals("3", array[0]); - assertEquals("4", array[1]); - assertEquals("1", array[2]); - assertEquals("2", array[3]); - - array = new String[]{"1", "2", "3", "4"}; - ArrayUtils.swap(array, -1, 2, 3); - assertEquals("3", array[0]); - assertEquals("4", array[1]); - assertEquals("1", array[2]); - assertEquals("2", array[3]); + public void testSameLengthInt() { + final int[] nullArray = null; + final int[] emptyArray = new int[0]; + final int[] oneArray = new int[]{4}; + final int[] twoArray = new int[]{5, 7}; - array = new String[]{"1", "2", "3", "4", "5"}; - ArrayUtils.swap(array, -3, 2, 3); - assertEquals("3", array[0]); - assertEquals("4", array[1]); - assertEquals("5", array[2]); - assertEquals("2", array[3]); - assertEquals("1", array[4]); + assertTrue(ArrayUtils.isSameLength(nullArray, nullArray)); + assertTrue(ArrayUtils.isSameLength(nullArray, emptyArray)); + assertFalse(ArrayUtils.isSameLength(nullArray, oneArray)); + assertFalse(ArrayUtils.isSameLength(nullArray, twoArray)); - array = new String[]{"1", "2", "3", "4", "5"}; - ArrayUtils.swap(array, 2, -2, 3); - assertEquals("3", array[0]); - assertEquals("4", array[1]); - assertEquals("5", array[2]); - assertEquals("2", array[3]); - assertEquals("1", array[4]); + assertTrue(ArrayUtils.isSameLength(emptyArray, nullArray)); + assertTrue(ArrayUtils.isSameLength(emptyArray, emptyArray)); + assertFalse(ArrayUtils.isSameLength(emptyArray, oneArray)); + assertFalse(ArrayUtils.isSameLength(emptyArray, twoArray)); - array = new String[0]; - ArrayUtils.swap(array, 0, 2, 2); - assertEquals(0, array.length); + assertFalse(ArrayUtils.isSameLength(oneArray, nullArray)); + assertFalse(ArrayUtils.isSameLength(oneArray, emptyArray)); + assertTrue(ArrayUtils.isSameLength(oneArray, oneArray)); + assertFalse(ArrayUtils.isSameLength(oneArray, twoArray)); - array = null; - ArrayUtils.swap(array, 0, 2, 2); - assertNull(array); + assertFalse(ArrayUtils.isSameLength(twoArray, nullArray)); + assertFalse(ArrayUtils.isSameLength(twoArray, emptyArray)); + assertFalse(ArrayUtils.isSameLength(twoArray, oneArray)); + assertTrue(ArrayUtils.isSameLength(twoArray, twoArray)); } - //----------------------------------------------------------------------- @Test - public void testShiftDouble() { - final double[] array = new double[]{1, 2, 3, 4}; - ArrayUtils.shift(array, 1); - assertEquals(4, array[0]); - assertEquals(1, array[1]); - assertEquals(2, array[2]); - assertEquals(3, array[3]); - ArrayUtils.shift(array, -1); - assertEquals(1, array[0]); - assertEquals(2, array[1]); - assertEquals(3, array[2]); - assertEquals(4, array[3]); - ArrayUtils.shift(array, 5); - assertEquals(4, array[0]); - assertEquals(1, array[1]); - assertEquals(2, array[2]); - assertEquals(3, array[3]); - ArrayUtils.shift(array, -3); - assertEquals(3, array[0]); - assertEquals(4, array[1]); - assertEquals(1, array[2]); - assertEquals(2, array[3]); - } + public void testSameLengthLong() { + final long[] nullArray = null; + final long[] emptyArray = new long[0]; + final long[] oneArray = new long[]{0L}; + final long[] twoArray = new long[]{0L, 76L}; - @Test - public void testShiftRangeDouble() { - final double[] array = new double[]{1, 2, 3, 4, 5}; - ArrayUtils.shift(array, 1, 3, 1); - assertEquals(1, array[0]); - assertEquals(3, array[1]); - assertEquals(2, array[2]); - assertEquals(4, array[3]); - assertEquals(5, array[4]); - ArrayUtils.shift(array, 1, 4, 2); - assertEquals(1, array[0]); - assertEquals(2, array[1]); - assertEquals(4, array[2]); - assertEquals(3, array[3]); - assertEquals(5, array[4]); - } + assertTrue(ArrayUtils.isSameLength(nullArray, nullArray)); + assertTrue(ArrayUtils.isSameLength(nullArray, emptyArray)); + assertFalse(ArrayUtils.isSameLength(nullArray, oneArray)); + assertFalse(ArrayUtils.isSameLength(nullArray, twoArray)); - @Test - public void testShiftRangeNoElemDouble() { - final double[] array = new double[]{1, 2, 3, 4}; - ArrayUtils.shift(array, 1, 1, 1); - assertEquals(1, array[0]); - assertEquals(2, array[1]); - assertEquals(3, array[2]); - assertEquals(4, array[3]); - } + assertTrue(ArrayUtils.isSameLength(emptyArray, nullArray)); + assertTrue(ArrayUtils.isSameLength(emptyArray, emptyArray)); + assertFalse(ArrayUtils.isSameLength(emptyArray, oneArray)); + assertFalse(ArrayUtils.isSameLength(emptyArray, twoArray)); - @Test - public void testShiftRangeNullDouble() { - final double[] array = null; - ArrayUtils.shift(array, 1, 1, 1); - assertNull(array); + assertFalse(ArrayUtils.isSameLength(oneArray, nullArray)); + assertFalse(ArrayUtils.isSameLength(oneArray, emptyArray)); + assertTrue(ArrayUtils.isSameLength(oneArray, oneArray)); + assertFalse(ArrayUtils.isSameLength(oneArray, twoArray)); + + assertFalse(ArrayUtils.isSameLength(twoArray, nullArray)); + assertFalse(ArrayUtils.isSameLength(twoArray, emptyArray)); + assertFalse(ArrayUtils.isSameLength(twoArray, oneArray)); + assertTrue(ArrayUtils.isSameLength(twoArray, twoArray)); } @Test - public void testShiftNullDouble() { - final double[] array = null; + public void testSameLengthShort() { + final short[] nullArray = null; + final short[] emptyArray = new short[0]; + final short[] oneArray = new short[]{4}; + final short[] twoArray = new short[]{6, 8}; - ArrayUtils.shift(array, 1); - assertNull(array); + assertTrue(ArrayUtils.isSameLength(nullArray, nullArray)); + assertTrue(ArrayUtils.isSameLength(nullArray, emptyArray)); + assertFalse(ArrayUtils.isSameLength(nullArray, oneArray)); + assertFalse(ArrayUtils.isSameLength(nullArray, twoArray)); + + assertTrue(ArrayUtils.isSameLength(emptyArray, nullArray)); + assertTrue(ArrayUtils.isSameLength(emptyArray, emptyArray)); + assertFalse(ArrayUtils.isSameLength(emptyArray, oneArray)); + assertFalse(ArrayUtils.isSameLength(emptyArray, twoArray)); + + assertFalse(ArrayUtils.isSameLength(oneArray, nullArray)); + assertFalse(ArrayUtils.isSameLength(oneArray, emptyArray)); + assertTrue(ArrayUtils.isSameLength(oneArray, oneArray)); + assertFalse(ArrayUtils.isSameLength(oneArray, twoArray)); + + assertFalse(ArrayUtils.isSameLength(twoArray, nullArray)); + assertFalse(ArrayUtils.isSameLength(twoArray, emptyArray)); + assertFalse(ArrayUtils.isSameLength(twoArray, oneArray)); + assertTrue(ArrayUtils.isSameLength(twoArray, twoArray)); } + //----------------------------------------------------------------------- @Test - public void testShiftAllDouble() { - final double[] array = new double[]{1, 2, 3, 4}; - ArrayUtils.shift(array, 4); - assertEquals(1, array[0]); - assertEquals(2, array[1]); - assertEquals(3, array[2]); - assertEquals(4, array[3]); - ArrayUtils.shift(array, -4); - assertEquals(1, array[0]); - assertEquals(2, array[1]); - assertEquals(3, array[2]); - assertEquals(4, array[3]); + public void testSameType() { + assertThrows(IllegalArgumentException.class, () -> ArrayUtils.isSameType(null, null)); + assertThrows(IllegalArgumentException.class, () -> ArrayUtils.isSameType(null, new Object[0])); + assertThrows(IllegalArgumentException.class, () -> ArrayUtils.isSameType(new Object[0], null)); + + assertTrue(ArrayUtils.isSameType(new Object[0], new Object[0])); + assertFalse(ArrayUtils.isSameType(new String[0], new Object[0])); + assertTrue(ArrayUtils.isSameType(new String[0][0], new String[0][0])); + assertFalse(ArrayUtils.isSameType(new String[0], new String[0][0])); + assertFalse(ArrayUtils.isSameType(new String[0][0], new String[0])); } @Test - public void testShiftFloat() { - final float[] array = new float[]{1, 2, 3, 4}; - ArrayUtils.shift(array, 1); - assertEquals(4, array[0]); - assertEquals(1, array[1]); - assertEquals(2, array[2]); - assertEquals(3, array[3]); - ArrayUtils.shift(array, -1); + public void testShiftAllByte() { + final byte[] array = new byte[]{1, 2, 3, 4}; + ArrayUtils.shift(array, 4); assertEquals(1, array[0]); assertEquals(2, array[1]); assertEquals(3, array[2]); assertEquals(4, array[3]); - ArrayUtils.shift(array, 5); - assertEquals(4, array[0]); - assertEquals(1, array[1]); - assertEquals(2, array[2]); - assertEquals(3, array[3]); - ArrayUtils.shift(array, -3); - assertEquals(3, array[0]); - assertEquals(4, array[1]); - assertEquals(1, array[2]); - assertEquals(2, array[3]); - } - - @Test - public void testShiftRangeFloat() { - final float[] array = new float[]{1, 2, 3, 4, 5}; - ArrayUtils.shift(array, 1, 3, 1); - assertEquals(1, array[0]); - assertEquals(3, array[1]); - assertEquals(2, array[2]); - assertEquals(4, array[3]); - assertEquals(5, array[4]); - ArrayUtils.shift(array, 1, 4, 2); + ArrayUtils.shift(array, -4); assertEquals(1, array[0]); assertEquals(2, array[1]); - assertEquals(4, array[2]); - assertEquals(3, array[3]); - assertEquals(5, array[4]); + assertEquals(3, array[2]); + assertEquals(4, array[3]); } @Test - public void testShiftRangeNoElemFloat() { - final float[] array = new float[]{1, 2, 3, 4}; - ArrayUtils.shift(array, 1, 1, 1); + public void testShiftAllChar() { + final char[] array = new char[]{1, 2, 3, 4}; + ArrayUtils.shift(array, 4); + assertEquals(1, array[0]); + assertEquals(2, array[1]); + assertEquals(3, array[2]); + assertEquals(4, array[3]); + ArrayUtils.shift(array, -4); assertEquals(1, array[0]); assertEquals(2, array[1]); assertEquals(3, array[2]); @@ -3896,23 +4301,8 @@ public void testShiftRangeNoElemFloat() { } @Test - public void testShiftRangeNullFloat() { - final float[] array = null; - ArrayUtils.shift(array, 1, 1, 1); - assertNull(array); - } - - @Test - public void testShiftNullFloat() { - final float[] array = null; - - ArrayUtils.shift(array, 1); - assertNull(array); - } - - @Test - public void testShiftAllFloat() { - final float[] array = new float[]{1, 2, 3, 4}; + public void testShiftAllDouble() { + final double[] array = new double[]{1, 2, 3, 4}; ArrayUtils.shift(array, 4); assertEquals(1, array[0]); assertEquals(2, array[1]); @@ -3926,66 +4316,44 @@ public void testShiftAllFloat() { } @Test - public void testShiftShort() { - short[] array = new short[]{1, 2, 3, 4}; - ArrayUtils.shift(array, 1); - assertEquals(4, array[0]); - assertEquals(1, array[1]); - assertEquals(2, array[2]); - assertEquals(3, array[3]); - ArrayUtils.shift(array, -1); + public void testShiftAllFloat() { + final float[] array = new float[]{1, 2, 3, 4}; + ArrayUtils.shift(array, 4); + assertEquals(1, array[0]); + assertEquals(2, array[1]); + assertEquals(3, array[2]); + assertEquals(4, array[3]); + ArrayUtils.shift(array, -4); assertEquals(1, array[0]); assertEquals(2, array[1]); assertEquals(3, array[2]); assertEquals(4, array[3]); - ArrayUtils.shift(array, 5); - assertEquals(4, array[0]); - assertEquals(1, array[1]); - assertEquals(2, array[2]); - assertEquals(3, array[3]); - ArrayUtils.shift(array, -3); - assertEquals(3, array[0]); - assertEquals(4, array[1]); - assertEquals(1, array[2]); - assertEquals(2, array[3]); - array = new short[]{1, 2, 3, 4, 5}; - ArrayUtils.shift(array, 2); - assertEquals(4, array[0]); - assertEquals(5, array[1]); - assertEquals(1, array[2]); - assertEquals(2, array[3]); - assertEquals(3, array[4]); - } - - @Test - public void testShiftNullShort() { - final short[] array = null; - - ArrayUtils.shift(array, 1); - assertNull(array); } @Test - public void testShiftRangeShort() { - final short[] array = new short[]{1, 2, 3, 4, 5}; - ArrayUtils.shift(array, 1, 3, 1); + public void testShiftAllInt() { + final int[] array = new int[]{1, 2, 3, 4}; + ArrayUtils.shift(array, 4); assertEquals(1, array[0]); - assertEquals(3, array[1]); - assertEquals(2, array[2]); + assertEquals(2, array[1]); + assertEquals(3, array[2]); assertEquals(4, array[3]); - assertEquals(5, array[4]); - ArrayUtils.shift(array, 1, 4, 2); + ArrayUtils.shift(array, -4); assertEquals(1, array[0]); assertEquals(2, array[1]); - assertEquals(4, array[2]); - assertEquals(3, array[3]); - assertEquals(5, array[4]); + assertEquals(3, array[2]); + assertEquals(4, array[3]); } @Test - public void testShiftRangeNoElemShort() { - final short[] array = new short[]{1, 2, 3, 4}; - ArrayUtils.shift(array, 1, 1, 1); + public void testShiftAllLong() { + final long[] array = new long[]{1, 2, 3, 4}; + ArrayUtils.shift(array, 4); + assertEquals(1, array[0]); + assertEquals(2, array[1]); + assertEquals(3, array[2]); + assertEquals(4, array[3]); + ArrayUtils.shift(array, -4); assertEquals(1, array[0]); assertEquals(2, array[1]); assertEquals(3, array[2]); @@ -3993,11 +4361,18 @@ public void testShiftRangeNoElemShort() { } @Test - public void testShiftRangeNullShort() { - final short[] array = null; - - ArrayUtils.shift(array, 1, 1, 1); - assertNull(array); + public void testShiftAllObject() { + final String[] array = new String[]{"1", "2", "3", "4"}; + ArrayUtils.shift(array, 4); + assertEquals("1", array[0]); + assertEquals("2", array[1]); + assertEquals("3", array[2]); + assertEquals("4", array[3]); + ArrayUtils.shift(array, -4); + assertEquals("1", array[0]); + assertEquals("2", array[1]); + assertEquals("3", array[2]); + assertEquals("4", array[3]); } @Test @@ -4015,6 +4390,35 @@ public void testShiftAllShort() { assertEquals(4, array[3]); } + @Test + public void testShiftBoolean() { + final boolean[] array = new boolean[]{true, true, false, false}; + + ArrayUtils.shift(array, 1); + assertFalse(array[0]); + assertTrue(array[1]); + assertTrue(array[2]); + assertFalse(array[3]); + + ArrayUtils.shift(array, -1); + assertTrue(array[0]); + assertTrue(array[1]); + assertFalse(array[2]); + assertFalse(array[3]); + + ArrayUtils.shift(array, 5); + assertFalse(array[0]); + assertTrue(array[1]); + assertTrue(array[2]); + assertFalse(array[3]); + + ArrayUtils.shift(array, -3); + assertFalse(array[0]); + assertFalse(array[1]); + assertTrue(array[2]); + assertTrue(array[3]); + } + @Test public void testShiftByte() { final byte[] array = new byte[]{1, 2, 3, 4}; @@ -4040,55 +4444,6 @@ public void testShiftByte() { assertEquals(2, array[3]); } - @Test - public void testShiftRangeByte() { - final byte[] array = new byte[]{1, 2, 3, 4, 5}; - ArrayUtils.shift(array, 1, 3, 1); - assertEquals(1, array[0]); - assertEquals(3, array[1]); - assertEquals(2, array[2]); - assertEquals(4, array[3]); - assertEquals(5, array[4]); - ArrayUtils.shift(array, 1, 4, 2); - assertEquals(1, array[0]); - assertEquals(2, array[1]); - assertEquals(4, array[2]); - assertEquals(3, array[3]); - assertEquals(5, array[4]); - } - - @Test - public void testShiftRangeNoElemByte() { - final byte[] array = new byte[]{1, 2, 3, 4}; - ArrayUtils.shift(array, 1, 1, 1); - assertEquals(1, array[0]); - assertEquals(2, array[1]); - assertEquals(3, array[2]); - assertEquals(4, array[3]); - } - - @Test - public void testShiftRangeNullByte() { - final byte[] array = null; - ArrayUtils.shift(array, 1, 1, 1); - assertNull(array); - } - - @Test - public void testShiftAllByte() { - final byte[] array = new byte[]{1, 2, 3, 4}; - ArrayUtils.shift(array, 4); - assertEquals(1, array[0]); - assertEquals(2, array[1]); - assertEquals(3, array[2]); - assertEquals(4, array[3]); - ArrayUtils.shift(array, -4); - assertEquals(1, array[0]); - assertEquals(2, array[1]); - assertEquals(3, array[2]); - assertEquals(4, array[3]); - } - @Test public void testShiftChar() { final char[] array = new char[]{1, 2, 3, 4}; @@ -4114,58 +4469,10 @@ public void testShiftChar() { assertEquals(2, array[3]); } - @Test - public void testShiftRangeChar() { - final char[] array = new char[]{1, 2, 3, 4, 5}; - ArrayUtils.shift(array, 1, 3, 1); - assertEquals(1, array[0]); - assertEquals(3, array[1]); - assertEquals(2, array[2]); - assertEquals(4, array[3]); - assertEquals(5, array[4]); - ArrayUtils.shift(array, 1, 4, 2); - assertEquals(1, array[0]); - assertEquals(2, array[1]); - assertEquals(4, array[2]); - assertEquals(3, array[3]); - assertEquals(5, array[4]); - } - - @Test - public void testShiftRangeNoElemChar() { - final char[] array = new char[]{1, 2, 3, 4}; - ArrayUtils.shift(array, 1, 1, 1); - assertEquals(1, array[0]); - assertEquals(2, array[1]); - assertEquals(3, array[2]); - assertEquals(4, array[3]); - } - - @Test - public void testShiftRangeNullChar() { - final char[] array = null; - ArrayUtils.shift(array, 1, 1, 1); - assertNull(array); - } - - @Test - public void testShiftAllChar() { - final char[] array = new char[]{1, 2, 3, 4}; - ArrayUtils.shift(array, 4); - assertEquals(1, array[0]); - assertEquals(2, array[1]); - assertEquals(3, array[2]); - assertEquals(4, array[3]); - ArrayUtils.shift(array, -4); - assertEquals(1, array[0]); - assertEquals(2, array[1]); - assertEquals(3, array[2]); - assertEquals(4, array[3]); - } - - @Test - public void testShiftLong() { - final long[] array = new long[]{1, 2, 3, 4}; + //----------------------------------------------------------------------- + @Test + public void testShiftDouble() { + final double[] array = new double[]{1, 2, 3, 4}; ArrayUtils.shift(array, 1); assertEquals(4, array[0]); assertEquals(1, array[1]); @@ -4188,66 +4495,60 @@ public void testShiftLong() { assertEquals(2, array[3]); } + @Test - public void testShiftRangeLong() { - final long[] array = new long[]{1, 2, 3, 4, 5}; - ArrayUtils.shift(array, 1, 3, 1); - assertEquals(1, array[0]); - assertEquals(3, array[1]); + public void testShiftFloat() { + final float[] array = new float[]{1, 2, 3, 4}; + ArrayUtils.shift(array, 1); + assertEquals(4, array[0]); + assertEquals(1, array[1]); assertEquals(2, array[2]); - assertEquals(4, array[3]); - assertEquals(5, array[4]); - ArrayUtils.shift(array, 1, 4, 2); - assertEquals(1, array[0]); - assertEquals(2, array[1]); - assertEquals(4, array[2]); assertEquals(3, array[3]); - assertEquals(5, array[4]); - } - - @Test - public void testShiftRangeNoElemLong() { - final long[] array = new long[]{1, 2, 3, 4}; - ArrayUtils.shift(array, 1, 1, 1); + ArrayUtils.shift(array, -1); assertEquals(1, array[0]); assertEquals(2, array[1]); assertEquals(3, array[2]); assertEquals(4, array[3]); + ArrayUtils.shift(array, 5); + assertEquals(4, array[0]); + assertEquals(1, array[1]); + assertEquals(2, array[2]); + assertEquals(3, array[3]); + ArrayUtils.shift(array, -3); + assertEquals(3, array[0]); + assertEquals(4, array[1]); + assertEquals(1, array[2]); + assertEquals(2, array[3]); } @Test - public void testShiftRangeNullLong() { - final long[] array = null; - ArrayUtils.shift(array, 1, 1, 1); - assertNull(array); - } - - @Test - public void testShiftNullLong() { - final long[] array = null; - + public void testShiftInt() { + final int[] array = new int[]{1, 2, 3, 4}; ArrayUtils.shift(array, 1); - assertNull(array); - } - - @Test - public void testShiftAllLong() { - final long[] array = new long[]{1, 2, 3, 4}; - ArrayUtils.shift(array, 4); - assertEquals(1, array[0]); - assertEquals(2, array[1]); - assertEquals(3, array[2]); - assertEquals(4, array[3]); - ArrayUtils.shift(array, -4); + assertEquals(4, array[0]); + assertEquals(1, array[1]); + assertEquals(2, array[2]); + assertEquals(3, array[3]); + ArrayUtils.shift(array, -1); assertEquals(1, array[0]); assertEquals(2, array[1]); assertEquals(3, array[2]); assertEquals(4, array[3]); + ArrayUtils.shift(array, 5); + assertEquals(4, array[0]); + assertEquals(1, array[1]); + assertEquals(2, array[2]); + assertEquals(3, array[3]); + ArrayUtils.shift(array, -3); + assertEquals(3, array[0]); + assertEquals(4, array[1]); + assertEquals(1, array[2]); + assertEquals(2, array[3]); } @Test - public void testShiftInt() { - final int[] array = new int[]{1, 2, 3, 4}; + public void testShiftLong() { + final long[] array = new long[]{1, 2, 3, 4}; ArrayUtils.shift(array, 1); assertEquals(4, array[0]); assertEquals(1, array[1]); @@ -4271,60 +4572,59 @@ public void testShiftInt() { } @Test - public void testShiftNullInt() { - final int[] array = null; + public void testShiftNullBoolean() { + final boolean[] array = null; ArrayUtils.shift(array, 1); assertNull(array); } @Test - public void testShiftRangeInt() { - final int[] array = new int[]{1, 2, 3, 4, 5}; - ArrayUtils.shift(array, 1, 3, 1); - assertEquals(1, array[0]); - assertEquals(3, array[1]); - assertEquals(2, array[2]); - assertEquals(4, array[3]); - assertEquals(5, array[4]); - ArrayUtils.shift(array, 1, 4, 2); - assertEquals(1, array[0]); - assertEquals(2, array[1]); - assertEquals(4, array[2]); - assertEquals(3, array[3]); - assertEquals(5, array[4]); + public void testShiftNullDouble() { + final double[] array = null; + + ArrayUtils.shift(array, 1); + assertNull(array); } @Test - public void testShiftRangeNoElemInt() { - final int[] array = new int[]{1, 2, 3, 4}; - ArrayUtils.shift(array, 1, 1, 1); - assertEquals(1, array[0]); - assertEquals(2, array[1]); - assertEquals(3, array[2]); - assertEquals(4, array[3]); + public void testShiftNullFloat() { + final float[] array = null; + + ArrayUtils.shift(array, 1); + assertNull(array); } @Test - public void testShiftRangeNullInt() { + public void testShiftNullInt() { final int[] array = null; - ArrayUtils.shift(array, 1, 1, 1); + + ArrayUtils.shift(array, 1); assertNull(array); } @Test - public void testShiftAllInt() { - final int[] array = new int[]{1, 2, 3, 4}; - ArrayUtils.shift(array, 4); - assertEquals(1, array[0]); - assertEquals(2, array[1]); - assertEquals(3, array[2]); - assertEquals(4, array[3]); - ArrayUtils.shift(array, -4); - assertEquals(1, array[0]); - assertEquals(2, array[1]); - assertEquals(3, array[2]); - assertEquals(4, array[3]); + public void testShiftNullLong() { + final long[] array = null; + + ArrayUtils.shift(array, 1); + assertNull(array); + } + + @Test + public void testShiftNullObject() { + final String[] array = null; + + ArrayUtils.shift(array, 1); + assertNull(array); + } + + @Test + public void testShiftNullShort() { + final short[] array = null; + + ArrayUtils.shift(array, 1); + assertNull(array); } @Test @@ -4353,2158 +4653,1858 @@ public void testShiftObject() { } @Test - public void testShiftNullObject() { - final String[] array = null; + public void testShiftRangeByte() { + final byte[] array = new byte[]{1, 2, 3, 4, 5}; + ArrayUtils.shift(array, 1, 3, 1); + assertEquals(1, array[0]); + assertEquals(3, array[1]); + assertEquals(2, array[2]); + assertEquals(4, array[3]); + assertEquals(5, array[4]); + ArrayUtils.shift(array, 1, 4, 2); + assertEquals(1, array[0]); + assertEquals(2, array[1]); + assertEquals(4, array[2]); + assertEquals(3, array[3]); + assertEquals(5, array[4]); + } - ArrayUtils.shift(array, 1); - assertNull(array); + @Test + public void testShiftRangeChar() { + final char[] array = new char[]{1, 2, 3, 4, 5}; + ArrayUtils.shift(array, 1, 3, 1); + assertEquals(1, array[0]); + assertEquals(3, array[1]); + assertEquals(2, array[2]); + assertEquals(4, array[3]); + assertEquals(5, array[4]); + ArrayUtils.shift(array, 1, 4, 2); + assertEquals(1, array[0]); + assertEquals(2, array[1]); + assertEquals(4, array[2]); + assertEquals(3, array[3]); + assertEquals(5, array[4]); } @Test - public void testShiftRangeObject() { - final String[] array = new String[]{"1", "2", "3", "4", "5"}; + public void testShiftRangeDouble() { + final double[] array = new double[]{1, 2, 3, 4, 5}; ArrayUtils.shift(array, 1, 3, 1); - assertEquals("1", array[0]); - assertEquals("3", array[1]); - assertEquals("2", array[2]); - assertEquals("4", array[3]); - assertEquals("5", array[4]); + assertEquals(1, array[0]); + assertEquals(3, array[1]); + assertEquals(2, array[2]); + assertEquals(4, array[3]); + assertEquals(5, array[4]); ArrayUtils.shift(array, 1, 4, 2); - assertEquals("1", array[0]); - assertEquals("2", array[1]); - assertEquals("4", array[2]); - assertEquals("3", array[3]); - assertEquals("5", array[4]); + assertEquals(1, array[0]); + assertEquals(2, array[1]); + assertEquals(4, array[2]); + assertEquals(3, array[3]); + assertEquals(5, array[4]); + } + + @Test + public void testShiftRangeFloat() { + final float[] array = new float[]{1, 2, 3, 4, 5}; + ArrayUtils.shift(array, 1, 3, 1); + assertEquals(1, array[0]); + assertEquals(3, array[1]); + assertEquals(2, array[2]); + assertEquals(4, array[3]); + assertEquals(5, array[4]); + ArrayUtils.shift(array, 1, 4, 2); + assertEquals(1, array[0]); + assertEquals(2, array[1]); + assertEquals(4, array[2]); + assertEquals(3, array[3]); + assertEquals(5, array[4]); + } + + @Test + public void testShiftRangeInt() { + final int[] array = new int[]{1, 2, 3, 4, 5}; + ArrayUtils.shift(array, 1, 3, 1); + assertEquals(1, array[0]); + assertEquals(3, array[1]); + assertEquals(2, array[2]); + assertEquals(4, array[3]); + assertEquals(5, array[4]); + ArrayUtils.shift(array, 1, 4, 2); + assertEquals(1, array[0]); + assertEquals(2, array[1]); + assertEquals(4, array[2]); + assertEquals(3, array[3]); + assertEquals(5, array[4]); + } + + @Test + public void testShiftRangeLong() { + final long[] array = new long[]{1, 2, 3, 4, 5}; + ArrayUtils.shift(array, 1, 3, 1); + assertEquals(1, array[0]); + assertEquals(3, array[1]); + assertEquals(2, array[2]); + assertEquals(4, array[3]); + assertEquals(5, array[4]); + ArrayUtils.shift(array, 1, 4, 2); + assertEquals(1, array[0]); + assertEquals(2, array[1]); + assertEquals(4, array[2]); + assertEquals(3, array[3]); + assertEquals(5, array[4]); } @Test - public void testShiftRangeNoElemObject() { - final String[] array = new String[]{"1", "2", "3", "4"}; + public void testShiftRangeNoElemByte() { + final byte[] array = new byte[]{1, 2, 3, 4}; ArrayUtils.shift(array, 1, 1, 1); - assertEquals("1", array[0]); - assertEquals("2", array[1]); - assertEquals("3", array[2]); - assertEquals("4", array[3]); + assertEquals(1, array[0]); + assertEquals(2, array[1]); + assertEquals(3, array[2]); + assertEquals(4, array[3]); } @Test - public void testShiftRangeNullObject() { - final String[] array = null; + public void testShiftRangeNoElemChar() { + final char[] array = new char[]{1, 2, 3, 4}; ArrayUtils.shift(array, 1, 1, 1); - assertNull(array); + assertEquals(1, array[0]); + assertEquals(2, array[1]); + assertEquals(3, array[2]); + assertEquals(4, array[3]); } @Test - public void testShiftAllObject() { - final String[] array = new String[]{"1", "2", "3", "4"}; - ArrayUtils.shift(array, 4); - assertEquals("1", array[0]); - assertEquals("2", array[1]); - assertEquals("3", array[2]); - assertEquals("4", array[3]); - ArrayUtils.shift(array, -4); - assertEquals("1", array[0]); - assertEquals("2", array[1]); - assertEquals("3", array[2]); - assertEquals("4", array[3]); + public void testShiftRangeNoElemDouble() { + final double[] array = new double[]{1, 2, 3, 4}; + ArrayUtils.shift(array, 1, 1, 1); + assertEquals(1, array[0]); + assertEquals(2, array[1]); + assertEquals(3, array[2]); + assertEquals(4, array[3]); } @Test - public void testShiftBoolean() { - final boolean[] array = new boolean[]{true, true, false, false}; - - ArrayUtils.shift(array, 1); - assertFalse(array[0]); - assertTrue(array[1]); - assertTrue(array[2]); - assertFalse(array[3]); - - ArrayUtils.shift(array, -1); - assertTrue(array[0]); - assertTrue(array[1]); - assertFalse(array[2]); - assertFalse(array[3]); - - ArrayUtils.shift(array, 5); - assertFalse(array[0]); - assertTrue(array[1]); - assertTrue(array[2]); - assertFalse(array[3]); - - ArrayUtils.shift(array, -3); - assertFalse(array[0]); - assertFalse(array[1]); - assertTrue(array[2]); - assertTrue(array[3]); + public void testShiftRangeNoElemFloat() { + final float[] array = new float[]{1, 2, 3, 4}; + ArrayUtils.shift(array, 1, 1, 1); + assertEquals(1, array[0]); + assertEquals(2, array[1]); + assertEquals(3, array[2]); + assertEquals(4, array[3]); } @Test - public void testShiftNullBoolean() { - final boolean[] array = null; - - ArrayUtils.shift(array, 1); - assertNull(array); + public void testShiftRangeNoElemInt() { + final int[] array = new int[]{1, 2, 3, 4}; + ArrayUtils.shift(array, 1, 1, 1); + assertEquals(1, array[0]); + assertEquals(2, array[1]); + assertEquals(3, array[2]); + assertEquals(4, array[3]); } - //----------------------------------------------------------------------- @Test - public void testIndexOf() { - final Object[] array = new Object[]{"0", "1", "2", "3", null, "0"}; - assertEquals(-1, ArrayUtils.indexOf(null, null)); - assertEquals(-1, ArrayUtils.indexOf(null, "0")); - assertEquals(-1, ArrayUtils.indexOf(new Object[0], "0")); - assertEquals(0, ArrayUtils.indexOf(array, "0")); - assertEquals(1, ArrayUtils.indexOf(array, "1")); - assertEquals(2, ArrayUtils.indexOf(array, "2")); - assertEquals(3, ArrayUtils.indexOf(array, "3")); - assertEquals(4, ArrayUtils.indexOf(array, null)); - assertEquals(-1, ArrayUtils.indexOf(array, "notInArray")); + public void testShiftRangeNoElemLong() { + final long[] array = new long[]{1, 2, 3, 4}; + ArrayUtils.shift(array, 1, 1, 1); + assertEquals(1, array[0]); + assertEquals(2, array[1]); + assertEquals(3, array[2]); + assertEquals(4, array[3]); } @Test - public void testIndexOfWithStartIndex() { - final Object[] array = new Object[]{"0", "1", "2", "3", null, "0"}; - assertEquals(-1, ArrayUtils.indexOf(null, null, 2)); - assertEquals(-1, ArrayUtils.indexOf(new Object[0], "0", 0)); - assertEquals(-1, ArrayUtils.indexOf(null, "0", 2)); - assertEquals(5, ArrayUtils.indexOf(array, "0", 2)); - assertEquals(-1, ArrayUtils.indexOf(array, "1", 2)); - assertEquals(2, ArrayUtils.indexOf(array, "2", 2)); - assertEquals(3, ArrayUtils.indexOf(array, "3", 2)); - assertEquals(4, ArrayUtils.indexOf(array, null, 2)); - assertEquals(-1, ArrayUtils.indexOf(array, "notInArray", 2)); - - assertEquals(4, ArrayUtils.indexOf(array, null, -1)); - assertEquals(-1, ArrayUtils.indexOf(array, null, 8)); - assertEquals(-1, ArrayUtils.indexOf(array, "0", 8)); + public void testShiftRangeNoElemObject() { + final String[] array = new String[]{"1", "2", "3", "4"}; + ArrayUtils.shift(array, 1, 1, 1); + assertEquals("1", array[0]); + assertEquals("2", array[1]); + assertEquals("3", array[2]); + assertEquals("4", array[3]); } @Test - public void testIndexesOf() { - final Object[] array = new Object[]{"0", "1", "2", "3", null, "0"}; - final BitSet emptySet = new BitSet(); - final BitSet testSet = new BitSet(); - assertEquals(emptySet, ArrayUtils.indexesOf((Object[]) null, null)); - assertEquals(emptySet, ArrayUtils.indexesOf(new Object[0], "0")); - testSet.set(5); - testSet.set(0); - assertEquals(testSet, ArrayUtils.indexesOf(array, "0")); - testSet.clear(); - testSet.set(2); - assertEquals(testSet, ArrayUtils.indexesOf(array, "2")); - testSet.clear(); - testSet.set(3); - assertEquals(testSet, ArrayUtils.indexesOf(array, "3")); - testSet.clear(); - testSet.set(4); - assertEquals(testSet, ArrayUtils.indexesOf(array, null)); - assertEquals(emptySet, ArrayUtils.indexesOf(array, "notInArray")); + public void testShiftRangeNoElemShort() { + final short[] array = new short[]{1, 2, 3, 4}; + ArrayUtils.shift(array, 1, 1, 1); + assertEquals(1, array[0]); + assertEquals(2, array[1]); + assertEquals(3, array[2]); + assertEquals(4, array[3]); } @Test - public void testIndexesOfWithStartIndex() { - final Object[] array = new Object[]{"0", "1", "2", "3", "2", "3", "1", null, "0"}; - final BitSet emptySet = new BitSet(); - final BitSet testSet = new BitSet(); - assertEquals(emptySet, ArrayUtils.indexesOf(null, null, 2)); - assertEquals(emptySet, ArrayUtils.indexesOf(new Object[0], "0", 0)); - assertEquals(emptySet, ArrayUtils.indexesOf(null, "0", 2)); - testSet.set(8); - assertEquals(testSet, ArrayUtils.indexesOf(array, "0", 8)); - testSet.set(0); - assertEquals(testSet, ArrayUtils.indexesOf(array, "0", 0)); - testSet.clear(); - testSet.set(6); - testSet.set(1); - assertEquals(testSet, ArrayUtils.indexesOf(array, "1", 0)); - assertEquals(emptySet, ArrayUtils.indexesOf(array, "1", 9)); - testSet.clear(); - testSet.set(4); - assertEquals(testSet, ArrayUtils.indexesOf(array, "2", 3)); - testSet.set(2); - assertEquals(testSet, ArrayUtils.indexesOf(array, "2", 0)); - testSet.clear(); - testSet.set(3); - testSet.set(5); - assertEquals(testSet, ArrayUtils.indexesOf(array, "3", 0)); - testSet.clear(); - testSet.set(7); - assertEquals(testSet, ArrayUtils.indexesOf(array, null, 0)); - + public void testShiftRangeNullByte() { + final byte[] array = null; + ArrayUtils.shift(array, 1, 1, 1); + assertNull(array); } - @Test - public void testLastIndexOf() { - final Object[] array = new Object[]{"0", "1", "2", "3", null, "0"}; - assertEquals(-1, ArrayUtils.lastIndexOf(null, null)); - assertEquals(-1, ArrayUtils.lastIndexOf(null, "0")); - assertEquals(5, ArrayUtils.lastIndexOf(array, "0")); - assertEquals(1, ArrayUtils.lastIndexOf(array, "1")); - assertEquals(2, ArrayUtils.lastIndexOf(array, "2")); - assertEquals(3, ArrayUtils.lastIndexOf(array, "3")); - assertEquals(4, ArrayUtils.lastIndexOf(array, null)); - assertEquals(-1, ArrayUtils.lastIndexOf(array, "notInArray")); + public void testShiftRangeNullChar() { + final char[] array = null; + ArrayUtils.shift(array, 1, 1, 1); + assertNull(array); } @Test - public void testLastIndexOfWithStartIndex() { - final Object[] array = new Object[]{"0", "1", "2", "3", null, "0"}; - assertEquals(-1, ArrayUtils.lastIndexOf(null, null, 2)); - assertEquals(-1, ArrayUtils.lastIndexOf(null, "0", 2)); - assertEquals(0, ArrayUtils.lastIndexOf(array, "0", 2)); - assertEquals(1, ArrayUtils.lastIndexOf(array, "1", 2)); - assertEquals(2, ArrayUtils.lastIndexOf(array, "2", 2)); - assertEquals(-1, ArrayUtils.lastIndexOf(array, "3", 2)); - assertEquals(-1, ArrayUtils.lastIndexOf(array, "3", -1)); - assertEquals(4, ArrayUtils.lastIndexOf(array, null, 5)); - assertEquals(-1, ArrayUtils.lastIndexOf(array, null, 2)); - assertEquals(-1, ArrayUtils.lastIndexOf(array, "notInArray", 5)); - - assertEquals(-1, ArrayUtils.lastIndexOf(array, null, -1)); - assertEquals(5, ArrayUtils.lastIndexOf(array, "0", 88)); + public void testShiftRangeNullDouble() { + final double[] array = null; + ArrayUtils.shift(array, 1, 1, 1); + assertNull(array); } @Test - public void testContains() { - final Object[] array = new Object[]{"0", "1", "2", "3", null, "0"}; - assertFalse(ArrayUtils.contains(null, null)); - assertFalse(ArrayUtils.contains(null, "1")); - assertTrue(ArrayUtils.contains(array, "0")); - assertTrue(ArrayUtils.contains(array, "1")); - assertTrue(ArrayUtils.contains(array, "2")); - assertTrue(ArrayUtils.contains(array, "3")); - assertTrue(ArrayUtils.contains(array, null)); - assertFalse(ArrayUtils.contains(array, "notInArray")); + public void testShiftRangeNullFloat() { + final float[] array = null; + ArrayUtils.shift(array, 1, 1, 1); + assertNull(array); } @Test - public void testContains_LANG_1261() { - class LANG1261ParentObject { - @Override - public boolean equals(final Object o) { - return true; - } - } - class LANG1261ChildObject extends LANG1261ParentObject { - } - - final Object[] array = new LANG1261ChildObject[]{new LANG1261ChildObject()}; - - assertTrue(ArrayUtils.contains(array, new LANG1261ParentObject())); + public void testShiftRangeNullInt() { + final int[] array = null; + ArrayUtils.shift(array, 1, 1, 1); + assertNull(array); } - //----------------------------------------------------------------------- @Test - public void testIndexOfLong() { - long[] array = null; - assertEquals(-1, ArrayUtils.indexOf(array, 0)); - array = new long[]{0, 1, 2, 3, 0}; - assertEquals(0, ArrayUtils.indexOf(array, 0)); - assertEquals(1, ArrayUtils.indexOf(array, 1)); - assertEquals(2, ArrayUtils.indexOf(array, 2)); - assertEquals(3, ArrayUtils.indexOf(array, 3)); - assertEquals(-1, ArrayUtils.indexOf(array, 99)); + public void testShiftRangeNullLong() { + final long[] array = null; + ArrayUtils.shift(array, 1, 1, 1); + assertNull(array); } @Test - public void testIndexOfLongWithStartIndex() { - long[] array = null; - assertEquals(-1, ArrayUtils.indexOf(array, 0, 2)); - array = new long[]{0, 1, 2, 3, 0}; - assertEquals(4, ArrayUtils.indexOf(array, 0, 2)); - assertEquals(-1, ArrayUtils.indexOf(array, 1, 2)); - assertEquals(2, ArrayUtils.indexOf(array, 2, 2)); - assertEquals(3, ArrayUtils.indexOf(array, 3, 2)); - assertEquals(3, ArrayUtils.indexOf(array, 3, -1)); - assertEquals(-1, ArrayUtils.indexOf(array, 99, 0)); - assertEquals(-1, ArrayUtils.indexOf(array, 0, 6)); + public void testShiftRangeNullObject() { + final String[] array = null; + ArrayUtils.shift(array, 1, 1, 1); + assertNull(array); } @Test - public void testIndexesOfLong() { - final long[] array = new long[]{0, 1, 2, 3}; - final BitSet emptySet = new BitSet(); - final BitSet testSet = new BitSet(); - assertEquals(emptySet, ArrayUtils.indexesOf((long[]) null, 0)); - assertEquals(emptySet, ArrayUtils.indexesOf(array, 4)); - testSet.set(0); - assertEquals(testSet, ArrayUtils.indexesOf(array, 0)); - testSet.clear(); - testSet.set(1); - assertEquals(testSet, ArrayUtils.indexesOf(array, 1)); - testSet.clear(); - testSet.set(2); - assertEquals(testSet, ArrayUtils.indexesOf(array, 2)); - testSet.clear(); - testSet.set(3); - assertEquals(testSet, ArrayUtils.indexesOf(array, 3)); - } + public void testShiftRangeNullShort() { + final short[] array = null; - @Test - public void testIndexesOfLongWithStartIndex() { - final long[] array = new long[]{0, 1, 2, 3, 2, 1, 0, 1}; - final BitSet emptySet = new BitSet(); - final BitSet testSet = new BitSet(); - assertEquals(emptySet, ArrayUtils.indexesOf((long[]) null, 0, 0)); - assertEquals(emptySet, ArrayUtils.indexesOf(array, 4, 0)); - testSet.set(6); - assertEquals(testSet, ArrayUtils.indexesOf(array, 0, 1)); - testSet.set(0); - assertEquals(testSet, ArrayUtils.indexesOf(array, 0, 0)); - testSet.clear(); - testSet.set(1); - testSet.set(5); - testSet.set(7); - assertEquals(testSet, ArrayUtils.indexesOf(array, 1, 0)); - testSet.clear(); - testSet.set(2); - testSet.set(4); - assertEquals(testSet, ArrayUtils.indexesOf(array, 2, 0)); - testSet.clear(); - testSet.set(3); - assertEquals(testSet, ArrayUtils.indexesOf(array, 3, 0)); - assertEquals(emptySet, ArrayUtils.indexesOf(array, 3, 8)); + ArrayUtils.shift(array, 1, 1, 1); + assertNull(array); } @Test - public void testLastIndexOfLong() { - long[] array = null; - assertEquals(-1, ArrayUtils.lastIndexOf(array, 0)); - array = new long[]{0, 1, 2, 3, 0}; - assertEquals(4, ArrayUtils.lastIndexOf(array, 0)); - assertEquals(1, ArrayUtils.lastIndexOf(array, 1)); - assertEquals(2, ArrayUtils.lastIndexOf(array, 2)); - assertEquals(3, ArrayUtils.lastIndexOf(array, 3)); - assertEquals(-1, ArrayUtils.lastIndexOf(array, 99)); + public void testShiftRangeObject() { + final String[] array = new String[]{"1", "2", "3", "4", "5"}; + ArrayUtils.shift(array, 1, 3, 1); + assertEquals("1", array[0]); + assertEquals("3", array[1]); + assertEquals("2", array[2]); + assertEquals("4", array[3]); + assertEquals("5", array[4]); + ArrayUtils.shift(array, 1, 4, 2); + assertEquals("1", array[0]); + assertEquals("2", array[1]); + assertEquals("4", array[2]); + assertEquals("3", array[3]); + assertEquals("5", array[4]); } @Test - public void testLastIndexOfLongWithStartIndex() { - long[] array = null; - assertEquals(-1, ArrayUtils.lastIndexOf(array, 0, 2)); - array = new long[]{0, 1, 2, 3, 0}; - assertEquals(0, ArrayUtils.lastIndexOf(array, 0, 2)); - assertEquals(1, ArrayUtils.lastIndexOf(array, 1, 2)); - assertEquals(2, ArrayUtils.lastIndexOf(array, 2, 2)); - assertEquals(-1, ArrayUtils.lastIndexOf(array, 3, 2)); - assertEquals(-1, ArrayUtils.lastIndexOf(array, 3, -1)); - assertEquals(-1, ArrayUtils.lastIndexOf(array, 99, 4)); - assertEquals(4, ArrayUtils.lastIndexOf(array, 0, 88)); + public void testShiftRangeShort() { + final short[] array = new short[]{1, 2, 3, 4, 5}; + ArrayUtils.shift(array, 1, 3, 1); + assertEquals(1, array[0]); + assertEquals(3, array[1]); + assertEquals(2, array[2]); + assertEquals(4, array[3]); + assertEquals(5, array[4]); + ArrayUtils.shift(array, 1, 4, 2); + assertEquals(1, array[0]); + assertEquals(2, array[1]); + assertEquals(4, array[2]); + assertEquals(3, array[3]); + assertEquals(5, array[4]); } @Test - public void testContainsLong() { - long[] array = null; - assertFalse(ArrayUtils.contains(array, 1)); - array = new long[]{0, 1, 2, 3, 0}; - assertTrue(ArrayUtils.contains(array, 0)); - assertTrue(ArrayUtils.contains(array, 1)); - assertTrue(ArrayUtils.contains(array, 2)); - assertTrue(ArrayUtils.contains(array, 3)); - assertFalse(ArrayUtils.contains(array, 99)); + public void testShiftShort() { + short[] array = new short[]{1, 2, 3, 4}; + ArrayUtils.shift(array, 1); + assertEquals(4, array[0]); + assertEquals(1, array[1]); + assertEquals(2, array[2]); + assertEquals(3, array[3]); + ArrayUtils.shift(array, -1); + assertEquals(1, array[0]); + assertEquals(2, array[1]); + assertEquals(3, array[2]); + assertEquals(4, array[3]); + ArrayUtils.shift(array, 5); + assertEquals(4, array[0]); + assertEquals(1, array[1]); + assertEquals(2, array[2]); + assertEquals(3, array[3]); + ArrayUtils.shift(array, -3); + assertEquals(3, array[0]); + assertEquals(4, array[1]); + assertEquals(1, array[2]); + assertEquals(2, array[3]); + array = new short[]{1, 2, 3, 4, 5}; + ArrayUtils.shift(array, 2); + assertEquals(4, array[0]); + assertEquals(5, array[1]); + assertEquals(1, array[2]); + assertEquals(2, array[3]); + assertEquals(3, array[4]); } - //----------------------------------------------------------------------- @Test - public void testIndexOfInt() { - int[] array = null; - assertEquals(-1, ArrayUtils.indexOf(array, 0)); - array = new int[]{0, 1, 2, 3, 0}; - assertEquals(0, ArrayUtils.indexOf(array, 0)); - assertEquals(1, ArrayUtils.indexOf(array, 1)); - assertEquals(2, ArrayUtils.indexOf(array, 2)); - assertEquals(3, ArrayUtils.indexOf(array, 3)); - assertEquals(-1, ArrayUtils.indexOf(array, 99)); + public void testShuffle() { + final String[] array1 = new String[]{"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"}; + final String[] array2 = ArrayUtils.clone(array1); + + ArrayUtils.shuffle(array1, new Random(SEED)); + assertFalse(Arrays.equals(array1, array2)); + for (final String element : array2) { + assertTrue(ArrayUtils.contains(array1, element), "Element " + element + " not found"); + } } @Test - public void testIndexOfIntWithStartIndex() { - int[] array = null; - assertEquals(-1, ArrayUtils.indexOf(array, 0, 2)); - array = new int[]{0, 1, 2, 3, 0}; - assertEquals(4, ArrayUtils.indexOf(array, 0, 2)); - assertEquals(-1, ArrayUtils.indexOf(array, 1, 2)); - assertEquals(2, ArrayUtils.indexOf(array, 2, 2)); - assertEquals(3, ArrayUtils.indexOf(array, 3, 2)); - assertEquals(3, ArrayUtils.indexOf(array, 3, -1)); - assertEquals(-1, ArrayUtils.indexOf(array, 99, 0)); - assertEquals(-1, ArrayUtils.indexOf(array, 0, 6)); + public void testShuffleBoolean() { + final boolean[] array1 = new boolean[]{true, false, true, true, false, false, true, false, false, true}; + final boolean[] array2 = ArrayUtils.clone(array1); + + ArrayUtils.shuffle(array1, new Random(SEED)); + assertFalse(Arrays.equals(array1, array2)); + assertEquals(5, ArrayUtils.removeAllOccurrences(array1, true).length); } @Test - public void textIndexesOfInt() { - int[] array = null; - final BitSet emptySet = new BitSet(); - final BitSet testSet = new BitSet(); - assertEquals(emptySet, ArrayUtils.indexesOf(array, 0)); - array = new int[]{0, 1, 2, 3, 0}; - testSet.set(0); - testSet.set(4); - assertEquals(testSet, ArrayUtils.indexesOf(array, 0)); - testSet.clear(); - testSet.set(1); - assertEquals(testSet, ArrayUtils.indexesOf(array, 1)); - testSet.clear(); - testSet.set(2); - assertEquals(testSet, ArrayUtils.indexesOf(array, 2)); - testSet.clear(); - testSet.set(3); - assertEquals(testSet, ArrayUtils.indexesOf(array, 3)); - assertEquals(emptySet, ArrayUtils.indexesOf(array, 99)); + public void testShuffleByte() { + final byte[] array1 = new byte[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; + final byte[] array2 = ArrayUtils.clone(array1); + + ArrayUtils.shuffle(array1, new Random(SEED)); + assertFalse(Arrays.equals(array1, array2)); + for (final byte element : array2) { + assertTrue(ArrayUtils.contains(array1, element), "Element " + element + " not found"); + } } @Test - public void testIndexesOfIntWithStartIndex() { - int[] array = null; - final BitSet emptySet = new BitSet(); - final BitSet testSet = new BitSet(); - assertEquals(emptySet, ArrayUtils.indexesOf(array, 0, 2)); - array = new int[]{0, 1, 2, 3, 0}; - testSet.set(4); - assertEquals(testSet, ArrayUtils.indexesOf(array, 0, 2)); - testSet.set(0); - assertEquals(testSet, ArrayUtils.indexesOf(array, 0, 0)); - testSet.clear(); - testSet.set(1); - assertEquals(testSet, ArrayUtils.indexesOf(array, 1, 1)); - testSet.clear(); - testSet.set(2); - assertEquals(testSet, ArrayUtils.indexesOf(array, 2, 0)); - testSet.clear(); - testSet.set(3); - assertEquals(testSet, ArrayUtils.indexesOf(array, 3, 0)); - assertEquals(testSet, ArrayUtils.indexesOf(array, 3, -1)); - assertEquals(emptySet, ArrayUtils.indexesOf(array, 99, 0)); + public void testShuffleChar() { + final char[] array1 = new char[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; + final char[] array2 = ArrayUtils.clone(array1); + + ArrayUtils.shuffle(array1, new Random(SEED)); + assertFalse(Arrays.equals(array1, array2)); + for (final char element : array2) { + assertTrue(ArrayUtils.contains(array1, element), "Element " + element + " not found"); + } } @Test - public void testLastIndexOfInt() { - int[] array = null; - assertEquals(-1, ArrayUtils.lastIndexOf(array, 0)); - array = new int[]{0, 1, 2, 3, 0}; - assertEquals(4, ArrayUtils.lastIndexOf(array, 0)); - assertEquals(1, ArrayUtils.lastIndexOf(array, 1)); - assertEquals(2, ArrayUtils.lastIndexOf(array, 2)); - assertEquals(3, ArrayUtils.lastIndexOf(array, 3)); - assertEquals(-1, ArrayUtils.lastIndexOf(array, 99)); + public void testShuffleDouble() { + final double[] array1 = new double[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; + final double[] array2 = ArrayUtils.clone(array1); + + ArrayUtils.shuffle(array1, new Random(SEED)); + assertFalse(Arrays.equals(array1, array2)); + for (final double element : array2) { + assertTrue(ArrayUtils.contains(array1, element), "Element " + element + " not found"); + } } @Test - public void testLastIndexOfIntWithStartIndex() { - int[] array = null; - assertEquals(-1, ArrayUtils.lastIndexOf(array, 0, 2)); - array = new int[]{0, 1, 2, 3, 0}; - assertEquals(0, ArrayUtils.lastIndexOf(array, 0, 2)); - assertEquals(1, ArrayUtils.lastIndexOf(array, 1, 2)); - assertEquals(2, ArrayUtils.lastIndexOf(array, 2, 2)); - assertEquals(-1, ArrayUtils.lastIndexOf(array, 3, 2)); - assertEquals(-1, ArrayUtils.lastIndexOf(array, 3, -1)); - assertEquals(-1, ArrayUtils.lastIndexOf(array, 99)); - assertEquals(4, ArrayUtils.lastIndexOf(array, 0, 88)); + public void testShuffleFloat() { + final float[] array1 = new float[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; + final float[] array2 = ArrayUtils.clone(array1); + + ArrayUtils.shuffle(array1, new Random(SEED)); + assertFalse(Arrays.equals(array1, array2)); + for (final float element : array2) { + assertTrue(ArrayUtils.contains(array1, element), "Element " + element + " not found"); + } } @Test - public void testContainsInt() { - int[] array = null; - assertFalse(ArrayUtils.contains(array, 1)); - array = new int[]{0, 1, 2, 3, 0}; - assertTrue(ArrayUtils.contains(array, 0)); - assertTrue(ArrayUtils.contains(array, 1)); - assertTrue(ArrayUtils.contains(array, 2)); - assertTrue(ArrayUtils.contains(array, 3)); - assertFalse(ArrayUtils.contains(array, 99)); + public void testShuffleInt() { + final int[] array1 = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; + final int[] array2 = ArrayUtils.clone(array1); + + ArrayUtils.shuffle(array1, new Random(SEED)); + assertFalse(Arrays.equals(array1, array2)); + for (final int element : array2) { + assertTrue(ArrayUtils.contains(array1, element), "Element " + element + " not found"); + } } - //----------------------------------------------------------------------- @Test - public void testIndexOfShort() { - short[] array = null; - assertEquals(-1, ArrayUtils.indexOf(array, (short) 0)); - array = new short[]{0, 1, 2, 3, 0}; - assertEquals(0, ArrayUtils.indexOf(array, (short) 0)); - assertEquals(1, ArrayUtils.indexOf(array, (short) 1)); - assertEquals(2, ArrayUtils.indexOf(array, (short) 2)); - assertEquals(3, ArrayUtils.indexOf(array, (short) 3)); - assertEquals(-1, ArrayUtils.indexOf(array, (short) 99)); + public void testShuffleLong() { + final long[] array1 = new long[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; + final long[] array2 = ArrayUtils.clone(array1); + + ArrayUtils.shuffle(array1, new Random(SEED)); + assertFalse(Arrays.equals(array1, array2)); + for (final long element : array2) { + assertTrue(ArrayUtils.contains(array1, element), "Element " + element + " not found"); + } } @Test - public void testIndexOfShortWithStartIndex() { - short[] array = null; - assertEquals(-1, ArrayUtils.indexOf(array, (short) 0, 2)); - array = new short[]{0, 1, 2, 3, 0}; - assertEquals(4, ArrayUtils.indexOf(array, (short) 0, 2)); - assertEquals(-1, ArrayUtils.indexOf(array, (short) 1, 2)); - assertEquals(2, ArrayUtils.indexOf(array, (short) 2, 2)); - assertEquals(3, ArrayUtils.indexOf(array, (short) 3, 2)); - assertEquals(3, ArrayUtils.indexOf(array, (short) 3, -1)); - assertEquals(-1, ArrayUtils.indexOf(array, (short) 99, 0)); - assertEquals(-1, ArrayUtils.indexOf(array, (short) 0, 6)); + public void testShuffleShort() { + final short[] array1 = new short[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; + final short[] array2 = ArrayUtils.clone(array1); + + ArrayUtils.shuffle(array1, new Random(SEED)); + assertFalse(Arrays.equals(array1, array2)); + for (final short element : array2) { + assertTrue(ArrayUtils.contains(array1, element), "Element " + element + " not found"); + } } @Test - public void testIndexesOfShort() { - short[] array = null; - final BitSet emptySet = new BitSet(); - final BitSet testSet = new BitSet(); - assertEquals(emptySet, ArrayUtils.indexesOf(array, (short) 0)); - array = new short[]{0, 1, 2, 3, 0}; - testSet.set(0); - testSet.set(4); - assertEquals(testSet, ArrayUtils.indexesOf(array, (short) 0)); - testSet.clear(); - testSet.set(1); - assertEquals(testSet, ArrayUtils.indexesOf(array, (short) 1)); - testSet.clear(); - testSet.set(2); - assertEquals(testSet, ArrayUtils.indexesOf(array, (short) 2)); - testSet.clear(); - testSet.set(3); - assertEquals(testSet, ArrayUtils.indexesOf(array, (short) 3)); - assertEquals(emptySet, ArrayUtils.indexesOf(array, (short) 99)); + public void testSubarrayBoolean() { + final boolean[] nullArray = null; + final boolean[] array = {true, true, false, true, false, true}; + final boolean[] leftSubarray = {true, true, false, true}; + final boolean[] midSubarray = {true, false, true, false}; + final boolean[] rightSubarray = {false, true, false, true}; + + assertTrue(ArrayUtils.isEquals(leftSubarray, ArrayUtils.subarray(array, 0, 4)), "0 start, mid end"); + assertTrue(ArrayUtils.isEquals(array, ArrayUtils.subarray(array, 0, array.length)), "0 start, length end"); + assertTrue(ArrayUtils.isEquals(midSubarray, ArrayUtils.subarray(array, 1, 5)), "mid start, mid end"); + assertTrue(ArrayUtils.isEquals(rightSubarray, ArrayUtils.subarray(array, 2, array.length)), + "mid start, length end"); + + assertNull(ArrayUtils.subarray(nullArray, 0, 3), "null input"); + assertEquals(ArrayUtils.EMPTY_BOOLEAN_ARRAY, ArrayUtils.subarray(ArrayUtils.EMPTY_BOOLEAN_ARRAY, 1, 2), + "empty array"); + assertEquals(ArrayUtils.EMPTY_BOOLEAN_ARRAY, ArrayUtils.subarray(array, 4, 2), "start > end"); + assertEquals(ArrayUtils.EMPTY_BOOLEAN_ARRAY, ArrayUtils.subarray(array, 3, 3), "start == end"); + assertTrue(ArrayUtils.isEquals(leftSubarray, ArrayUtils.subarray(array, -2, 4)), + "start undershoot, normal end"); + assertEquals(ArrayUtils.EMPTY_BOOLEAN_ARRAY, ArrayUtils.subarray(array, 33, 4), "start overshoot, any end"); + assertTrue(ArrayUtils.isEquals(rightSubarray, ArrayUtils.subarray(array, 2, 33)), + "normal start, end overshoot"); + assertTrue(ArrayUtils.isEquals(array, ArrayUtils.subarray(array, -2, 12)), "start undershoot, end overshoot"); + + // empty-return tests + + assertSame(ArrayUtils.EMPTY_BOOLEAN_ARRAY, ArrayUtils.subarray(ArrayUtils.EMPTY_BOOLEAN_ARRAY, 1, 2), + "empty array, object test"); + assertSame(ArrayUtils.EMPTY_BOOLEAN_ARRAY, ArrayUtils.subarray(array, 4, 1), "start > end, object test"); + assertSame(ArrayUtils.EMPTY_BOOLEAN_ARRAY, ArrayUtils.subarray(array, 3, 3), "start == end, object test"); + assertSame(ArrayUtils.EMPTY_BOOLEAN_ARRAY, ArrayUtils.subarray(array, 8733, 4), + "start overshoot, any end, object test"); + + // array type tests + + assertSame(boolean.class, ArrayUtils.subarray(array, 2, 4).getClass().getComponentType(), "boolean type"); } @Test - public void testIndexesOfShortWithStartIndex() { - short[] array = null; - final BitSet emptySet = new BitSet(); - final BitSet testSet = new BitSet(); - assertEquals(emptySet, ArrayUtils.indexesOf(array, (short) 0, 2)); - array = new short[]{0, 1, 2, 3, 0}; - testSet.set(4); - assertEquals(testSet, ArrayUtils.indexesOf(array, (short) 0, 2)); - testSet.set(0); - assertEquals(testSet, ArrayUtils.indexesOf(array, (short) 0, 0)); - testSet.clear(); - testSet.set(1); - assertEquals(testSet, ArrayUtils.indexesOf(array, (short) 1, 1)); - testSet.clear(); - testSet.set(2); - assertEquals(testSet, ArrayUtils.indexesOf(array, (short) 2, 0)); - testSet.clear(); - testSet.set(3); - assertEquals(testSet, ArrayUtils.indexesOf(array, (short) 3, 0)); - assertEquals(testSet, ArrayUtils.indexesOf(array, (short) 3, -1)); - assertEquals(emptySet, ArrayUtils.indexesOf(array, (short) 99, 0)); + public void testSubarrayByte() { + final byte[] nullArray = null; + final byte[] array = {10, 11, 12, 13, 14, 15}; + final byte[] leftSubarray = {10, 11, 12, 13}; + final byte[] midSubarray = {11, 12, 13, 14}; + final byte[] rightSubarray = {12, 13, 14, 15}; + + assertTrue(ArrayUtils.isEquals(leftSubarray, ArrayUtils.subarray(array, 0, 4)), "0 start, mid end"); + assertTrue(ArrayUtils.isEquals(array, ArrayUtils.subarray(array, 0, array.length)), "0 start, length end"); + assertTrue(ArrayUtils.isEquals(midSubarray, ArrayUtils.subarray(array, 1, 5)), "mid start, mid end"); + assertTrue(ArrayUtils.isEquals(rightSubarray, ArrayUtils.subarray(array, 2, array.length)), + "mid start, length end"); + + assertNull(ArrayUtils.subarray(nullArray, 0, 3), "null input"); + assertEquals(ArrayUtils.EMPTY_BYTE_ARRAY, ArrayUtils.subarray(ArrayUtils.EMPTY_BYTE_ARRAY, 1, 2), + "empty array"); + assertEquals(ArrayUtils.EMPTY_BYTE_ARRAY, ArrayUtils.subarray(array, 4, 2), "start > end"); + assertEquals(ArrayUtils.EMPTY_BYTE_ARRAY, ArrayUtils.subarray(array, 3, 3), "start == end"); + assertTrue(ArrayUtils.isEquals(leftSubarray, ArrayUtils.subarray(array, -2, 4)), + "start undershoot, normal end"); + assertEquals(ArrayUtils.EMPTY_BYTE_ARRAY, ArrayUtils.subarray(array, 33, 4), "start overshoot, any end"); + assertTrue(ArrayUtils.isEquals(rightSubarray, ArrayUtils.subarray(array, 2, 33)), + "normal start, end overshoot"); + assertTrue(ArrayUtils.isEquals(array, ArrayUtils.subarray(array, -2, 12)), "start undershoot, end overshoot"); + + // empty-return tests + + assertSame(ArrayUtils.EMPTY_BYTE_ARRAY, ArrayUtils.subarray(ArrayUtils.EMPTY_BYTE_ARRAY, 1, 2), + "empty array, object test"); + assertSame(ArrayUtils.EMPTY_BYTE_ARRAY, ArrayUtils.subarray(array, 4, 1), "start > end, object test"); + assertSame(ArrayUtils.EMPTY_BYTE_ARRAY, ArrayUtils.subarray(array, 3, 3), "start == end, object test"); + assertSame(ArrayUtils.EMPTY_BYTE_ARRAY, ArrayUtils.subarray(array, 8733, 4), + "start overshoot, any end, object test"); + + // array type tests + + assertSame(byte.class, ArrayUtils.subarray(array, 2, 4).getClass().getComponentType(), "byte type"); } @Test - public void testLastIndexOfShort() { - short[] array = null; - assertEquals(-1, ArrayUtils.lastIndexOf(array, (short) 0)); - array = new short[]{0, 1, 2, 3, 0}; - assertEquals(4, ArrayUtils.lastIndexOf(array, (short) 0)); - assertEquals(1, ArrayUtils.lastIndexOf(array, (short) 1)); - assertEquals(2, ArrayUtils.lastIndexOf(array, (short) 2)); - assertEquals(3, ArrayUtils.lastIndexOf(array, (short) 3)); - assertEquals(-1, ArrayUtils.lastIndexOf(array, (short) 99)); + public void testSubarrayDouble() { + final double[] nullArray = null; + final double[] array = {10.123, 11.234, 12.345, 13.456, 14.567, 15.678}; + final double[] leftSubarray = {10.123, 11.234, 12.345, 13.456}; + final double[] midSubarray = {11.234, 12.345, 13.456, 14.567}; + final double[] rightSubarray = {12.345, 13.456, 14.567, 15.678}; + + assertTrue(ArrayUtils.isEquals(leftSubarray, ArrayUtils.subarray(array, 0, 4)), "0 start, mid end"); + assertTrue(ArrayUtils.isEquals(array, ArrayUtils.subarray(array, 0, array.length)), "0 start, length end"); + assertTrue(ArrayUtils.isEquals(midSubarray, ArrayUtils.subarray(array, 1, 5)), "mid start, mid end"); + assertTrue(ArrayUtils.isEquals(rightSubarray, ArrayUtils.subarray(array, 2, array.length)), + "mid start, length end"); + + assertNull(ArrayUtils.subarray(nullArray, 0, 3), "null input"); + assertEquals(ArrayUtils.EMPTY_DOUBLE_ARRAY, ArrayUtils.subarray(ArrayUtils.EMPTY_DOUBLE_ARRAY, 1, 2), + "empty array"); + assertEquals(ArrayUtils.EMPTY_DOUBLE_ARRAY, ArrayUtils.subarray(array, 4, 2), "start > end"); + assertEquals(ArrayUtils.EMPTY_DOUBLE_ARRAY, ArrayUtils.subarray(array, 3, 3), "start == end"); + assertTrue(ArrayUtils.isEquals(leftSubarray, ArrayUtils.subarray(array, -2, 4)), + "start undershoot, normal end"); + assertEquals(ArrayUtils.EMPTY_DOUBLE_ARRAY, ArrayUtils.subarray(array, 33, 4), "start overshoot, any end"); + assertTrue(ArrayUtils.isEquals(rightSubarray, ArrayUtils.subarray(array, 2, 33)), + "normal start, end overshoot"); + assertTrue(ArrayUtils.isEquals(array, ArrayUtils.subarray(array, -2, 12)), "start undershoot, end overshoot"); + + // empty-return tests + + assertSame(ArrayUtils.EMPTY_DOUBLE_ARRAY, ArrayUtils.subarray(ArrayUtils.EMPTY_DOUBLE_ARRAY, 1, 2), + "empty array, object test"); + assertSame(ArrayUtils.EMPTY_DOUBLE_ARRAY, ArrayUtils.subarray(array, 4, 1), "start > end, object test"); + assertSame(ArrayUtils.EMPTY_DOUBLE_ARRAY, ArrayUtils.subarray(array, 3, 3), "start == end, object test"); + assertSame(ArrayUtils.EMPTY_DOUBLE_ARRAY, ArrayUtils.subarray(array, 8733, 4), + "start overshoot, any end, object test"); + + // array type tests + + assertSame(double.class, ArrayUtils.subarray(array, 2, 4).getClass().getComponentType(), "double type"); } @Test - public void testLastIndexOfShortWithStartIndex() { - short[] array = null; - assertEquals(-1, ArrayUtils.lastIndexOf(array, (short) 0, 2)); - array = new short[]{0, 1, 2, 3, 0}; - assertEquals(0, ArrayUtils.lastIndexOf(array, (short) 0, 2)); - assertEquals(1, ArrayUtils.lastIndexOf(array, (short) 1, 2)); - assertEquals(2, ArrayUtils.lastIndexOf(array, (short) 2, 2)); - assertEquals(-1, ArrayUtils.lastIndexOf(array, (short) 3, 2)); - assertEquals(-1, ArrayUtils.lastIndexOf(array, (short) 3, -1)); - assertEquals(-1, ArrayUtils.lastIndexOf(array, (short) 99)); - assertEquals(4, ArrayUtils.lastIndexOf(array, (short) 0, 88)); - } + public void testSubarrayFloat() { + final float[] nullArray = null; + final float[] array = {10, 11, 12, 13, 14, 15}; + final float[] leftSubarray = {10, 11, 12, 13}; + final float[] midSubarray = {11, 12, 13, 14}; + final float[] rightSubarray = {12, 13, 14, 15}; - @Test - public void testContainsShort() { - short[] array = null; - assertFalse(ArrayUtils.contains(array, (short) 1)); - array = new short[]{0, 1, 2, 3, 0}; - assertTrue(ArrayUtils.contains(array, (short) 0)); - assertTrue(ArrayUtils.contains(array, (short) 1)); - assertTrue(ArrayUtils.contains(array, (short) 2)); - assertTrue(ArrayUtils.contains(array, (short) 3)); - assertFalse(ArrayUtils.contains(array, (short) 99)); - } + assertTrue(ArrayUtils.isEquals(leftSubarray, ArrayUtils.subarray(array, 0, 4)), "0 start, mid end"); + assertTrue(ArrayUtils.isEquals(array, ArrayUtils.subarray(array, 0, array.length)), "0 start, length end"); + assertTrue(ArrayUtils.isEquals(midSubarray, ArrayUtils.subarray(array, 1, 5)), "mid start, mid end"); + assertTrue(ArrayUtils.isEquals(rightSubarray, ArrayUtils.subarray(array, 2, array.length)), + "mid start, length end"); - //----------------------------------------------------------------------- - @Test - public void testIndexOfChar() { - char[] array = null; - assertEquals(-1, ArrayUtils.indexOf(array, 'a')); - array = new char[]{'a', 'b', 'c', 'd', 'a'}; - assertEquals(0, ArrayUtils.indexOf(array, 'a')); - assertEquals(1, ArrayUtils.indexOf(array, 'b')); - assertEquals(2, ArrayUtils.indexOf(array, 'c')); - assertEquals(3, ArrayUtils.indexOf(array, 'd')); - assertEquals(-1, ArrayUtils.indexOf(array, 'e')); - } + assertNull(ArrayUtils.subarray(nullArray, 0, 3), "null input"); + assertEquals(ArrayUtils.EMPTY_FLOAT_ARRAY, ArrayUtils.subarray(ArrayUtils.EMPTY_FLOAT_ARRAY, 1, 2), + "empty array"); + assertEquals(ArrayUtils.EMPTY_FLOAT_ARRAY, ArrayUtils.subarray(array, 4, 2), "start > end"); + assertEquals(ArrayUtils.EMPTY_FLOAT_ARRAY, ArrayUtils.subarray(array, 3, 3), "start == end"); + assertTrue(ArrayUtils.isEquals(leftSubarray, ArrayUtils.subarray(array, -2, 4)), + "start undershoot, normal end"); + assertEquals(ArrayUtils.EMPTY_FLOAT_ARRAY, ArrayUtils.subarray(array, 33, 4), "start overshoot, any end"); + assertTrue(ArrayUtils.isEquals(rightSubarray, ArrayUtils.subarray(array, 2, 33)), + "normal start, end overshoot"); + assertTrue(ArrayUtils.isEquals(array, ArrayUtils.subarray(array, -2, 12)), "start undershoot, end overshoot"); - @Test - public void testIndexOfCharWithStartIndex() { - char[] array = null; - assertEquals(-1, ArrayUtils.indexOf(array, 'a', 2)); - array = new char[]{'a', 'b', 'c', 'd', 'a'}; - assertEquals(4, ArrayUtils.indexOf(array, 'a', 2)); - assertEquals(-1, ArrayUtils.indexOf(array, 'b', 2)); - assertEquals(2, ArrayUtils.indexOf(array, 'c', 2)); - assertEquals(3, ArrayUtils.indexOf(array, 'd', 2)); - assertEquals(3, ArrayUtils.indexOf(array, 'd', -1)); - assertEquals(-1, ArrayUtils.indexOf(array, 'e', 0)); - assertEquals(-1, ArrayUtils.indexOf(array, 'a', 6)); - } + // empty-return tests - @Test - public void testIndexesOfChar() { - char[] array = null; - final BitSet emptySet = new BitSet(); - final BitSet testSet = new BitSet(); - assertEquals(emptySet, ArrayUtils.indexesOf(array, 'a')); - array = new char[]{'a', 'b', 'c', 'd', 'a'}; - testSet.set(0); - testSet.set(4); - assertEquals(testSet, ArrayUtils.indexesOf(array, 'a')); - testSet.clear(); - testSet.set(1); - assertEquals(testSet, ArrayUtils.indexesOf(array, 'b')); - testSet.clear(); - testSet.set(2); - assertEquals(testSet, ArrayUtils.indexesOf(array, 'c')); - testSet.clear(); - testSet.set(3); - assertEquals(testSet, ArrayUtils.indexesOf(array, 'd')); - assertEquals(emptySet, ArrayUtils.indexesOf(array, 'e')); - } + assertSame(ArrayUtils.EMPTY_FLOAT_ARRAY, ArrayUtils.subarray(ArrayUtils.EMPTY_FLOAT_ARRAY, 1, 2), + "empty array, object test"); + assertSame(ArrayUtils.EMPTY_FLOAT_ARRAY, ArrayUtils.subarray(array, 4, 1), "start > end, object test"); + assertSame(ArrayUtils.EMPTY_FLOAT_ARRAY, ArrayUtils.subarray(array, 3, 3), "start == end, object test"); + assertSame(ArrayUtils.EMPTY_FLOAT_ARRAY, ArrayUtils.subarray(array, 8733, 4), + "start overshoot, any end, object test"); - @Test - public void testIndexesOfCharWithStartIndex() { - char[] array = null; - final BitSet emptySet = new BitSet(); - final BitSet testSet = new BitSet(); - assertEquals(emptySet, ArrayUtils.indexesOf(array, 'a', 0)); - array = new char[]{'a', 'b', 'c', 'd', 'a'}; - testSet.set(4); - assertEquals(testSet, ArrayUtils.indexesOf(array, 'a', 2)); - testSet.set(0); - assertEquals(testSet, ArrayUtils.indexesOf(array, 'a', 0)); - assertEquals(testSet, ArrayUtils.indexesOf(array, 'a', -1)); - testSet.clear(); - testSet.set(1); - assertEquals(testSet, ArrayUtils.indexesOf(array, 'b', 1)); - testSet.clear(); - testSet.set(2); - assertEquals(testSet, ArrayUtils.indexesOf(array, 'c', 0)); - testSet.clear(); - testSet.set(3); - assertEquals(testSet, ArrayUtils.indexesOf(array, 'd', 0)); - assertEquals(emptySet, ArrayUtils.indexesOf(array, 'd', 5)); - assertEquals(emptySet, ArrayUtils.indexesOf(array, 'e', 0)); - } + // array type tests - @Test - public void testLastIndexOfChar() { - char[] array = null; - assertEquals(-1, ArrayUtils.lastIndexOf(array, 'a')); - array = new char[]{'a', 'b', 'c', 'd', 'a'}; - assertEquals(4, ArrayUtils.lastIndexOf(array, 'a')); - assertEquals(1, ArrayUtils.lastIndexOf(array, 'b')); - assertEquals(2, ArrayUtils.lastIndexOf(array, 'c')); - assertEquals(3, ArrayUtils.lastIndexOf(array, 'd')); - assertEquals(-1, ArrayUtils.lastIndexOf(array, 'e')); + assertSame(float.class, ArrayUtils.subarray(array, 2, 4).getClass().getComponentType(), "float type"); } @Test - public void testLastIndexOfCharWithStartIndex() { - char[] array = null; - assertEquals(-1, ArrayUtils.lastIndexOf(array, 'a', 2)); - array = new char[]{'a', 'b', 'c', 'd', 'a'}; - assertEquals(0, ArrayUtils.lastIndexOf(array, 'a', 2)); - assertEquals(1, ArrayUtils.lastIndexOf(array, 'b', 2)); - assertEquals(2, ArrayUtils.lastIndexOf(array, 'c', 2)); - assertEquals(-1, ArrayUtils.lastIndexOf(array, 'd', 2)); - assertEquals(-1, ArrayUtils.lastIndexOf(array, 'd', -1)); - assertEquals(-1, ArrayUtils.lastIndexOf(array, 'e')); - assertEquals(4, ArrayUtils.lastIndexOf(array, 'a', 88)); - } + public void testSubarrayInt() { + final int[] nullArray = null; + final int[] array = {10, 11, 12, 13, 14, 15}; + final int[] leftSubarray = {10, 11, 12, 13}; + final int[] midSubarray = {11, 12, 13, 14}; + final int[] rightSubarray = {12, 13, 14, 15}; - @Test - public void testContainsChar() { - char[] array = null; - assertFalse(ArrayUtils.contains(array, 'b')); - array = new char[]{'a', 'b', 'c', 'd', 'a'}; - assertTrue(ArrayUtils.contains(array, 'a')); - assertTrue(ArrayUtils.contains(array, 'b')); - assertTrue(ArrayUtils.contains(array, 'c')); - assertTrue(ArrayUtils.contains(array, 'd')); - assertFalse(ArrayUtils.contains(array, 'e')); - } - //----------------------------------------------------------------------- - @Test - public void testIndexOfByte() { - byte[] array = null; - assertEquals(-1, ArrayUtils.indexOf(array, (byte) 0)); - array = new byte[]{0, 1, 2, 3, 0}; - assertEquals(0, ArrayUtils.indexOf(array, (byte) 0)); - assertEquals(1, ArrayUtils.indexOf(array, (byte) 1)); - assertEquals(2, ArrayUtils.indexOf(array, (byte) 2)); - assertEquals(3, ArrayUtils.indexOf(array, (byte) 3)); - assertEquals(-1, ArrayUtils.indexOf(array, (byte) 99)); - } + assertTrue(ArrayUtils.isEquals(leftSubarray, ArrayUtils.subarray(array, 0, 4)), "0 start, mid end"); - @Test - public void testIndexOfByteWithStartIndex() { - byte[] array = null; - assertEquals(-1, ArrayUtils.indexOf(array, (byte) 0, 2)); - array = new byte[]{0, 1, 2, 3, 0}; - assertEquals(4, ArrayUtils.indexOf(array, (byte) 0, 2)); - assertEquals(-1, ArrayUtils.indexOf(array, (byte) 1, 2)); - assertEquals(2, ArrayUtils.indexOf(array, (byte) 2, 2)); - assertEquals(3, ArrayUtils.indexOf(array, (byte) 3, 2)); - assertEquals(3, ArrayUtils.indexOf(array, (byte) 3, -1)); - assertEquals(-1, ArrayUtils.indexOf(array, (byte) 99, 0)); - assertEquals(-1, ArrayUtils.indexOf(array, (byte) 0, 6)); - } + assertTrue(ArrayUtils.isEquals(array, ArrayUtils.subarray(array, 0, array.length)), "0 start, length end"); - @Test - public void testIndexesOfByte() { - byte[] array = null; - final BitSet emptySet = new BitSet(); - final BitSet testSet = new BitSet(); - assertEquals(emptySet, ArrayUtils.indexesOf(array, (byte) 0)); - array = new byte[]{0, 1, 2, 3, 0}; - testSet.set(0); - testSet.set(4); - assertEquals(testSet, ArrayUtils.indexesOf(array, (byte) 0)); - testSet.clear(); - testSet.set(1); - assertEquals(testSet, ArrayUtils.indexesOf(array, (byte) 1)); - testSet.clear(); - testSet.set(2); - assertEquals(testSet, ArrayUtils.indexesOf(array, (byte) 2)); - testSet.clear(); - testSet.set(3); - assertEquals(testSet, ArrayUtils.indexesOf(array, (byte) 3)); - assertEquals(emptySet, ArrayUtils.indexesOf(array, (byte) 99)); - } + assertTrue(ArrayUtils.isEquals(midSubarray, ArrayUtils.subarray(array, 1, 5)), "mid start, mid end"); - @Test - public void testIndexesOfByteWithStartIndex() { - byte[] array = null; - final BitSet emptySet = new BitSet(); - final BitSet testSet = new BitSet(); - assertEquals(emptySet, ArrayUtils.indexesOf(array, (byte) 0, 2)); - array = new byte[]{0, 1, 2, 3, 0}; - testSet.set(4); - assertEquals(testSet, ArrayUtils.indexesOf(array, (byte) 0, 2)); - testSet.set(0); - assertEquals(testSet, ArrayUtils.indexesOf(array, (byte) 0, 0)); - testSet.clear(); - testSet.set(1); - assertEquals(testSet, ArrayUtils.indexesOf(array, (byte) 1, 1)); - testSet.clear(); - testSet.set(2); - assertEquals(testSet, ArrayUtils.indexesOf(array, (byte) 2, 0)); - testSet.clear(); - testSet.set(3); - assertEquals(testSet, ArrayUtils.indexesOf(array, (byte) 3, 0)); - assertEquals(testSet, ArrayUtils.indexesOf(array, (byte) 3, -1)); - assertEquals(emptySet, ArrayUtils.indexesOf(array, (byte) 99, 0)); - } + assertTrue(ArrayUtils.isEquals(rightSubarray, ArrayUtils.subarray(array, 2, array.length)), + "mid start, length end"); + + + assertNull(ArrayUtils.subarray(nullArray, 0, 3), "null input"); + + assertEquals(ArrayUtils.EMPTY_INT_ARRAY, ArrayUtils.subarray(ArrayUtils.EMPTY_INT_ARRAY, 1, 2), "empty array"); + + assertEquals(ArrayUtils.EMPTY_INT_ARRAY, ArrayUtils.subarray(array, 4, 2), "start > end"); + + assertEquals(ArrayUtils.EMPTY_INT_ARRAY, ArrayUtils.subarray(array, 3, 3), "start == end"); + + assertTrue(ArrayUtils.isEquals(leftSubarray, ArrayUtils.subarray(array, -2, 4)), + "start undershoot, normal end"); + + assertEquals(ArrayUtils.EMPTY_INT_ARRAY, ArrayUtils.subarray(array, 33, 4), "start overshoot, any end"); + + assertTrue(ArrayUtils.isEquals(rightSubarray, ArrayUtils.subarray(array, 2, 33)), + "normal start, end overshoot"); + + assertTrue(ArrayUtils.isEquals(array, ArrayUtils.subarray(array, -2, 12)), "start undershoot, end overshoot"); - @Test - public void testLastIndexOfByte() { - byte[] array = null; - assertEquals(-1, ArrayUtils.lastIndexOf(array, (byte) 0)); - array = new byte[]{0, 1, 2, 3, 0}; - assertEquals(4, ArrayUtils.lastIndexOf(array, (byte) 0)); - assertEquals(1, ArrayUtils.lastIndexOf(array, (byte) 1)); - assertEquals(2, ArrayUtils.lastIndexOf(array, (byte) 2)); - assertEquals(3, ArrayUtils.lastIndexOf(array, (byte) 3)); - assertEquals(-1, ArrayUtils.lastIndexOf(array, (byte) 99)); - } + // empty-return tests - @Test - public void testLastIndexOfByteWithStartIndex() { - byte[] array = null; - assertEquals(-1, ArrayUtils.lastIndexOf(array, (byte) 0, 2)); - array = new byte[]{0, 1, 2, 3, 0}; - assertEquals(0, ArrayUtils.lastIndexOf(array, (byte) 0, 2)); - assertEquals(1, ArrayUtils.lastIndexOf(array, (byte) 1, 2)); - assertEquals(2, ArrayUtils.lastIndexOf(array, (byte) 2, 2)); - assertEquals(-1, ArrayUtils.lastIndexOf(array, (byte) 3, 2)); - assertEquals(-1, ArrayUtils.lastIndexOf(array, (byte) 3, -1)); - assertEquals(-1, ArrayUtils.lastIndexOf(array, (byte) 99)); - assertEquals(4, ArrayUtils.lastIndexOf(array, (byte) 0, 88)); - } + assertSame(ArrayUtils.EMPTY_INT_ARRAY, ArrayUtils.subarray(ArrayUtils.EMPTY_INT_ARRAY, 1, 2), + "empty array, object test"); - @Test - public void testContainsByte() { - byte[] array = null; - assertFalse(ArrayUtils.contains(array, (byte) 1)); - array = new byte[]{0, 1, 2, 3, 0}; - assertTrue(ArrayUtils.contains(array, (byte) 0)); - assertTrue(ArrayUtils.contains(array, (byte) 1)); - assertTrue(ArrayUtils.contains(array, (byte) 2)); - assertTrue(ArrayUtils.contains(array, (byte) 3)); - assertFalse(ArrayUtils.contains(array, (byte) 99)); - } + assertSame(ArrayUtils.EMPTY_INT_ARRAY, ArrayUtils.subarray(array, 4, 1), "start > end, object test"); - //----------------------------------------------------------------------- - @SuppressWarnings("cast") - @Test - public void testIndexOfDouble() { - double[] array = null; - assertEquals(-1, ArrayUtils.indexOf(array, (double) 0)); - array = new double[0]; - assertEquals(-1, ArrayUtils.indexOf(array, (double) 0)); - array = new double[]{0, 1, 2, 3, 0}; - assertEquals(0, ArrayUtils.indexOf(array, (double) 0)); - assertEquals(1, ArrayUtils.indexOf(array, (double) 1)); - assertEquals(2, ArrayUtils.indexOf(array, (double) 2)); - assertEquals(3, ArrayUtils.indexOf(array, (double) 3)); - assertEquals(3, ArrayUtils.indexOf(array, (double) 3, -1)); - assertEquals(-1, ArrayUtils.indexOf(array, (double) 99)); - } + assertSame(ArrayUtils.EMPTY_INT_ARRAY, ArrayUtils.subarray(array, 3, 3), "start == end, object test"); - @SuppressWarnings("cast") - @Test - public void testIndexOfDoubleTolerance() { - double[] array = null; - assertEquals(-1, ArrayUtils.indexOf(array, (double) 0, (double) 0)); - array = new double[0]; - assertEquals(-1, ArrayUtils.indexOf(array, (double) 0, (double) 0)); - array = new double[]{0, 1, 2, 3, 0}; - assertEquals(0, ArrayUtils.indexOf(array, (double) 0, 0.3)); - assertEquals(2, ArrayUtils.indexOf(array, 2.2, 0.35)); - assertEquals(3, ArrayUtils.indexOf(array, 4.15, 2.0)); - assertEquals(1, ArrayUtils.indexOf(array, 1.00001324, 0.0001)); - } + assertSame(ArrayUtils.EMPTY_INT_ARRAY, ArrayUtils.subarray(array, 8733, 4), + "start overshoot, any end, object test"); - @SuppressWarnings("cast") - @Test - public void testIndexOfDoubleWithStartIndex() { - double[] array = null; - assertEquals(-1, ArrayUtils.indexOf(array, (double) 0, 2)); - array = new double[0]; - assertEquals(-1, ArrayUtils.indexOf(array, (double) 0, 2)); - array = new double[]{0, 1, 2, 3, 0}; - assertEquals(4, ArrayUtils.indexOf(array, (double) 0, 2)); - assertEquals(-1, ArrayUtils.indexOf(array, (double) 1, 2)); - assertEquals(2, ArrayUtils.indexOf(array, (double) 2, 2)); - assertEquals(3, ArrayUtils.indexOf(array, (double) 3, 2)); - assertEquals(-1, ArrayUtils.indexOf(array, (double) 99, 0)); - assertEquals(-1, ArrayUtils.indexOf(array, (double) 0, 6)); - } + // array type tests - @SuppressWarnings("cast") - @Test - public void testIndexOfDoubleWithStartIndexTolerance() { - double[] array = null; - assertEquals(-1, ArrayUtils.indexOf(array, (double) 0, 2, (double) 0)); - array = new double[0]; - assertEquals(-1, ArrayUtils.indexOf(array, (double) 0, 2, (double) 0)); - array = new double[]{0, 1, 2, 3, 0}; - assertEquals(-1, ArrayUtils.indexOf(array, (double) 0, 99, 0.3)); - assertEquals(0, ArrayUtils.indexOf(array, (double) 0, 0, 0.3)); - assertEquals(4, ArrayUtils.indexOf(array, (double) 0, 3, 0.3)); - assertEquals(2, ArrayUtils.indexOf(array, 2.2, 0, 0.35)); - assertEquals(3, ArrayUtils.indexOf(array, 4.15, 0, 2.0)); - assertEquals(1, ArrayUtils.indexOf(array, 1.00001324, 0, 0.0001)); - assertEquals(3, ArrayUtils.indexOf(array, 4.15, -1, 2.0)); - assertEquals(1, ArrayUtils.indexOf(array, 1.00001324, -300, 0.0001)); + assertSame(int.class, ArrayUtils.subarray(array, 2, 4).getClass().getComponentType(), "int type"); } - @SuppressWarnings("cast") @Test - public void testIndexesOfDouble() { - double[] array = null; - final BitSet emptySet = new BitSet(); - final BitSet testSet = new BitSet(); - assertEquals(emptySet, ArrayUtils.indexesOf(array, 0)); - array = new double[]{0, 1, 2, 3, 0}; - testSet.set(0); - testSet.set(4); - assertEquals(testSet, ArrayUtils.indexesOf(array, 0)); - testSet.clear(); - testSet.set(1); - assertEquals(testSet, ArrayUtils.indexesOf(array, 1)); - testSet.clear(); - testSet.set(2); - assertEquals(testSet, ArrayUtils.indexesOf(array, 2)); - testSet.clear(); - testSet.set(3); - assertEquals(testSet, ArrayUtils.indexesOf(array, 3)); - assertEquals(emptySet, ArrayUtils.indexesOf(array, 99)); - } + public void testSubarrayLong() { + final long[] nullArray = null; + final long[] array = {999910, 999911, 999912, 999913, 999914, 999915}; + final long[] leftSubarray = {999910, 999911, 999912, 999913}; + final long[] midSubarray = {999911, 999912, 999913, 999914}; + final long[] rightSubarray = {999912, 999913, 999914, 999915}; - @SuppressWarnings("cast") - @Test - public void testIndexesOfDoubleWithStartIndex() { - double[] array = null; - final BitSet emptySet = new BitSet(); - final BitSet testSet = new BitSet(); - assertEquals(emptySet, ArrayUtils.indexesOf(array, 0, 2)); - array = new double[]{0, 1, 2, 3, 0}; - testSet.set(4); - assertEquals(testSet, ArrayUtils.indexesOf(array, 0, 2)); - testSet.set(0); - assertEquals(testSet, ArrayUtils.indexesOf(array, 0, 0)); - testSet.clear(); - testSet.set(1); - assertEquals(testSet, ArrayUtils.indexesOf(array, 1, 1)); - testSet.clear(); - testSet.set(2); - assertEquals(testSet, ArrayUtils.indexesOf(array, 2, 0)); - testSet.clear(); - testSet.set(3); - assertEquals(testSet, ArrayUtils.indexesOf(array, 3, 0)); - assertEquals(testSet, ArrayUtils.indexesOf(array, 3, -1)); - assertEquals(emptySet, ArrayUtils.indexesOf(array, 99, 0)); - } + assertTrue(ArrayUtils.isEquals(leftSubarray, ArrayUtils.subarray(array, 0, 4)), "0 start, mid end"); - @SuppressWarnings("cast") - @Test - public void testIndexesOfDoubleTolerance() { - double[] array = null; - final BitSet emptySet = new BitSet(); - final BitSet testSet = new BitSet(); - assertEquals(emptySet, ArrayUtils.indexesOf(array, (double) 0, (double) 0)); - array = new double[0]; - assertEquals(emptySet, ArrayUtils.indexesOf(array, (double) 0, (double) 0)); - array = new double[]{0, 1, 2, 3, 0}; - testSet.set(0); - testSet.set(4); - assertEquals(testSet, ArrayUtils.indexesOf(array, (double) 0, 0.3)); - testSet.clear(); - testSet.set(3); - assertEquals(testSet, ArrayUtils.indexesOf(array, 4.15, 2.0)); - testSet.clear(); - testSet.set(1); - assertEquals(testSet, ArrayUtils.indexesOf(array, 1.00001324, 0.0001)); - } + assertTrue(ArrayUtils.isEquals(array, ArrayUtils.subarray(array, 0, array.length)), "0 start, length end"); - @SuppressWarnings("cast") - @Test - public void testIndexesOfDoubleWithStartIndexTolerance() { - double[] array = null; - final BitSet emptySet = new BitSet(); - final BitSet testSet = new BitSet(); - assertEquals(emptySet, ArrayUtils.indexesOf(array, (double) 0, 0, (double) 0)); - array = new double[0]; - assertEquals(emptySet, ArrayUtils.indexesOf(array, (double) 0, 0, (double) 0)); - array = new double[]{0, 1, 2, 3, 0}; - testSet.set(4); - assertEquals(testSet, ArrayUtils.indexesOf(array, (double) 0, 1, 0.3)); - testSet.set(0); - assertEquals(testSet, ArrayUtils.indexesOf(array, (double) 0, 0, 0.3)); - testSet.clear(); - testSet.set(2); - assertEquals(testSet, ArrayUtils.indexesOf(array, 2, 0, 0.35)); - assertEquals(testSet, ArrayUtils.indexesOf(array, 2, 2, 0.35)); - assertEquals(testSet, ArrayUtils.indexesOf(array, 2, -1, 0.35)); - assertEquals(emptySet, ArrayUtils.indexesOf(array, 2, 3, 0.35)); - testSet.clear(); - testSet.set(3); - assertEquals(testSet, ArrayUtils.indexesOf(array, 4.15, 0, 2.0)); - testSet.clear(); - testSet.set(1); - assertEquals(testSet, ArrayUtils.indexesOf(array, 1.00001324, 0, 0.0001)); - } + assertTrue(ArrayUtils.isEquals(midSubarray, ArrayUtils.subarray(array, 1, 5)), "mid start, mid end"); - @SuppressWarnings("cast") - @Test - public void testLastIndexOfDouble() { - double[] array = null; - assertEquals(-1, ArrayUtils.lastIndexOf(array, (double) 0)); - array = new double[0]; - assertEquals(-1, ArrayUtils.lastIndexOf(array, (double) 0)); - array = new double[]{0, 1, 2, 3, 0}; - assertEquals(4, ArrayUtils.lastIndexOf(array, (double) 0)); - assertEquals(1, ArrayUtils.lastIndexOf(array, (double) 1)); - assertEquals(2, ArrayUtils.lastIndexOf(array, (double) 2)); - assertEquals(3, ArrayUtils.lastIndexOf(array, (double) 3)); - assertEquals(-1, ArrayUtils.lastIndexOf(array, (double) 99)); - } + assertTrue(ArrayUtils.isEquals(rightSubarray, ArrayUtils.subarray(array, 2, array.length)), + "mid start, length end"); + + assertNull(ArrayUtils.subarray(nullArray, 0, 3), "null input"); + + assertEquals(ArrayUtils.EMPTY_LONG_ARRAY, ArrayUtils.subarray(ArrayUtils.EMPTY_LONG_ARRAY, 1, 2), + "empty array"); + + assertEquals(ArrayUtils.EMPTY_LONG_ARRAY, ArrayUtils.subarray(array, 4, 2), "start > end"); + + assertEquals(ArrayUtils.EMPTY_LONG_ARRAY, ArrayUtils.subarray(array, 3, 3), "start == end"); + + assertTrue(ArrayUtils.isEquals(leftSubarray, ArrayUtils.subarray(array, -2, 4)), + "start undershoot, normal end"); + + assertEquals(ArrayUtils.EMPTY_LONG_ARRAY, ArrayUtils.subarray(array, 33, 4), "start overshoot, any end"); + + assertTrue(ArrayUtils.isEquals(rightSubarray, ArrayUtils.subarray(array, 2, 33)), + "normal start, end overshoot"); + + assertTrue(ArrayUtils.isEquals(array, ArrayUtils.subarray(array, -2, 12)), "start undershoot, end overshoot"); + + // empty-return tests + + assertSame(ArrayUtils.EMPTY_LONG_ARRAY, ArrayUtils.subarray(ArrayUtils.EMPTY_LONG_ARRAY, 1, 2), + "empty array, object test"); + + assertSame(ArrayUtils.EMPTY_LONG_ARRAY, ArrayUtils.subarray(array, 4, 1), "start > end, object test"); + + assertSame(ArrayUtils.EMPTY_LONG_ARRAY, ArrayUtils.subarray(array, 3, 3), "start == end, object test"); + + assertSame(ArrayUtils.EMPTY_LONG_ARRAY, ArrayUtils.subarray(array, 8733, 4), + "start overshoot, any end, object test"); + + // array type tests + + assertSame(long.class, ArrayUtils.subarray(array, 2, 4).getClass().getComponentType(), "long type"); - @SuppressWarnings("cast") - @Test - public void testLastIndexOfDoubleTolerance() { - double[] array = null; - assertEquals(-1, ArrayUtils.lastIndexOf(array, (double) 0, (double) 0)); - array = new double[0]; - assertEquals(-1, ArrayUtils.lastIndexOf(array, (double) 0, (double) 0)); - array = new double[]{0, 1, 2, 3, 0}; - assertEquals(4, ArrayUtils.lastIndexOf(array, (double) 0, 0.3)); - assertEquals(2, ArrayUtils.lastIndexOf(array, 2.2, 0.35)); - assertEquals(3, ArrayUtils.lastIndexOf(array, 4.15, 2.0)); - assertEquals(1, ArrayUtils.lastIndexOf(array, 1.00001324, 0.0001)); } - @SuppressWarnings("cast") @Test - public void testLastIndexOfDoubleWithStartIndex() { - double[] array = null; - assertEquals(-1, ArrayUtils.lastIndexOf(array, (double) 0, 2)); - array = new double[0]; - assertEquals(-1, ArrayUtils.lastIndexOf(array, (double) 0, 2)); - array = new double[]{0, 1, 2, 3, 0}; - assertEquals(0, ArrayUtils.lastIndexOf(array, (double) 0, 2)); - assertEquals(1, ArrayUtils.lastIndexOf(array, (double) 1, 2)); - assertEquals(2, ArrayUtils.lastIndexOf(array, (double) 2, 2)); - assertEquals(-1, ArrayUtils.lastIndexOf(array, (double) 3, 2)); - assertEquals(-1, ArrayUtils.lastIndexOf(array, (double) 3, -1)); - assertEquals(-1, ArrayUtils.lastIndexOf(array, (double) 99)); - assertEquals(4, ArrayUtils.lastIndexOf(array, (double) 0, 88)); - } + public void testSubarrayObject() { + final Object[] nullArray = null; + final Object[] objectArray = {"a", "b", "c", "d", "e", "f"}; - @SuppressWarnings("cast") - @Test - public void testLastIndexOfDoubleWithStartIndexTolerance() { - double[] array = null; - assertEquals(-1, ArrayUtils.lastIndexOf(array, (double) 0, 2, (double) 0)); - array = new double[0]; - assertEquals(-1, ArrayUtils.lastIndexOf(array, (double) 0, 2, (double) 0)); - array = new double[]{(double) 3}; - assertEquals(-1, ArrayUtils.lastIndexOf(array, (double) 1, 0, (double) 0)); - array = new double[]{0, 1, 2, 3, 0}; - assertEquals(4, ArrayUtils.lastIndexOf(array, (double) 0, 99, 0.3)); - assertEquals(0, ArrayUtils.lastIndexOf(array, (double) 0, 3, 0.3)); - assertEquals(2, ArrayUtils.lastIndexOf(array, 2.2, 3, 0.35)); - assertEquals(3, ArrayUtils.lastIndexOf(array, 4.15, array.length, 2.0)); - assertEquals(1, ArrayUtils.lastIndexOf(array, 1.00001324, array.length, 0.0001)); - assertEquals(-1, ArrayUtils.lastIndexOf(array, 4.15, -200, 2.0)); - } + assertEquals("abcd", StringUtils.join(ArrayUtils.subarray(objectArray, 0, 4)), "0 start, mid end"); + assertEquals("abcdef", StringUtils.join(ArrayUtils.subarray(objectArray, 0, objectArray.length)), + "0 start, length end"); + assertEquals("bcd", StringUtils.join(ArrayUtils.subarray(objectArray, 1, 4)), "mid start, mid end"); + assertEquals("bcdef", StringUtils.join(ArrayUtils.subarray(objectArray, 1, objectArray.length)), + "mid start, length end"); - @SuppressWarnings("cast") - @Test - public void testContainsDouble() { - double[] array = null; - assertFalse(ArrayUtils.contains(array, (double) 1)); - array = new double[]{0, 1, 2, 3, 0}; - assertTrue(ArrayUtils.contains(array, (double) 0)); - assertTrue(ArrayUtils.contains(array, (double) 1)); - assertTrue(ArrayUtils.contains(array, (double) 2)); - assertTrue(ArrayUtils.contains(array, (double) 3)); - assertFalse(ArrayUtils.contains(array, (double) 99)); + assertNull(ArrayUtils.subarray(nullArray, 0, 3), "null input"); + assertEquals("", StringUtils.join(ArrayUtils.subarray(ArrayUtils.EMPTY_OBJECT_ARRAY, 1, 2)), "empty array"); + assertEquals("", StringUtils.join(ArrayUtils.subarray(objectArray, 4, 2)), "start > end"); + assertEquals("", StringUtils.join(ArrayUtils.subarray(objectArray, 3, 3)), "start == end"); + assertEquals("abcd", StringUtils.join(ArrayUtils.subarray(objectArray, -2, 4)), "start undershoot, normal end"); + assertEquals("", StringUtils.join(ArrayUtils.subarray(objectArray, 33, 4)), "start overshoot, any end"); + assertEquals("cdef", StringUtils.join(ArrayUtils.subarray(objectArray, 2, 33)), "normal start, end overshoot"); + assertEquals("abcdef", StringUtils.join(ArrayUtils.subarray(objectArray, -2, 12)), + "start undershoot, end overshoot"); + + // array type tests + final Date[] dateArray = {new java.sql.Date(new Date().getTime()), + new Date(), new Date(), new Date(), new Date()}; + + assertSame(Object.class, ArrayUtils.subarray(objectArray, 2, 4).getClass().getComponentType(), "Object type"); + assertSame(Date.class, ArrayUtils.subarray(dateArray, 1, 4).getClass().getComponentType(), + "java.util.Date type"); + assertNotSame(java.sql.Date.class, ArrayUtils.subarray(dateArray, 1, 4).getClass().getComponentType(), + "java.sql.Date type"); + assertThrows(ClassCastException.class, + () -> java.sql.Date[].class.cast(ArrayUtils.subarray(dateArray, 1, 3)), + "Invalid downcast"); } - @SuppressWarnings("cast") @Test - public void testContainsDoubleTolerance() { - double[] array = null; - assertFalse(ArrayUtils.contains(array, (double) 1, (double) 0)); - array = new double[]{0, 1, 2, 3, 0}; - assertFalse(ArrayUtils.contains(array, 4.0, 0.33)); - assertFalse(ArrayUtils.contains(array, 2.5, 0.49)); - assertTrue(ArrayUtils.contains(array, 2.5, 0.50)); - assertTrue(ArrayUtils.contains(array, 2.5, 0.51)); + public void testSubarrayShort() { + final short[] nullArray = null; + final short[] array = {10, 11, 12, 13, 14, 15}; + final short[] leftSubarray = {10, 11, 12, 13}; + final short[] midSubarray = {11, 12, 13, 14}; + final short[] rightSubarray = {12, 13, 14, 15}; + + assertTrue(ArrayUtils.isEquals(leftSubarray, ArrayUtils.subarray(array, 0, 4)), "0 start, mid end"); + assertTrue(ArrayUtils.isEquals(array, ArrayUtils.subarray(array, 0, array.length)), "0 start, length end"); + assertTrue(ArrayUtils.isEquals(midSubarray, ArrayUtils.subarray(array, 1, 5)), "mid start, mid end"); + assertTrue(ArrayUtils.isEquals(rightSubarray, ArrayUtils.subarray(array, 2, array.length)), + "mid start, length end"); + + assertNull(ArrayUtils.subarray(nullArray, 0, 3), "null input"); + assertEquals(ArrayUtils.EMPTY_SHORT_ARRAY, ArrayUtils.subarray(ArrayUtils.EMPTY_SHORT_ARRAY, 1, 2), + "empty array"); + assertEquals(ArrayUtils.EMPTY_SHORT_ARRAY, ArrayUtils.subarray(array, 4, 2), "start > end"); + assertEquals(ArrayUtils.EMPTY_SHORT_ARRAY, ArrayUtils.subarray(array, 3, 3), "start == end"); + assertTrue(ArrayUtils.isEquals(leftSubarray, ArrayUtils.subarray(array, -2, 4)), + "start undershoot, normal end"); + assertEquals(ArrayUtils.EMPTY_SHORT_ARRAY, ArrayUtils.subarray(array, 33, 4), "start overshoot, any end"); + assertTrue(ArrayUtils.isEquals(rightSubarray, ArrayUtils.subarray(array, 2, 33)), + "normal start, end overshoot"); + assertTrue(ArrayUtils.isEquals(array, ArrayUtils.subarray(array, -2, 12)), "start undershoot, end overshoot"); + + // empty-return tests + + assertSame(ArrayUtils.EMPTY_SHORT_ARRAY, ArrayUtils.subarray(ArrayUtils.EMPTY_SHORT_ARRAY, 1, 2), + "empty array, object test"); + assertSame(ArrayUtils.EMPTY_SHORT_ARRAY, ArrayUtils.subarray(array, 4, 1), "start > end, object test"); + assertSame(ArrayUtils.EMPTY_SHORT_ARRAY, ArrayUtils.subarray(array, 3, 3), "start == end, object test"); + assertSame(ArrayUtils.EMPTY_SHORT_ARRAY, ArrayUtils.subarray(array, 8733, 4), + "start overshoot, any end, object test"); + + // array type tests + + assertSame(short.class, ArrayUtils.subarray(array, 2, 4).getClass().getComponentType(), "short type"); } - //----------------------------------------------------------------------- - @SuppressWarnings("cast") @Test - public void testIndexOfFloat() { - float[] array = null; - assertEquals(-1, ArrayUtils.indexOf(array, (float) 0)); - array = new float[0]; - assertEquals(-1, ArrayUtils.indexOf(array, (float) 0)); - array = new float[]{0, 1, 2, 3, 0}; - assertEquals(0, ArrayUtils.indexOf(array, (float) 0)); - assertEquals(1, ArrayUtils.indexOf(array, (float) 1)); - assertEquals(2, ArrayUtils.indexOf(array, (float) 2)); - assertEquals(3, ArrayUtils.indexOf(array, (float) 3)); - assertEquals(-1, ArrayUtils.indexOf(array, (float) 99)); + public void testSubarrChar() { + final char[] nullArray = null; + final char[] array = {'a', 'b', 'c', 'd', 'e', 'f'}; + final char[] leftSubarray = {'a', 'b', 'c', 'd'}; + final char[] midSubarray = {'b', 'c', 'd', 'e'}; + final char[] rightSubarray = {'c', 'd', 'e', 'f'}; + + assertTrue(ArrayUtils.isEquals(leftSubarray, ArrayUtils.subarray(array, 0, 4)), "0 start, mid end"); + assertTrue(ArrayUtils.isEquals(array, ArrayUtils.subarray(array, 0, array.length)), "0 start, length end"); + assertTrue(ArrayUtils.isEquals(midSubarray, ArrayUtils.subarray(array, 1, 5)), "mid start, mid end"); + assertTrue(ArrayUtils.isEquals(rightSubarray, ArrayUtils.subarray(array, 2, array.length)), + "mid start, length end"); + + assertNull(ArrayUtils.subarray(nullArray, 0, 3), "null input"); + assertEquals(ArrayUtils.EMPTY_CHAR_ARRAY, ArrayUtils.subarray(ArrayUtils.EMPTY_CHAR_ARRAY, 1, 2), + "empty array"); + assertEquals(ArrayUtils.EMPTY_CHAR_ARRAY, ArrayUtils.subarray(array, 4, 2), "start > end"); + assertEquals(ArrayUtils.EMPTY_CHAR_ARRAY, ArrayUtils.subarray(array, 3, 3), "start == end"); + assertTrue(ArrayUtils.isEquals(leftSubarray, ArrayUtils.subarray(array, -2, 4)), + "start undershoot, normal end"); + assertEquals(ArrayUtils.EMPTY_CHAR_ARRAY, ArrayUtils.subarray(array, 33, 4), "start overshoot, any end"); + assertTrue(ArrayUtils.isEquals(rightSubarray, ArrayUtils.subarray(array, 2, 33)), + "normal start, end overshoot"); + assertTrue(ArrayUtils.isEquals(array, ArrayUtils.subarray(array, -2, 12)), "start undershoot, end overshoot"); + + // empty-return tests + + assertSame(ArrayUtils.EMPTY_CHAR_ARRAY, ArrayUtils.subarray(ArrayUtils.EMPTY_CHAR_ARRAY, 1, 2), + "empty array, object test"); + assertSame(ArrayUtils.EMPTY_CHAR_ARRAY, ArrayUtils.subarray(array, 4, 1), "start > end, object test"); + assertSame(ArrayUtils.EMPTY_CHAR_ARRAY, ArrayUtils.subarray(array, 3, 3), "start == end, object test"); + assertSame(ArrayUtils.EMPTY_CHAR_ARRAY, ArrayUtils.subarray(array, 8733, 4), + "start overshoot, any end, object test"); + + // array type tests + + assertSame(char.class, ArrayUtils.subarray(array, 2, 4).getClass().getComponentType(), "char type"); } - @SuppressWarnings("cast") @Test - public void testIndexOfFloatWithStartIndex() { - float[] array = null; - assertEquals(-1, ArrayUtils.indexOf(array, (float) 0, 2)); - array = new float[0]; - assertEquals(-1, ArrayUtils.indexOf(array, (float) 0, 2)); - array = new float[]{0, 1, 2, 3, 0}; - assertEquals(4, ArrayUtils.indexOf(array, (float) 0, 2)); - assertEquals(-1, ArrayUtils.indexOf(array, (float) 1, 2)); - assertEquals(2, ArrayUtils.indexOf(array, (float) 2, 2)); - assertEquals(3, ArrayUtils.indexOf(array, (float) 3, 2)); - assertEquals(3, ArrayUtils.indexOf(array, (float) 3, -1)); - assertEquals(-1, ArrayUtils.indexOf(array, (float) 99, 0)); - assertEquals(-1, ArrayUtils.indexOf(array, (float) 0, 6)); + public void testSwapBoolean() { + final boolean[] array = new boolean[]{true, false, false}; + ArrayUtils.swap(array, 0, 2); + assertFalse(array[0]); + assertFalse(array[1]); + assertTrue(array[2]); } - @SuppressWarnings("cast") @Test - public void testIndexesOfFloat() { - float[] array = null; - final BitSet emptySet = new BitSet(); - final BitSet testSet = new BitSet(); - assertEquals(emptySet, ArrayUtils.indexesOf(array, 0)); - array = new float[]{0, 1, 2, 3, 0}; - testSet.set(0); - testSet.set(4); - assertEquals(testSet, ArrayUtils.indexesOf(array, 0)); - testSet.clear(); - testSet.set(1); - assertEquals(testSet, ArrayUtils.indexesOf(array, 1)); - testSet.clear(); - testSet.set(2); - assertEquals(testSet, ArrayUtils.indexesOf(array, 2)); - testSet.clear(); - testSet.set(3); - assertEquals(testSet, ArrayUtils.indexesOf(array, 3)); - assertEquals(emptySet, ArrayUtils.indexesOf(array, 99)); + public void testSwapBooleanRange() { + boolean[] array = new boolean[]{false, false, true, true}; + ArrayUtils.swap(array, 0, 2, 2); + assertTrue(array[0]); + assertTrue(array[1]); + assertFalse(array[2]); + assertFalse(array[3]); + + array = new boolean[]{false, true, false}; + ArrayUtils.swap(array, 0, 3); + assertFalse(array[0]); + assertTrue(array[1]); + assertFalse(array[2]); + + array = new boolean[]{true, true, false}; + ArrayUtils.swap(array, 0, 2, 2); + assertFalse(array[0]); + assertTrue(array[1]); + assertTrue(array[2]); + + array = new boolean[]{true, true, false}; + ArrayUtils.swap(array, -1, 2, 2); + assertFalse(array[0]); + assertTrue(array[1]); + assertTrue(array[2]); + + array = new boolean[]{true, true, false}; + ArrayUtils.swap(array, 0, -1, 2); + assertTrue(array[0]); + assertTrue(array[1]); + assertFalse(array[2]); + + array = new boolean[]{true, true, false}; + ArrayUtils.swap(array, -1, -1, 2); + assertTrue(array[0]); + assertTrue(array[1]); + assertFalse(array[2]); } - @SuppressWarnings("cast") @Test - public void testIndexesOfFloatWithStartIndex() { - float[] array = null; - final BitSet emptySet = new BitSet(); - final BitSet testSet = new BitSet(); - assertEquals(emptySet, ArrayUtils.indexesOf(array, 0, 2)); - array = new float[]{0, 1, 2, 3, 0}; - testSet.set(4); - assertEquals(testSet, ArrayUtils.indexesOf(array, 0, 2)); - testSet.set(0); - assertEquals(testSet, ArrayUtils.indexesOf(array, 0, 0)); - testSet.clear(); - testSet.set(1); - assertEquals(testSet, ArrayUtils.indexesOf(array, 1, 1)); - testSet.clear(); - testSet.set(2); - assertEquals(testSet, ArrayUtils.indexesOf(array, 2, 0)); - testSet.clear(); - testSet.set(3); - assertEquals(testSet, ArrayUtils.indexesOf(array, 3, 0)); - assertEquals(testSet, ArrayUtils.indexesOf(array, 3, -1)); - assertEquals(emptySet, ArrayUtils.indexesOf(array, 99, 0)); + public void testSwapByte() { + final byte[] array = new byte[]{1, 2, 3}; + ArrayUtils.swap(array, 0, 2); + assertEquals(3, array[0]); + assertEquals(2, array[1]); + assertEquals(1, array[2]); } - @SuppressWarnings("cast") @Test - public void testLastIndexOfFloat() { - float[] array = null; - assertEquals(-1, ArrayUtils.lastIndexOf(array, (float) 0)); - array = new float[0]; - assertEquals(-1, ArrayUtils.lastIndexOf(array, (float) 0)); - array = new float[]{0, 1, 2, 3, 0}; - assertEquals(4, ArrayUtils.lastIndexOf(array, (float) 0)); - assertEquals(1, ArrayUtils.lastIndexOf(array, (float) 1)); - assertEquals(2, ArrayUtils.lastIndexOf(array, (float) 2)); - assertEquals(3, ArrayUtils.lastIndexOf(array, (float) 3)); - assertEquals(-1, ArrayUtils.lastIndexOf(array, (float) 99)); - } + public void testSwapByteRange() { + byte[] array = new byte[]{1, 2, 3, 4}; + ArrayUtils.swap(array, 0, 2, 2); + assertEquals(3, array[0]); + assertEquals(4, array[1]); + assertEquals(1, array[2]); + assertEquals(2, array[3]); - @SuppressWarnings("cast") - @Test - public void testLastIndexOfFloatWithStartIndex() { - float[] array = null; - assertEquals(-1, ArrayUtils.lastIndexOf(array, (float) 0, 2)); - array = new float[0]; - assertEquals(-1, ArrayUtils.lastIndexOf(array, (float) 0, 2)); - array = new float[]{0, 1, 2, 3, 0}; - assertEquals(0, ArrayUtils.lastIndexOf(array, (float) 0, 2)); - assertEquals(1, ArrayUtils.lastIndexOf(array, (float) 1, 2)); - assertEquals(2, ArrayUtils.lastIndexOf(array, (float) 2, 2)); - assertEquals(-1, ArrayUtils.lastIndexOf(array, (float) 3, 2)); - assertEquals(-1, ArrayUtils.lastIndexOf(array, (float) 3, -1)); - assertEquals(-1, ArrayUtils.lastIndexOf(array, (float) 99)); - assertEquals(4, ArrayUtils.lastIndexOf(array, (float) 0, 88)); + array = new byte[]{1, 2, 3}; + ArrayUtils.swap(array, 0, 3); + assertEquals(1, array[0]); + assertEquals(2, array[1]); + assertEquals(3, array[2]); + + array = new byte[]{1, 2, 3}; + ArrayUtils.swap(array, 0, 2, 2); + assertEquals(3, array[0]); + assertEquals(2, array[1]); + assertEquals(1, array[2]); + + array = new byte[]{1, 2, 3}; + ArrayUtils.swap(array, -1, 2, 2); + assertEquals(3, array[0]); + assertEquals(2, array[1]); + assertEquals(1, array[2]); + + array = new byte[]{1, 2, 3}; + ArrayUtils.swap(array, 0, -1, 2); + assertEquals(1, array[0]); + assertEquals(2, array[1]); + assertEquals(3, array[2]); + + array = new byte[]{1, 2, 3}; + ArrayUtils.swap(array, -1, -1, 2); + assertEquals(1, array[0]); + assertEquals(2, array[1]); + assertEquals(3, array[2]); } - @SuppressWarnings("cast") + //----------------------------------------------------------------------- @Test - public void testContainsFloat() { - float[] array = null; - assertFalse(ArrayUtils.contains(array, (float) 1)); - array = new float[]{0, 1, 2, 3, 0}; - assertTrue(ArrayUtils.contains(array, (float) 0)); - assertTrue(ArrayUtils.contains(array, (float) 1)); - assertTrue(ArrayUtils.contains(array, (float) 2)); - assertTrue(ArrayUtils.contains(array, (float) 3)); - assertFalse(ArrayUtils.contains(array, (float) 99)); + public void testSwapChar() { + char[] array = new char[]{1, 2, 3}; + ArrayUtils.swap(array, 0, 2); + assertArrayEquals(new char[]{3, 2, 1}, array); + + array = new char[]{1, 2, 3}; + ArrayUtils.swap(array, 0, 0); + assertArrayEquals(new char[]{1, 2, 3}, array); + + array = new char[]{1, 2, 3}; + ArrayUtils.swap(array, 1, 0); + assertArrayEquals(new char[]{2, 1, 3}, array); } - //----------------------------------------------------------------------- @Test - public void testIndexOfBoolean() { - boolean[] array = null; - assertEquals(-1, ArrayUtils.indexOf(array, true)); - array = new boolean[0]; - assertEquals(-1, ArrayUtils.indexOf(array, true)); - array = new boolean[]{true, false, true}; - assertEquals(0, ArrayUtils.indexOf(array, true)); - assertEquals(1, ArrayUtils.indexOf(array, false)); - array = new boolean[]{true, true}; - assertEquals(-1, ArrayUtils.indexOf(array, false)); + public void testSwapCharRange() { + char[] array = new char[]{1, 2, 3, 4}; + ArrayUtils.swap(array, 0, 2, 2); + assertEquals(3, array[0]); + assertEquals(4, array[1]); + assertEquals(1, array[2]); + assertEquals(2, array[3]); + + array = new char[]{1, 2, 3}; + ArrayUtils.swap(array, 0, 3); + assertEquals(1, array[0]); + assertEquals(2, array[1]); + assertEquals(3, array[2]); + + array = new char[]{1, 2, 3}; + ArrayUtils.swap(array, 0, 2, 2); + assertEquals(3, array[0]); + assertEquals(2, array[1]); + assertEquals(1, array[2]); + + array = new char[]{1, 2, 3}; + ArrayUtils.swap(array, -1, 2, 2); + assertEquals(3, array[0]); + assertEquals(2, array[1]); + assertEquals(1, array[2]); + + array = new char[]{1, 2, 3}; + ArrayUtils.swap(array, 0, -1, 2); + assertEquals(1, array[0]); + assertEquals(2, array[1]); + assertEquals(3, array[2]); + + array = new char[]{1, 2, 3}; + ArrayUtils.swap(array, -1, -1, 2); + assertEquals(1, array[0]); + assertEquals(2, array[1]); + assertEquals(3, array[2]); } @Test - public void testIndexOfBooleanWithStartIndex() { - boolean[] array = null; - assertEquals(-1, ArrayUtils.indexOf(array, true, 2)); - array = new boolean[0]; - assertEquals(-1, ArrayUtils.indexOf(array, true, 2)); - array = new boolean[]{true, false, true}; - assertEquals(2, ArrayUtils.indexOf(array, true, 1)); - assertEquals(-1, ArrayUtils.indexOf(array, false, 2)); - assertEquals(1, ArrayUtils.indexOf(array, false, 0)); - assertEquals(1, ArrayUtils.indexOf(array, false, -1)); - array = new boolean[]{true, true}; - assertEquals(-1, ArrayUtils.indexOf(array, false, 0)); - assertEquals(-1, ArrayUtils.indexOf(array, false, -1)); + public void testSwapDouble() { + final double[] array = new double[]{1, 2, 3}; + ArrayUtils.swap(array, 0, 2); + assertEquals(3, array[0]); + assertEquals(2, array[1]); + assertEquals(1, array[2]); } @Test - public void testIndexesOfBoolean() { - boolean[] array = null; - final BitSet emptySet = new BitSet(); - final BitSet testSet = new BitSet(); - assertEquals(emptySet, ArrayUtils.indexesOf(array, true)); - array = new boolean[0]; - assertEquals(emptySet, ArrayUtils.indexesOf(array, true)); - array = new boolean[]{true, false, true}; - testSet.set(0); - testSet.set(2); - assertEquals(testSet, ArrayUtils.indexesOf(array, true)); - testSet.clear(); - testSet.set(1); - assertEquals(testSet, ArrayUtils.indexesOf(array, false)); - array = new boolean[]{true, true}; - assertEquals(emptySet, ArrayUtils.indexesOf(array, false)); + public void testSwapDoubleRange() { + double[] array = new double[]{1, 2, 3, 4}; + ArrayUtils.swap(array, 0, 2, 2); + assertEquals(3, array[0]); + assertEquals(4, array[1]); + assertEquals(1, array[2]); + assertEquals(2, array[3]); + + array = new double[]{1, 2, 3}; + ArrayUtils.swap(array, 0, 3); + assertEquals(1, array[0]); + assertEquals(2, array[1]); + assertEquals(3, array[2]); + + array = new double[]{1, 2, 3}; + ArrayUtils.swap(array, 0, 2, 2); + assertEquals(3, array[0]); + assertEquals(2, array[1]); + assertEquals(1, array[2]); + + array = new double[]{1, 2, 3}; + ArrayUtils.swap(array, -1, 2, 2); + assertEquals(3, array[0]); + assertEquals(2, array[1]); + assertEquals(1, array[2]); + + array = new double[]{1, 2, 3}; + ArrayUtils.swap(array, 0, -1, 2); + assertEquals(1, array[0]); + assertEquals(2, array[1]); + assertEquals(3, array[2]); + + array = new double[]{1, 2, 3}; + ArrayUtils.swap(array, -1, -1, 2); + assertEquals(1, array[0]); + assertEquals(2, array[1]); + assertEquals(3, array[2]); } @Test - public void testIndexesOfBooleanWithStartIndex() { - boolean[] array = null; - final BitSet emptySet = new BitSet(); - final BitSet testSet = new BitSet(); - assertEquals(emptySet, ArrayUtils.indexesOf(array, true, 0)); - array = new boolean[0]; - assertEquals(emptySet, ArrayUtils.indexesOf(array, true, 0)); - array = new boolean[]{true, false, true}; - testSet.set(2); - assertEquals(testSet, ArrayUtils.indexesOf(array, true, 1)); - testSet.set(0); - assertEquals(testSet, ArrayUtils.indexesOf(array, true, 0)); - testSet.clear(); - testSet.set(1); - assertEquals(testSet, ArrayUtils.indexesOf(array, false, 1)); - array = new boolean[]{true, true}; - assertEquals(emptySet, ArrayUtils.indexesOf(array, false, 0)); - assertEquals(emptySet, ArrayUtils.indexesOf(array, false, -1)); + public void testSwapEmptyBooleanArray() { + final boolean[] array = new boolean[0]; + ArrayUtils.swap(array, 0, 2); + assertEquals(0, array.length); } @Test - public void testLastIndexOfBoolean() { - boolean[] array = null; - assertEquals(-1, ArrayUtils.lastIndexOf(array, true)); - array = new boolean[0]; - assertEquals(-1, ArrayUtils.lastIndexOf(array, true)); - array = new boolean[]{true, false, true}; - assertEquals(2, ArrayUtils.lastIndexOf(array, true)); - assertEquals(1, ArrayUtils.lastIndexOf(array, false)); - array = new boolean[]{true, true}; - assertEquals(-1, ArrayUtils.lastIndexOf(array, false)); + public void testSwapEmptyByteArray() { + final byte[] array = new byte[0]; + ArrayUtils.swap(array, 0, 2); + assertEquals(0, array.length); } @Test - public void testLastIndexOfBooleanWithStartIndex() { - boolean[] array = null; - assertEquals(-1, ArrayUtils.lastIndexOf(array, true, 2)); - array = new boolean[0]; - assertEquals(-1, ArrayUtils.lastIndexOf(array, true, 2)); - array = new boolean[]{true, false, true}; - assertEquals(2, ArrayUtils.lastIndexOf(array, true, 2)); - assertEquals(0, ArrayUtils.lastIndexOf(array, true, 1)); - assertEquals(1, ArrayUtils.lastIndexOf(array, false, 2)); - assertEquals(-1, ArrayUtils.lastIndexOf(array, true, -1)); - array = new boolean[]{true, true}; - assertEquals(-1, ArrayUtils.lastIndexOf(array, false, 2)); - assertEquals(-1, ArrayUtils.lastIndexOf(array, true, -1)); + public void testSwapEmptyCharArray() { + final char[] array = new char[0]; + ArrayUtils.swap(array, 0, 2); + assertEquals(0, array.length); } @Test - public void testContainsBoolean() { - boolean[] array = null; - assertFalse(ArrayUtils.contains(array, true)); - array = new boolean[]{true, false, true}; - assertTrue(ArrayUtils.contains(array, true)); - assertTrue(ArrayUtils.contains(array, false)); - array = new boolean[]{true, true}; - assertTrue(ArrayUtils.contains(array, true)); - assertFalse(ArrayUtils.contains(array, false)); + public void testSwapEmptyDoubleArray() { + final double[] array = new double[0]; + ArrayUtils.swap(array, 0, 2); + assertEquals(0, array.length); } - // testToPrimitive/Object for boolean - // ----------------------------------------------------------------------- @Test - public void testToPrimitive_boolean() { - final Boolean[] b = null; - assertNull(ArrayUtils.toPrimitive(b)); - assertSame(ArrayUtils.EMPTY_BOOLEAN_ARRAY, ArrayUtils.toPrimitive(new Boolean[0])); - assertArrayEquals(new boolean[]{true, false, true}, ArrayUtils.toPrimitive(new Boolean[]{Boolean.TRUE, Boolean.FALSE, Boolean.TRUE})); - - assertThrows(NullPointerException.class, () -> ArrayUtils.toPrimitive(new Boolean[]{Boolean.TRUE, null})); + public void testSwapEmptyFloatArray() { + final float[] array = new float[0]; + ArrayUtils.swap(array, 0, 2); + assertEquals(0, array.length); } @Test - public void testToPrimitive_boolean_boolean() { - assertNull(ArrayUtils.toPrimitive(null, false)); - assertSame(ArrayUtils.EMPTY_BOOLEAN_ARRAY, ArrayUtils.toPrimitive(new Boolean[0], false)); - assertArrayEquals(new boolean[]{true, false, true}, ArrayUtils.toPrimitive(new Boolean[]{Boolean.TRUE, Boolean.FALSE, Boolean.TRUE}, false)); - assertArrayEquals(new boolean[]{true, false, false}, ArrayUtils.toPrimitive(new Boolean[]{Boolean.TRUE, null, Boolean.FALSE}, false)); - assertArrayEquals(new boolean[]{true, true, false}, ArrayUtils.toPrimitive(new Boolean[]{Boolean.TRUE, null, Boolean.FALSE}, true)); + public void testSwapEmptyIntArray() { + final int[] array = new int[0]; + ArrayUtils.swap(array, 0, 2); + assertEquals(0, array.length); } @Test - public void testToObject_boolean() { - final boolean[] b = null; - assertArrayEquals(null, ArrayUtils.toObject(b)); - assertSame(ArrayUtils.EMPTY_BOOLEAN_OBJECT_ARRAY, ArrayUtils.toObject(new boolean[0])); - assertArrayEquals(new Boolean[]{Boolean.TRUE, Boolean.FALSE, Boolean.TRUE}, ArrayUtils.toObject(new boolean[]{true, false, true})); + public void testSwapEmptyLongArray() { + final long[] array = new long[0]; + ArrayUtils.swap(array, 0, 2); + assertEquals(0, array.length); } - // testToPrimitive/Object for byte - // ----------------------------------------------------------------------- @Test - public void testToPrimitive_char() { - final Character[] b = null; - assertNull(ArrayUtils.toPrimitive(b)); - - assertSame(ArrayUtils.EMPTY_CHAR_ARRAY, ArrayUtils.toPrimitive(new Character[0])); - - assertArrayEquals(new char[]{Character.MIN_VALUE, Character.MAX_VALUE, '0'}, ArrayUtils.toPrimitive(new Character[]{Character.valueOf(Character.MIN_VALUE), - Character.valueOf(Character.MAX_VALUE), Character.valueOf('0')})); - - assertThrows(NullPointerException.class, - () -> ArrayUtils.toPrimitive(new Character[]{Character.valueOf(Character.MIN_VALUE), null})); + public void testSwapEmptyObjectArray() { + final String[] array = new String[0]; + ArrayUtils.swap(array, 0, 2); + assertEquals(0, array.length); } @Test - public void testToPrimitive_char_char() { - final Character[] b = null; - assertNull(ArrayUtils.toPrimitive(b, Character.MIN_VALUE)); - - assertSame(ArrayUtils.EMPTY_CHAR_ARRAY, - ArrayUtils.toPrimitive(new Character[0], (char) 0)); - - assertArrayEquals(new char[]{Character.MIN_VALUE, Character.MAX_VALUE, '0'}, ArrayUtils.toPrimitive(new Character[]{Character.valueOf(Character.MIN_VALUE), - Character.valueOf(Character.MAX_VALUE), Character.valueOf('0')}, - Character.MIN_VALUE)); - - assertArrayEquals(new char[]{Character.MIN_VALUE, Character.MAX_VALUE, '0'}, ArrayUtils.toPrimitive(new Character[]{Character.valueOf(Character.MIN_VALUE), null, - Character.valueOf('0')}, Character.MAX_VALUE)); + public void testSwapEmptyShortArray() { + final short[] array = new short[0]; + ArrayUtils.swap(array, 0, 2); + assertEquals(0, array.length); } @Test - public void testToObject_char() { - final char[] b = null; - assertArrayEquals(null, ArrayUtils.toObject(b)); - - assertSame(ArrayUtils.EMPTY_CHARACTER_OBJECT_ARRAY, - ArrayUtils.toObject(new char[0])); - - assertArrayEquals(new Character[]{Character.valueOf(Character.MIN_VALUE), - Character.valueOf(Character.MAX_VALUE), Character.valueOf('0')}, ArrayUtils.toObject(new char[]{Character.MIN_VALUE, Character.MAX_VALUE, - '0'})); + public void testSwapFloat() { + final float[] array = new float[]{1, 2, 3}; + ArrayUtils.swap(array, 0, 2); + assertEquals(3, array[0]); + assertEquals(2, array[1]); + assertEquals(1, array[2]); } - // testToPrimitive/Object for byte - // ----------------------------------------------------------------------- @Test - public void testToPrimitive_byte() { - final Byte[] b = null; - assertNull(ArrayUtils.toPrimitive(b)); + public void testSwapFloatRange() { + float[] array = new float[]{1, 2, 3, 4}; + ArrayUtils.swap(array, 0, 2, 2); + assertEquals(3, array[0]); + assertEquals(4, array[1]); + assertEquals(1, array[2]); + assertEquals(2, array[3]); - assertSame(ArrayUtils.EMPTY_BYTE_ARRAY, ArrayUtils.toPrimitive(new Byte[0])); + array = new float[]{1, 2, 3}; + ArrayUtils.swap(array, 0, 3); + assertEquals(1, array[0]); + assertEquals(2, array[1]); + assertEquals(3, array[2]); - assertArrayEquals(new byte[]{Byte.MIN_VALUE, Byte.MAX_VALUE, (byte) 9999999}, ArrayUtils.toPrimitive(new Byte[]{Byte.valueOf(Byte.MIN_VALUE), - Byte.valueOf(Byte.MAX_VALUE), Byte.valueOf((byte) 9999999)})); + array = new float[]{1, 2, 3}; + ArrayUtils.swap(array, 0, 2, 2); + assertEquals(3, array[0]); + assertEquals(2, array[1]); + assertEquals(1, array[2]); - assertThrows(NullPointerException.class, - () -> ArrayUtils.toPrimitive(new Byte[]{Byte.valueOf(Byte.MIN_VALUE), null})); + array = new float[]{1, 2, 3}; + ArrayUtils.swap(array, -1, 2, 2); + assertEquals(3, array[0]); + assertEquals(2, array[1]); + assertEquals(1, array[2]); + + array = new float[]{1, 2, 3}; + ArrayUtils.swap(array, 0, -1, 2); + assertEquals(1, array[0]); + assertEquals(2, array[1]); + assertEquals(3, array[2]); + + array = new float[]{1, 2, 3}; + ArrayUtils.swap(array, -1, -1, 2); + assertEquals(1, array[0]); + assertEquals(2, array[1]); + assertEquals(3, array[2]); } @Test - public void testToPrimitive_byte_byte() { - final Byte[] b = null; - assertNull(ArrayUtils.toPrimitive(b, Byte.MIN_VALUE)); - - assertSame(ArrayUtils.EMPTY_BYTE_ARRAY, - ArrayUtils.toPrimitive(new Byte[0], (byte) 1)); + public void testSwapInt() { + final int[] array = new int[]{1, 2, 3}; + ArrayUtils.swap(array, 0, 2); + assertEquals(3, array[0]); + assertEquals(2, array[1]); + assertEquals(1, array[2]); + } - assertArrayEquals(new byte[]{Byte.MIN_VALUE, Byte.MAX_VALUE, (byte) 9999999}, ArrayUtils.toPrimitive(new Byte[]{Byte.valueOf(Byte.MIN_VALUE), - Byte.valueOf(Byte.MAX_VALUE), Byte.valueOf((byte) 9999999)}, - Byte.MIN_VALUE)); + @Test + public void testSwapIntExchangedOffsets() { + int[] array; + array = new int[]{1, 2, 3}; + ArrayUtils.swap(array, 0, 1, 2); + assertArrayEquals(new int[]{2, 3, 1}, array); - assertArrayEquals(new byte[]{Byte.MIN_VALUE, Byte.MAX_VALUE, (byte) 9999999}, ArrayUtils.toPrimitive(new Byte[]{Byte.valueOf(Byte.MIN_VALUE), null, - Byte.valueOf((byte) 9999999)}, Byte.MAX_VALUE)); + array = new int[]{1, 2, 3}; + ArrayUtils.swap(array, 1, 0, 2); + assertArrayEquals(new int[]{2, 3, 1}, array); } @Test - public void testToObject_byte() { - final byte[] b = null; - assertArrayEquals(null, ArrayUtils.toObject(b)); + public void testSwapIntRange() { + int[] array = new int[]{1, 2, 3, 4}; + ArrayUtils.swap(array, 0, 2, 2); + assertEquals(3, array[0]); + assertEquals(4, array[1]); + assertEquals(1, array[2]); + assertEquals(2, array[3]); - assertSame(ArrayUtils.EMPTY_BYTE_OBJECT_ARRAY, - ArrayUtils.toObject(new byte[0])); + array = new int[]{1, 2, 3}; + ArrayUtils.swap(array, 3, 0); + assertEquals(1, array[0]); + assertEquals(2, array[1]); + assertEquals(3, array[2]); - assertArrayEquals(new Byte[]{Byte.valueOf(Byte.MIN_VALUE), - Byte.valueOf(Byte.MAX_VALUE), Byte.valueOf((byte) 9999999)}, ArrayUtils.toObject(new byte[]{Byte.MIN_VALUE, Byte.MAX_VALUE, - (byte) 9999999})); - } + array = new int[]{1, 2, 3}; + ArrayUtils.swap(array, 0, 2, 2); + assertEquals(3, array[0]); + assertEquals(2, array[1]); + assertEquals(1, array[2]); - // testToPrimitive/Object for short - // ----------------------------------------------------------------------- - @Test - public void testToPrimitive_short() { - final Short[] b = null; - assertNull(ArrayUtils.toPrimitive(b)); + array = new int[]{1, 2, 3}; + ArrayUtils.swap(array, -1, 2, 2); + assertEquals(3, array[0]); + assertEquals(2, array[1]); + assertEquals(1, array[2]); - assertSame(ArrayUtils.EMPTY_SHORT_ARRAY, ArrayUtils.toPrimitive(new Short[0])); + array = new int[]{1, 2, 3}; + ArrayUtils.swap(array, 0, -1, 2); + assertEquals(1, array[0]); + assertEquals(2, array[1]); + assertEquals(3, array[2]); - assertArrayEquals(new short[]{Short.MIN_VALUE, Short.MAX_VALUE, (short) 9999999}, ArrayUtils.toPrimitive(new Short[]{Short.valueOf(Short.MIN_VALUE), - Short.valueOf(Short.MAX_VALUE), Short.valueOf((short) 9999999)})); + array = new int[]{1, 2, 3}; + ArrayUtils.swap(array, -1, -1, 2); + assertEquals(1, array[0]); + assertEquals(2, array[1]); + assertEquals(3, array[2]); + } - assertThrows(NullPointerException.class, - () -> ArrayUtils.toPrimitive(new Short[]{Short.valueOf(Short.MIN_VALUE), null})); + @Test + public void testSwapLong() { + final long[] array = new long[]{1, 2, 3}; + ArrayUtils.swap(array, 0, 2); + assertEquals(3, array[0]); + assertEquals(2, array[1]); + assertEquals(1, array[2]); } @Test - public void testToPrimitive_short_short() { - final Short[] s = null; - assertNull(ArrayUtils.toPrimitive(s, Short.MIN_VALUE)); - - assertSame(ArrayUtils.EMPTY_SHORT_ARRAY, ArrayUtils.toPrimitive(new Short[0], - Short.MIN_VALUE)); + public void testSwapLongRange() { + long[] array = new long[]{1, 2, 3, 4}; + ArrayUtils.swap(array, 0, 2, 2); + assertEquals(3, array[0]); + assertEquals(4, array[1]); + assertEquals(1, array[2]); + assertEquals(2, array[3]); - assertArrayEquals(new short[]{Short.MIN_VALUE, Short.MAX_VALUE, (short) 9999999}, ArrayUtils.toPrimitive(new Short[]{Short.valueOf(Short.MIN_VALUE), - Short.valueOf(Short.MAX_VALUE), Short.valueOf((short) 9999999)}, Short.MIN_VALUE)); + array = new long[]{1, 2, 3}; + ArrayUtils.swap(array, 0, 3); + assertEquals(1, array[0]); + assertEquals(2, array[1]); + assertEquals(3, array[2]); - assertArrayEquals(new short[]{Short.MIN_VALUE, Short.MAX_VALUE, (short) 9999999}, ArrayUtils.toPrimitive(new Short[]{Short.valueOf(Short.MIN_VALUE), null, - Short.valueOf((short) 9999999)}, Short.MAX_VALUE)); - } + array = new long[]{1, 2, 3}; + ArrayUtils.swap(array, 0, 2, 2); + assertEquals(3, array[0]); + assertEquals(2, array[1]); + assertEquals(1, array[2]); - @Test - public void testToObject_short() { - final short[] b = null; - assertArrayEquals(null, ArrayUtils.toObject(b)); + array = new long[]{1, 2, 3}; + ArrayUtils.swap(array, -1, 2, 2); + assertEquals(3, array[0]); + assertEquals(2, array[1]); + assertEquals(1, array[2]); - assertSame(ArrayUtils.EMPTY_SHORT_OBJECT_ARRAY, - ArrayUtils.toObject(new short[0])); + array = new long[]{1, 2, 3}; + ArrayUtils.swap(array, 0, -1, 2); + assertEquals(1, array[0]); + assertEquals(2, array[1]); + assertEquals(3, array[2]); - assertArrayEquals(new Short[]{Short.valueOf(Short.MIN_VALUE), Short.valueOf(Short.MAX_VALUE), - Short.valueOf((short) 9999999)}, ArrayUtils.toObject(new short[]{Short.MIN_VALUE, Short.MAX_VALUE, - (short) 9999999})); + array = new long[]{1, 2, 3}; + ArrayUtils.swap(array, -1, -1, 2); + assertEquals(1, array[0]); + assertEquals(2, array[1]); + assertEquals(3, array[2]); } - // testToPrimitive/Object for int - // ----------------------------------------------------------------------- @Test - public void testToPrimitive_int() { - final Integer[] b = null; - assertNull(ArrayUtils.toPrimitive(b)); - assertSame(ArrayUtils.EMPTY_INT_ARRAY, ArrayUtils.toPrimitive(new Integer[0])); - assertArrayEquals(new int[]{Integer.MIN_VALUE, Integer.MAX_VALUE, 9999999}, ArrayUtils.toPrimitive(new Integer[]{Integer.valueOf(Integer.MIN_VALUE), - Integer.valueOf(Integer.MAX_VALUE), Integer.valueOf(9999999)})); - - assertThrows(NullPointerException.class, - () -> ArrayUtils.toPrimitive(new Integer[]{Integer.valueOf(Integer.MIN_VALUE), null})); + public void testSwapNullBooleanArray() { + final boolean[] array = null; + ArrayUtils.swap(array, 0, 2); + assertNull(array); } @Test - public void testToPrimitive_int_int() { - final Long[] l = null; - assertNull(ArrayUtils.toPrimitive(l, Integer.MIN_VALUE)); - assertSame(ArrayUtils.EMPTY_INT_ARRAY, - ArrayUtils.toPrimitive(new Integer[0], 1)); - assertArrayEquals(new int[]{Integer.MIN_VALUE, Integer.MAX_VALUE, 9999999}, ArrayUtils.toPrimitive(new Integer[]{Integer.valueOf(Integer.MIN_VALUE), - Integer.valueOf(Integer.MAX_VALUE), Integer.valueOf(9999999)}, 1)); - assertArrayEquals(new int[]{Integer.MIN_VALUE, Integer.MAX_VALUE, 9999999}, ArrayUtils.toPrimitive(new Integer[]{Integer.valueOf(Integer.MIN_VALUE), - null, Integer.valueOf(9999999)}, Integer.MAX_VALUE)); + public void testSwapNullByteArray() { + final byte[] array = null; + ArrayUtils.swap(array, 0, 2); + assertNull(array); } @Test - public void testToPrimitive_intNull() { - final Integer[] iArray = null; - assertNull(ArrayUtils.toPrimitive(iArray, Integer.MIN_VALUE)); + public void testSwapNullCharArray() { + final char[] array = null; + ArrayUtils.swap(array, 0, 2); + assertNull(array); } @Test - public void testToObject_int() { - final int[] b = null; - assertArrayEquals(null, ArrayUtils.toObject(b)); - - assertSame( - ArrayUtils.EMPTY_INTEGER_OBJECT_ARRAY, - ArrayUtils.toObject(new int[0])); - - assertArrayEquals(new Integer[]{ - Integer.valueOf(Integer.MIN_VALUE), - Integer.valueOf(Integer.MAX_VALUE), - Integer.valueOf(9999999)}, ArrayUtils.toObject( - new int[]{Integer.MIN_VALUE, Integer.MAX_VALUE, 9999999})); + public void testSwapNullDoubleArray() { + final double[] array = null; + ArrayUtils.swap(array, 0, 2); + assertNull(array); } - // testToPrimitive/Object for long - // ----------------------------------------------------------------------- @Test - public void testToPrimitive_long() { - final Long[] b = null; - assertNull(ArrayUtils.toPrimitive(b)); - - assertSame(ArrayUtils.EMPTY_LONG_ARRAY, - ArrayUtils.toPrimitive(new Long[0])); - - assertArrayEquals(new long[]{Long.MIN_VALUE, Long.MAX_VALUE, 9999999}, ArrayUtils.toPrimitive(new Long[]{Long.valueOf(Long.MIN_VALUE), - Long.valueOf(Long.MAX_VALUE), Long.valueOf(9999999)})); - - assertThrows(NullPointerException.class, - () -> ArrayUtils.toPrimitive(new Long[]{Long.valueOf(Long.MIN_VALUE), null})); + public void testSwapNullFloatArray() { + final float[] array = null; + ArrayUtils.swap(array, 0, 2); + assertNull(array); } @Test - public void testToPrimitive_long_long() { - final Long[] l = null; - assertNull(ArrayUtils.toPrimitive(l, Long.MIN_VALUE)); - - assertSame(ArrayUtils.EMPTY_LONG_ARRAY, - ArrayUtils.toPrimitive(new Long[0], 1)); - - assertArrayEquals(new long[]{Long.MIN_VALUE, Long.MAX_VALUE, 9999999}, ArrayUtils.toPrimitive(new Long[]{Long.valueOf(Long.MIN_VALUE), - Long.valueOf(Long.MAX_VALUE), Long.valueOf(9999999)}, 1)); - - assertArrayEquals(new long[]{Long.MIN_VALUE, Long.MAX_VALUE, 9999999}, ArrayUtils.toPrimitive(new Long[]{Long.valueOf(Long.MIN_VALUE), - null, Long.valueOf(9999999)}, Long.MAX_VALUE)); + public void testSwapNullIntArray() { + final int[] array = null; + ArrayUtils.swap(array, 0, 2); + assertNull(array); } @Test - public void testToObject_long() { - final long[] b = null; - assertArrayEquals(null, ArrayUtils.toObject(b)); - - assertSame( - ArrayUtils.EMPTY_LONG_OBJECT_ARRAY, - ArrayUtils.toObject(new long[0])); - - assertArrayEquals(new Long[]{ - Long.valueOf(Long.MIN_VALUE), - Long.valueOf(Long.MAX_VALUE), - Long.valueOf(9999999)}, ArrayUtils.toObject( - new long[]{Long.MIN_VALUE, Long.MAX_VALUE, 9999999})); + public void testSwapNullLongArray() { + final long[] array = null; + ArrayUtils.swap(array, 0, 2); + assertNull(array); } - // testToPrimitive/Object for float - // ----------------------------------------------------------------------- @Test - public void testToPrimitive_float() { - final Float[] b = null; - assertNull(ArrayUtils.toPrimitive(b)); - - assertSame(ArrayUtils.EMPTY_FLOAT_ARRAY, - ArrayUtils.toPrimitive(new Float[0])); - - assertArrayEquals(new float[]{Float.MIN_VALUE, Float.MAX_VALUE, 9999999}, ArrayUtils.toPrimitive(new Float[]{Float.valueOf(Float.MIN_VALUE), - Float.valueOf(Float.MAX_VALUE), Float.valueOf(9999999)})); - - assertThrows(NullPointerException.class, - () -> ArrayUtils.toPrimitive(new Float[]{Float.valueOf(Float.MIN_VALUE), null})); + public void testSwapNullObjectArray() { + final String[] array = null; + ArrayUtils.swap(array, 0, 2); + assertNull(array); } @Test - public void testToPrimitive_float_float() { - final Float[] l = null; - assertNull(ArrayUtils.toPrimitive(l, Float.MIN_VALUE)); - - assertSame(ArrayUtils.EMPTY_FLOAT_ARRAY, - ArrayUtils.toPrimitive(new Float[0], 1)); - - assertArrayEquals(new float[]{Float.MIN_VALUE, Float.MAX_VALUE, 9999999}, ArrayUtils.toPrimitive(new Float[]{Float.valueOf(Float.MIN_VALUE), - Float.valueOf(Float.MAX_VALUE), Float.valueOf(9999999)}, 1)); - - assertArrayEquals(new float[]{Float.MIN_VALUE, Float.MAX_VALUE, 9999999}, ArrayUtils.toPrimitive(new Float[]{Float.valueOf(Float.MIN_VALUE), - null, Float.valueOf(9999999)}, Float.MAX_VALUE)); + public void testSwapNullShortArray() { + final short[] array = null; + ArrayUtils.swap(array, 0, 2); + assertNull(array); } @Test - public void testToObject_float() { - final float[] b = null; - assertArrayEquals(null, ArrayUtils.toObject(b)); - - assertSame( - ArrayUtils.EMPTY_FLOAT_OBJECT_ARRAY, - ArrayUtils.toObject(new float[0])); - - assertArrayEquals(new Float[]{ - Float.valueOf(Float.MIN_VALUE), - Float.valueOf(Float.MAX_VALUE), - Float.valueOf(9999999)}, ArrayUtils.toObject( - new float[]{Float.MIN_VALUE, Float.MAX_VALUE, 9999999})); + public void testSwapObject() { + final String[] array = new String[]{"1", "2", "3"}; + ArrayUtils.swap(array, 0, 2); + assertEquals("3", array[0]); + assertEquals("2", array[1]); + assertEquals("1", array[2]); } - // testToPrimitive/Object for double - // ----------------------------------------------------------------------- @Test - public void testToPrimitive_double() { - final Double[] b = null; - assertNull(ArrayUtils.toPrimitive(b)); + public void testSwapObjectRange() { + String[] array = new String[]{"1", "2", "3", "4"}; + ArrayUtils.swap(array, 0, 2, 2); + assertEquals("3", array[0]); + assertEquals("4", array[1]); + assertEquals("1", array[2]); + assertEquals("2", array[3]); - assertSame(ArrayUtils.EMPTY_DOUBLE_ARRAY, - ArrayUtils.toPrimitive(new Double[0])); + array = new String[]{"1", "2", "3", "4"}; + ArrayUtils.swap(array, -1, 2, 3); + assertEquals("3", array[0]); + assertEquals("4", array[1]); + assertEquals("1", array[2]); + assertEquals("2", array[3]); - assertArrayEquals(new double[]{Double.MIN_VALUE, Double.MAX_VALUE, 9999999}, ArrayUtils.toPrimitive(new Double[]{Double.valueOf(Double.MIN_VALUE), - Double.valueOf(Double.MAX_VALUE), Double.valueOf(9999999)})); + array = new String[]{"1", "2", "3", "4", "5"}; + ArrayUtils.swap(array, -3, 2, 3); + assertEquals("3", array[0]); + assertEquals("4", array[1]); + assertEquals("5", array[2]); + assertEquals("2", array[3]); + assertEquals("1", array[4]); - assertThrows(NullPointerException.class, - () -> ArrayUtils.toPrimitive(new Float[]{Float.valueOf(Float.MIN_VALUE), null})); + array = new String[]{"1", "2", "3", "4", "5"}; + ArrayUtils.swap(array, 2, -2, 3); + assertEquals("3", array[0]); + assertEquals("4", array[1]); + assertEquals("5", array[2]); + assertEquals("2", array[3]); + assertEquals("1", array[4]); + + array = new String[0]; + ArrayUtils.swap(array, 0, 2, 2); + assertEquals(0, array.length); + + array = null; + ArrayUtils.swap(array, 0, 2, 2); + assertNull(array); } @Test - public void testToPrimitive_double_double() { - final Double[] l = null; - assertNull(ArrayUtils.toPrimitive(l, Double.MIN_VALUE)); + public void testSwapShort() { + final short[] array = new short[]{1, 2, 3}; + ArrayUtils.swap(array, 0, 2); + assertEquals(3, array[0]); + assertEquals(2, array[1]); + assertEquals(1, array[2]); + } - assertSame(ArrayUtils.EMPTY_DOUBLE_ARRAY, - ArrayUtils.toPrimitive(new Double[0], 1)); + @Test + public void testSwapShortRange() { + short[] array = new short[]{1, 2, 3, 4}; + ArrayUtils.swap(array, 0, 2, 2); + assertEquals(3, array[0]); + assertEquals(4, array[1]); + assertEquals(1, array[2]); + assertEquals(2, array[3]); - assertArrayEquals(new double[]{Double.MIN_VALUE, Double.MAX_VALUE, 9999999}, ArrayUtils.toPrimitive(new Double[]{Double.valueOf(Double.MIN_VALUE), - Double.valueOf(Double.MAX_VALUE), Double.valueOf(9999999)}, 1)); + array = new short[]{1, 2, 3}; + ArrayUtils.swap(array, 3, 0); + assertEquals(1, array[0]); + assertEquals(2, array[1]); + assertEquals(3, array[2]); - assertArrayEquals(new double[]{Double.MIN_VALUE, Double.MAX_VALUE, 9999999}, ArrayUtils.toPrimitive(new Double[]{Double.valueOf(Double.MIN_VALUE), - null, Double.valueOf(9999999)}, Double.MAX_VALUE)); - } + array = new short[]{1, 2, 3}; + ArrayUtils.swap(array, 0, 2, 2); + assertEquals(3, array[0]); + assertEquals(2, array[1]); + assertEquals(1, array[2]); - @Test - public void testToObject_double() { - final double[] b = null; - assertArrayEquals(null, ArrayUtils.toObject(b)); + array = new short[]{1, 2, 3}; + ArrayUtils.swap(array, -1, 2, 2); + assertEquals(3, array[0]); + assertEquals(2, array[1]); + assertEquals(1, array[2]); - assertSame( - ArrayUtils.EMPTY_DOUBLE_OBJECT_ARRAY, - ArrayUtils.toObject(new double[0])); + array = new short[]{1, 2, 3}; + ArrayUtils.swap(array, 0, -1, 2); + assertEquals(1, array[0]); + assertEquals(2, array[1]); + assertEquals(3, array[2]); - assertArrayEquals(new Double[]{ - Double.valueOf(Double.MIN_VALUE), - Double.valueOf(Double.MAX_VALUE), - Double.valueOf(9999999)}, ArrayUtils.toObject( - new double[]{Double.MIN_VALUE, Double.MAX_VALUE, 9999999})); + array = new short[]{1, 2, 3}; + ArrayUtils.swap(array, -1, -1, 2); + assertEquals(1, array[0]); + assertEquals(2, array[1]); + assertEquals(3, array[2]); } //----------------------------------------------------------------------- - - /** - * Test for {@link ArrayUtils#isEmpty(java.lang.Object[])}. - */ @Test - public void testIsEmptyObject() { - final Object[] emptyArray = new Object[]{}; - final Object[] notEmptyArray = new Object[]{new String("Value")}; - assertTrue(ArrayUtils.isEmpty((Object[]) null)); - assertTrue(ArrayUtils.isEmpty(emptyArray)); - assertFalse(ArrayUtils.isEmpty(notEmptyArray)); - } + public void testToMap() { + Map map = ArrayUtils.toMap(new String[][]{{"foo", "bar"}, {"hello", "world"}}); - /** - * Tests for {@link ArrayUtils#isEmpty(long[])}, - * {@link ArrayUtils#isEmpty(int[])}, - * {@link ArrayUtils#isEmpty(short[])}, - * {@link ArrayUtils#isEmpty(char[])}, - * {@link ArrayUtils#isEmpty(byte[])}, - * {@link ArrayUtils#isEmpty(double[])}, - * {@link ArrayUtils#isEmpty(float[])} and - * {@link ArrayUtils#isEmpty(boolean[])}. - */ - @Test - public void testIsEmptyPrimitives() { - final long[] emptyLongArray = new long[]{}; - final long[] notEmptyLongArray = new long[]{1L}; - assertTrue(ArrayUtils.isEmpty((long[]) null)); - assertTrue(ArrayUtils.isEmpty(emptyLongArray)); - assertFalse(ArrayUtils.isEmpty(notEmptyLongArray)); + assertEquals("bar", map.get("foo")); + assertEquals("world", map.get("hello")); - final int[] emptyIntArray = new int[]{}; - final int[] notEmptyIntArray = new int[]{1}; - assertTrue(ArrayUtils.isEmpty((int[]) null)); - assertTrue(ArrayUtils.isEmpty(emptyIntArray)); - assertFalse(ArrayUtils.isEmpty(notEmptyIntArray)); + assertNull(ArrayUtils.toMap(null)); + assertThrows(IllegalArgumentException.class, () -> + ArrayUtils.toMap(new String[][]{{"foo", "bar"}, {"short"}})); + assertThrows(IllegalArgumentException.class, () -> + ArrayUtils.toMap(new Object[]{new Object[]{"foo", "bar"}, "illegal type"})); + assertThrows(IllegalArgumentException.class, () -> + ArrayUtils.toMap(new Object[]{new Object[]{"foo", "bar"}, null})); - final short[] emptyShortArray = new short[]{}; - final short[] notEmptyShortArray = new short[]{1}; - assertTrue(ArrayUtils.isEmpty((short[]) null)); - assertTrue(ArrayUtils.isEmpty(emptyShortArray)); - assertFalse(ArrayUtils.isEmpty(notEmptyShortArray)); + map = ArrayUtils.toMap(new Object[]{new Map.Entry() { + @Override + public boolean equals(final Object o) { + throw new UnsupportedOperationException(); + } - final char[] emptyCharArray = new char[]{}; - final char[] notEmptyCharArray = new char[]{1}; - assertTrue(ArrayUtils.isEmpty((char[]) null)); - assertTrue(ArrayUtils.isEmpty(emptyCharArray)); - assertFalse(ArrayUtils.isEmpty(notEmptyCharArray)); + @Override + public Object getKey() { + return "foo"; + } - final byte[] emptyByteArray = new byte[]{}; - final byte[] notEmptyByteArray = new byte[]{1}; - assertTrue(ArrayUtils.isEmpty((byte[]) null)); - assertTrue(ArrayUtils.isEmpty(emptyByteArray)); - assertFalse(ArrayUtils.isEmpty(notEmptyByteArray)); + @Override + public Object getValue() { + return "bar"; + } - final double[] emptyDoubleArray = new double[]{}; - final double[] notEmptyDoubleArray = new double[]{1.0}; - assertTrue(ArrayUtils.isEmpty((double[]) null)); - assertTrue(ArrayUtils.isEmpty(emptyDoubleArray)); - assertFalse(ArrayUtils.isEmpty(notEmptyDoubleArray)); + @Override + public int hashCode() { + throw new UnsupportedOperationException(); + } - final float[] emptyFloatArray = new float[]{}; - final float[] notEmptyFloatArray = new float[]{1.0F}; - assertTrue(ArrayUtils.isEmpty((float[]) null)); - assertTrue(ArrayUtils.isEmpty(emptyFloatArray)); - assertFalse(ArrayUtils.isEmpty(notEmptyFloatArray)); + @Override + public Object setValue(final Object value) { + throw new UnsupportedOperationException(); + } + }}); + assertEquals("bar", map.get("foo")); - final boolean[] emptyBooleanArray = new boolean[]{}; - final boolean[] notEmptyBooleanArray = new boolean[]{true}; - assertTrue(ArrayUtils.isEmpty((boolean[]) null)); - assertTrue(ArrayUtils.isEmpty(emptyBooleanArray)); - assertFalse(ArrayUtils.isEmpty(notEmptyBooleanArray)); + // Return empty map when got input array with length = 0 + assertEquals(Collections.emptyMap(), ArrayUtils.toMap(new Object[0])); + + // Test all null values + map = ArrayUtils.toMap(new Object[][] { {null, null}, {null, null} }); + assertEquals(Collections.singletonMap(null, null), map); + + // Test duplicate keys + map = ArrayUtils.toMap(new Object[][] { {"key", "value2"}, {"key", "value1"} }); + assertEquals(Collections.singletonMap("key", "value1"), map); } - /** - * Test for {@link ArrayUtils#isNotEmpty(java.lang.Object[])}. - */ + //----------------------------------------------------------------------- + @Test - public void testIsNotEmptyObject() { - final Object[] emptyArray = new Object[]{}; - final Object[] notEmptyArray = new Object[]{new String("Value")}; - assertFalse(ArrayUtils.isNotEmpty((Object[]) null)); - assertFalse(ArrayUtils.isNotEmpty(emptyArray)); - assertTrue(ArrayUtils.isNotEmpty(notEmptyArray)); + public void testToObject_boolean() { + final boolean[] b = null; + assertArrayEquals(null, ArrayUtils.toObject(b)); + assertSame(ArrayUtils.EMPTY_BOOLEAN_OBJECT_ARRAY, ArrayUtils.toObject(new boolean[0])); + assertArrayEquals(new Boolean[]{Boolean.TRUE, Boolean.FALSE, Boolean.TRUE}, ArrayUtils.toObject(new boolean[]{true, false, true})); } - /** - * Tests for {@link ArrayUtils#isNotEmpty(long[])}, - * {@link ArrayUtils#isNotEmpty(int[])}, - * {@link ArrayUtils#isNotEmpty(short[])}, - * {@link ArrayUtils#isNotEmpty(char[])}, - * {@link ArrayUtils#isNotEmpty(byte[])}, - * {@link ArrayUtils#isNotEmpty(double[])}, - * {@link ArrayUtils#isNotEmpty(float[])} and - * {@link ArrayUtils#isNotEmpty(boolean[])}. - */ @Test - public void testIsNotEmptyPrimitives() { - final long[] emptyLongArray = new long[]{}; - final long[] notEmptyLongArray = new long[]{1L}; - assertFalse(ArrayUtils.isNotEmpty((long[]) null)); - assertFalse(ArrayUtils.isNotEmpty(emptyLongArray)); - assertTrue(ArrayUtils.isNotEmpty(notEmptyLongArray)); - - final int[] emptyIntArray = new int[]{}; - final int[] notEmptyIntArray = new int[]{1}; - assertFalse(ArrayUtils.isNotEmpty((int[]) null)); - assertFalse(ArrayUtils.isNotEmpty(emptyIntArray)); - assertTrue(ArrayUtils.isNotEmpty(notEmptyIntArray)); - - final short[] emptyShortArray = new short[]{}; - final short[] notEmptyShortArray = new short[]{1}; - assertFalse(ArrayUtils.isNotEmpty((short[]) null)); - assertFalse(ArrayUtils.isNotEmpty(emptyShortArray)); - assertTrue(ArrayUtils.isNotEmpty(notEmptyShortArray)); + public void testToObject_byte() { + final byte[] b = null; + assertArrayEquals(null, ArrayUtils.toObject(b)); - final char[] emptyCharArray = new char[]{}; - final char[] notEmptyCharArray = new char[]{1}; - assertFalse(ArrayUtils.isNotEmpty((char[]) null)); - assertFalse(ArrayUtils.isNotEmpty(emptyCharArray)); - assertTrue(ArrayUtils.isNotEmpty(notEmptyCharArray)); + assertSame(ArrayUtils.EMPTY_BYTE_OBJECT_ARRAY, + ArrayUtils.toObject(new byte[0])); - final byte[] emptyByteArray = new byte[]{}; - final byte[] notEmptyByteArray = new byte[]{1}; - assertFalse(ArrayUtils.isNotEmpty((byte[]) null)); - assertFalse(ArrayUtils.isNotEmpty(emptyByteArray)); - assertTrue(ArrayUtils.isNotEmpty(notEmptyByteArray)); + assertArrayEquals(new Byte[]{Byte.valueOf(Byte.MIN_VALUE), + Byte.valueOf(Byte.MAX_VALUE), Byte.valueOf((byte) 9999999)}, ArrayUtils.toObject(new byte[]{Byte.MIN_VALUE, Byte.MAX_VALUE, + (byte) 9999999})); + } - final double[] emptyDoubleArray = new double[]{}; - final double[] notEmptyDoubleArray = new double[]{1.0}; - assertFalse(ArrayUtils.isNotEmpty((double[]) null)); - assertFalse(ArrayUtils.isNotEmpty(emptyDoubleArray)); - assertTrue(ArrayUtils.isNotEmpty(notEmptyDoubleArray)); + @Test + public void testToObject_char() { + final char[] b = null; + assertArrayEquals(null, ArrayUtils.toObject(b)); - final float[] emptyFloatArray = new float[]{}; - final float[] notEmptyFloatArray = new float[]{1.0F}; - assertFalse(ArrayUtils.isNotEmpty((float[]) null)); - assertFalse(ArrayUtils.isNotEmpty(emptyFloatArray)); - assertTrue(ArrayUtils.isNotEmpty(notEmptyFloatArray)); + assertSame(ArrayUtils.EMPTY_CHARACTER_OBJECT_ARRAY, + ArrayUtils.toObject(new char[0])); - final boolean[] emptyBooleanArray = new boolean[]{}; - final boolean[] notEmptyBooleanArray = new boolean[]{true}; - assertFalse(ArrayUtils.isNotEmpty((boolean[]) null)); - assertFalse(ArrayUtils.isNotEmpty(emptyBooleanArray)); - assertTrue(ArrayUtils.isNotEmpty(notEmptyBooleanArray)); + assertArrayEquals(new Character[]{Character.valueOf(Character.MIN_VALUE), + Character.valueOf(Character.MAX_VALUE), Character.valueOf('0')}, ArrayUtils.toObject(new char[]{Character.MIN_VALUE, Character.MAX_VALUE, + '0'})); } - // ------------------------------------------------------------------------ @Test - public void testGetLength() { - assertEquals(0, ArrayUtils.getLength(null)); - - final Object[] emptyObjectArray = new Object[0]; - final Object[] notEmptyObjectArray = new Object[]{"aValue"}; - assertEquals(0, ArrayUtils.getLength(null)); - assertEquals(0, ArrayUtils.getLength(emptyObjectArray)); - assertEquals(1, ArrayUtils.getLength(notEmptyObjectArray)); + public void testToObject_double() { + final double[] b = null; + assertArrayEquals(null, ArrayUtils.toObject(b)); - final int[] emptyIntArray = new int[]{}; - final int[] notEmptyIntArray = new int[]{1}; - assertEquals(0, ArrayUtils.getLength(null)); - assertEquals(0, ArrayUtils.getLength(emptyIntArray)); - assertEquals(1, ArrayUtils.getLength(notEmptyIntArray)); + assertSame( + ArrayUtils.EMPTY_DOUBLE_OBJECT_ARRAY, + ArrayUtils.toObject(new double[0])); - final short[] emptyShortArray = new short[]{}; - final short[] notEmptyShortArray = new short[]{1}; - assertEquals(0, ArrayUtils.getLength(null)); - assertEquals(0, ArrayUtils.getLength(emptyShortArray)); - assertEquals(1, ArrayUtils.getLength(notEmptyShortArray)); + assertArrayEquals(new Double[]{ + Double.valueOf(Double.MIN_VALUE), + Double.valueOf(Double.MAX_VALUE), + Double.valueOf(9999999)}, ArrayUtils.toObject( + new double[]{Double.MIN_VALUE, Double.MAX_VALUE, 9999999})); + } - final char[] emptyCharArray = new char[]{}; - final char[] notEmptyCharArray = new char[]{1}; - assertEquals(0, ArrayUtils.getLength(null)); - assertEquals(0, ArrayUtils.getLength(emptyCharArray)); - assertEquals(1, ArrayUtils.getLength(notEmptyCharArray)); + @Test + public void testToObject_float() { + final float[] b = null; + assertArrayEquals(null, ArrayUtils.toObject(b)); - final byte[] emptyByteArray = new byte[]{}; - final byte[] notEmptyByteArray = new byte[]{1}; - assertEquals(0, ArrayUtils.getLength(null)); - assertEquals(0, ArrayUtils.getLength(emptyByteArray)); - assertEquals(1, ArrayUtils.getLength(notEmptyByteArray)); + assertSame( + ArrayUtils.EMPTY_FLOAT_OBJECT_ARRAY, + ArrayUtils.toObject(new float[0])); - final double[] emptyDoubleArray = new double[]{}; - final double[] notEmptyDoubleArray = new double[]{1.0}; - assertEquals(0, ArrayUtils.getLength(null)); - assertEquals(0, ArrayUtils.getLength(emptyDoubleArray)); - assertEquals(1, ArrayUtils.getLength(notEmptyDoubleArray)); + assertArrayEquals(new Float[]{ + Float.valueOf(Float.MIN_VALUE), + Float.valueOf(Float.MAX_VALUE), + Float.valueOf(9999999)}, ArrayUtils.toObject( + new float[]{Float.MIN_VALUE, Float.MAX_VALUE, 9999999})); + } - final float[] emptyFloatArray = new float[]{}; - final float[] notEmptyFloatArray = new float[]{1.0F}; - assertEquals(0, ArrayUtils.getLength(null)); - assertEquals(0, ArrayUtils.getLength(emptyFloatArray)); - assertEquals(1, ArrayUtils.getLength(notEmptyFloatArray)); + @Test + public void testToObject_int() { + final int[] b = null; + assertArrayEquals(null, ArrayUtils.toObject(b)); - final boolean[] emptyBooleanArray = new boolean[]{}; - final boolean[] notEmptyBooleanArray = new boolean[]{true}; - assertEquals(0, ArrayUtils.getLength(null)); - assertEquals(0, ArrayUtils.getLength(emptyBooleanArray)); - assertEquals(1, ArrayUtils.getLength(notEmptyBooleanArray)); + assertSame( + ArrayUtils.EMPTY_INTEGER_OBJECT_ARRAY, + ArrayUtils.toObject(new int[0])); - assertThrows(IllegalArgumentException.class, () -> ArrayUtils.getLength("notAnArray")); + assertArrayEquals(new Integer[]{ + Integer.valueOf(Integer.MIN_VALUE), + Integer.valueOf(Integer.MAX_VALUE), + Integer.valueOf(9999999)}, ArrayUtils.toObject( + new int[]{Integer.MIN_VALUE, Integer.MAX_VALUE, 9999999})); } @Test - public void testIsSorted() { - Integer[] array = null; - assertTrue(ArrayUtils.isSorted(array)); - - array = new Integer[]{1}; - assertTrue(ArrayUtils.isSorted(array)); + public void testToObject_long() { + final long[] b = null; + assertArrayEquals(null, ArrayUtils.toObject(b)); - array = new Integer[]{1, 2, 3}; - assertTrue(ArrayUtils.isSorted(array)); + assertSame( + ArrayUtils.EMPTY_LONG_OBJECT_ARRAY, + ArrayUtils.toObject(new long[0])); - array = new Integer[]{1, 3, 2}; - assertFalse(ArrayUtils.isSorted(array)); + assertArrayEquals(new Long[]{ + Long.valueOf(Long.MIN_VALUE), + Long.valueOf(Long.MAX_VALUE), + Long.valueOf(9999999)}, ArrayUtils.toObject( + new long[]{Long.MIN_VALUE, Long.MAX_VALUE, 9999999})); } @Test - public void testIsSortedComparator() { - final Comparator c = (o1, o2) -> o2.compareTo(o1); + public void testToObject_short() { + final short[] b = null; + assertArrayEquals(null, ArrayUtils.toObject(b)); - Integer[] array = null; - assertTrue(ArrayUtils.isSorted(array, c)); + assertSame(ArrayUtils.EMPTY_SHORT_OBJECT_ARRAY, + ArrayUtils.toObject(new short[0])); - array = new Integer[]{1}; - assertTrue(ArrayUtils.isSorted(array, c)); + assertArrayEquals(new Short[]{Short.valueOf(Short.MIN_VALUE), Short.valueOf(Short.MAX_VALUE), + Short.valueOf((short) 9999999)}, ArrayUtils.toObject(new short[]{Short.MIN_VALUE, Short.MAX_VALUE, + (short) 9999999})); + } - array = new Integer[]{3, 2, 1}; - assertTrue(ArrayUtils.isSorted(array, c)); + // testToPrimitive/Object for boolean + // ----------------------------------------------------------------------- + @Test + public void testToPrimitive_boolean() { + final Boolean[] b = null; + assertNull(ArrayUtils.toPrimitive(b)); + assertSame(ArrayUtils.EMPTY_BOOLEAN_ARRAY, ArrayUtils.toPrimitive(new Boolean[0])); + assertArrayEquals(new boolean[]{true, false, true}, ArrayUtils.toPrimitive(new Boolean[]{Boolean.TRUE, Boolean.FALSE, Boolean.TRUE})); - array = new Integer[]{1, 3, 2}; - assertFalse(ArrayUtils.isSorted(array, c)); + assertThrows(NullPointerException.class, () -> ArrayUtils.toPrimitive(new Boolean[]{Boolean.TRUE, null})); } @Test - public void testIsSortedNullComparator() { - assertThrows(IllegalArgumentException.class, () -> ArrayUtils.isSorted(null, null)); + public void testToPrimitive_boolean_boolean() { + assertNull(ArrayUtils.toPrimitive(null, false)); + assertSame(ArrayUtils.EMPTY_BOOLEAN_ARRAY, ArrayUtils.toPrimitive(new Boolean[0], false)); + assertArrayEquals(new boolean[]{true, false, true}, ArrayUtils.toPrimitive(new Boolean[]{Boolean.TRUE, Boolean.FALSE, Boolean.TRUE}, false)); + assertArrayEquals(new boolean[]{true, false, false}, ArrayUtils.toPrimitive(new Boolean[]{Boolean.TRUE, null, Boolean.FALSE}, false)); + assertArrayEquals(new boolean[]{true, true, false}, ArrayUtils.toPrimitive(new Boolean[]{Boolean.TRUE, null, Boolean.FALSE}, true)); } + // testToPrimitive/Object for byte + // ----------------------------------------------------------------------- @Test - public void testIsSortedInt() { - int[] array = null; - assertTrue(ArrayUtils.isSorted(array)); + public void testToPrimitive_byte() { + final Byte[] b = null; + assertNull(ArrayUtils.toPrimitive(b)); - array = new int[]{1}; - assertTrue(ArrayUtils.isSorted(array)); + assertSame(ArrayUtils.EMPTY_BYTE_ARRAY, ArrayUtils.toPrimitive(new Byte[0])); - array = new int[]{1, 2, 3}; - assertTrue(ArrayUtils.isSorted(array)); + assertArrayEquals(new byte[]{Byte.MIN_VALUE, Byte.MAX_VALUE, (byte) 9999999}, ArrayUtils.toPrimitive(new Byte[]{Byte.valueOf(Byte.MIN_VALUE), + Byte.valueOf(Byte.MAX_VALUE), Byte.valueOf((byte) 9999999)})); - array = new int[]{1, 3, 2}; - assertFalse(ArrayUtils.isSorted(array)); + assertThrows(NullPointerException.class, + () -> ArrayUtils.toPrimitive(new Byte[]{Byte.valueOf(Byte.MIN_VALUE), null})); } @Test - public void testIsSortedFloat() { - float[] array = null; - assertTrue(ArrayUtils.isSorted(array)); + public void testToPrimitive_byte_byte() { + final Byte[] b = null; + assertNull(ArrayUtils.toPrimitive(b, Byte.MIN_VALUE)); - array = new float[]{0f}; - assertTrue(ArrayUtils.isSorted(array)); + assertSame(ArrayUtils.EMPTY_BYTE_ARRAY, + ArrayUtils.toPrimitive(new Byte[0], (byte) 1)); - array = new float[]{-1f, 0f, 0.1f, 0.2f}; - assertTrue(ArrayUtils.isSorted(array)); + assertArrayEquals(new byte[]{Byte.MIN_VALUE, Byte.MAX_VALUE, (byte) 9999999}, ArrayUtils.toPrimitive(new Byte[]{Byte.valueOf(Byte.MIN_VALUE), + Byte.valueOf(Byte.MAX_VALUE), Byte.valueOf((byte) 9999999)}, + Byte.MIN_VALUE)); - array = new float[]{-1f, 0.2f, 0.1f, 0f}; - assertFalse(ArrayUtils.isSorted(array)); + assertArrayEquals(new byte[]{Byte.MIN_VALUE, Byte.MAX_VALUE, (byte) 9999999}, ArrayUtils.toPrimitive(new Byte[]{Byte.valueOf(Byte.MIN_VALUE), null, + Byte.valueOf((byte) 9999999)}, Byte.MAX_VALUE)); } + // testToPrimitive/Object for byte + // ----------------------------------------------------------------------- @Test - public void testIsSortedLong() { - long[] array = null; - assertTrue(ArrayUtils.isSorted(array)); + public void testToPrimitive_char() { + final Character[] b = null; + assertNull(ArrayUtils.toPrimitive(b)); - array = new long[]{0L}; - assertTrue(ArrayUtils.isSorted(array)); + assertSame(ArrayUtils.EMPTY_CHAR_ARRAY, ArrayUtils.toPrimitive(new Character[0])); - array = new long[]{-1L, 0L, 1L}; - assertTrue(ArrayUtils.isSorted(array)); + assertArrayEquals(new char[]{Character.MIN_VALUE, Character.MAX_VALUE, '0'}, ArrayUtils.toPrimitive(new Character[]{Character.valueOf(Character.MIN_VALUE), + Character.valueOf(Character.MAX_VALUE), Character.valueOf('0')})); - array = new long[]{-1L, 1L, 0L}; - assertFalse(ArrayUtils.isSorted(array)); + assertThrows(NullPointerException.class, + () -> ArrayUtils.toPrimitive(new Character[]{Character.valueOf(Character.MIN_VALUE), null})); } @Test - public void testIsSortedDouble() { - double[] array = null; - assertTrue(ArrayUtils.isSorted(array)); + public void testToPrimitive_char_char() { + final Character[] b = null; + assertNull(ArrayUtils.toPrimitive(b, Character.MIN_VALUE)); - array = new double[]{0.0}; - assertTrue(ArrayUtils.isSorted(array)); + assertSame(ArrayUtils.EMPTY_CHAR_ARRAY, + ArrayUtils.toPrimitive(new Character[0], (char) 0)); - array = new double[]{-1.0, 0.0, 0.1, 0.2}; - assertTrue(ArrayUtils.isSorted(array)); + assertArrayEquals(new char[]{Character.MIN_VALUE, Character.MAX_VALUE, '0'}, ArrayUtils.toPrimitive(new Character[]{Character.valueOf(Character.MIN_VALUE), + Character.valueOf(Character.MAX_VALUE), Character.valueOf('0')}, + Character.MIN_VALUE)); - array = new double[]{-1.0, 0.2, 0.1, 0.0}; - assertFalse(ArrayUtils.isSorted(array)); + assertArrayEquals(new char[]{Character.MIN_VALUE, Character.MAX_VALUE, '0'}, ArrayUtils.toPrimitive(new Character[]{Character.valueOf(Character.MIN_VALUE), null, + Character.valueOf('0')}, Character.MAX_VALUE)); } + // testToPrimitive/Object for double + // ----------------------------------------------------------------------- @Test - public void testIsSortedChar() { - char[] array = null; - assertTrue(ArrayUtils.isSorted(array)); + public void testToPrimitive_double() { + final Double[] b = null; + assertNull(ArrayUtils.toPrimitive(b)); - array = new char[]{'a'}; - assertTrue(ArrayUtils.isSorted(array)); + assertSame(ArrayUtils.EMPTY_DOUBLE_ARRAY, + ArrayUtils.toPrimitive(new Double[0])); - array = new char[]{'a', 'b', 'c'}; - assertTrue(ArrayUtils.isSorted(array)); + assertArrayEquals(new double[]{Double.MIN_VALUE, Double.MAX_VALUE, 9999999}, ArrayUtils.toPrimitive(new Double[]{Double.valueOf(Double.MIN_VALUE), + Double.valueOf(Double.MAX_VALUE), Double.valueOf(9999999)})); - array = new char[]{'a', 'c', 'b'}; - assertFalse(ArrayUtils.isSorted(array)); + assertThrows(NullPointerException.class, + () -> ArrayUtils.toPrimitive(new Float[]{Float.valueOf(Float.MIN_VALUE), null})); } @Test - public void testIsSortedByte() { - byte[] array = null; - assertTrue(ArrayUtils.isSorted(array)); + public void testToPrimitive_double_double() { + final Double[] l = null; + assertNull(ArrayUtils.toPrimitive(l, Double.MIN_VALUE)); - array = new byte[]{0x10}; - assertTrue(ArrayUtils.isSorted(array)); + assertSame(ArrayUtils.EMPTY_DOUBLE_ARRAY, + ArrayUtils.toPrimitive(new Double[0], 1)); - array = new byte[]{0x10, 0x20, 0x30}; - assertTrue(ArrayUtils.isSorted(array)); + assertArrayEquals(new double[]{Double.MIN_VALUE, Double.MAX_VALUE, 9999999}, ArrayUtils.toPrimitive(new Double[]{Double.valueOf(Double.MIN_VALUE), + Double.valueOf(Double.MAX_VALUE), Double.valueOf(9999999)}, 1)); - array = new byte[]{0x10, 0x30, 0x20}; - assertFalse(ArrayUtils.isSorted(array)); + assertArrayEquals(new double[]{Double.MIN_VALUE, Double.MAX_VALUE, 9999999}, ArrayUtils.toPrimitive(new Double[]{Double.valueOf(Double.MIN_VALUE), + null, Double.valueOf(9999999)}, Double.MAX_VALUE)); } + // testToPrimitive/Object for float + // ----------------------------------------------------------------------- @Test - public void testIsSortedShort() { - short[] array = null; - assertTrue(ArrayUtils.isSorted(array)); + public void testToPrimitive_float() { + final Float[] b = null; + assertNull(ArrayUtils.toPrimitive(b)); - array = new short[]{0}; - assertTrue(ArrayUtils.isSorted(array)); + assertSame(ArrayUtils.EMPTY_FLOAT_ARRAY, + ArrayUtils.toPrimitive(new Float[0])); - array = new short[]{-1, 0, 1}; - assertTrue(ArrayUtils.isSorted(array)); + assertArrayEquals(new float[]{Float.MIN_VALUE, Float.MAX_VALUE, 9999999}, ArrayUtils.toPrimitive(new Float[]{Float.valueOf(Float.MIN_VALUE), + Float.valueOf(Float.MAX_VALUE), Float.valueOf(9999999)})); - array = new short[]{-1, 1, 0}; - assertFalse(ArrayUtils.isSorted(array)); + assertThrows(NullPointerException.class, + () -> ArrayUtils.toPrimitive(new Float[]{Float.valueOf(Float.MIN_VALUE), null})); } @Test - public void testIsSortedBool() { - boolean[] array = null; - assertTrue(ArrayUtils.isSorted(array)); + public void testToPrimitive_float_float() { + final Float[] l = null; + assertNull(ArrayUtils.toPrimitive(l, Float.MIN_VALUE)); - array = new boolean[]{true}; - assertTrue(ArrayUtils.isSorted(array)); + assertSame(ArrayUtils.EMPTY_FLOAT_ARRAY, + ArrayUtils.toPrimitive(new Float[0], 1)); - array = new boolean[]{false, true}; - assertTrue(ArrayUtils.isSorted(array)); + assertArrayEquals(new float[]{Float.MIN_VALUE, Float.MAX_VALUE, 9999999}, ArrayUtils.toPrimitive(new Float[]{Float.valueOf(Float.MIN_VALUE), + Float.valueOf(Float.MAX_VALUE), Float.valueOf(9999999)}, 1)); - array = new boolean[]{true, false}; - assertFalse(ArrayUtils.isSorted(array)); + assertArrayEquals(new float[]{Float.MIN_VALUE, Float.MAX_VALUE, 9999999}, ArrayUtils.toPrimitive(new Float[]{Float.valueOf(Float.MIN_VALUE), + null, Float.valueOf(9999999)}, Float.MAX_VALUE)); } + // testToPrimitive/Object for int + // ----------------------------------------------------------------------- @Test - public void testCreatePrimitiveArray() { - assertNull(ArrayUtils.toPrimitive((Object[]) null)); - assertArrayEquals(new int[]{}, ArrayUtils.toPrimitive(new Integer[]{})); - assertArrayEquals(new short[]{2}, ArrayUtils.toPrimitive(new Short[]{2})); - assertArrayEquals(new long[]{2, 3}, ArrayUtils.toPrimitive(new Long[]{2L, 3L})); - assertArrayEquals(new float[]{3.14f}, ArrayUtils.toPrimitive(new Float[]{3.14f}), 0.1f); - assertArrayEquals(new double[]{2.718}, ArrayUtils.toPrimitive(new Double[]{2.718}), 0.1); + public void testToPrimitive_int() { + final Integer[] b = null; + assertNull(ArrayUtils.toPrimitive(b)); + assertSame(ArrayUtils.EMPTY_INT_ARRAY, ArrayUtils.toPrimitive(new Integer[0])); + assertArrayEquals(new int[]{Integer.MIN_VALUE, Integer.MAX_VALUE, 9999999}, ArrayUtils.toPrimitive(new Integer[]{Integer.valueOf(Integer.MIN_VALUE), + Integer.valueOf(Integer.MAX_VALUE), Integer.valueOf(9999999)})); + + assertThrows(NullPointerException.class, + () -> ArrayUtils.toPrimitive(new Integer[]{Integer.valueOf(Integer.MIN_VALUE), null})); } @Test - public void testToStringArray_array() { - assertNull(ArrayUtils.toStringArray(null)); - - assertArrayEquals(new String[0], ArrayUtils.toStringArray(new Object[0])); - - final Object[] array = new Object[]{1, 2, 3, "array", "test"}; - assertArrayEquals(new String[]{"1", "2", "3", "array", "test"}, ArrayUtils.toStringArray(array)); + public void testToPrimitive_int_int() { + final Long[] l = null; + assertNull(ArrayUtils.toPrimitive(l, Integer.MIN_VALUE)); + assertSame(ArrayUtils.EMPTY_INT_ARRAY, + ArrayUtils.toPrimitive(new Integer[0], 1)); + assertArrayEquals(new int[]{Integer.MIN_VALUE, Integer.MAX_VALUE, 9999999}, ArrayUtils.toPrimitive(new Integer[]{Integer.valueOf(Integer.MIN_VALUE), + Integer.valueOf(Integer.MAX_VALUE), Integer.valueOf(9999999)}, 1)); + assertArrayEquals(new int[]{Integer.MIN_VALUE, Integer.MAX_VALUE, 9999999}, ArrayUtils.toPrimitive(new Integer[]{Integer.valueOf(Integer.MIN_VALUE), + null, Integer.valueOf(9999999)}, Integer.MAX_VALUE)); + } - assertThrows(NullPointerException.class, () -> ArrayUtils.toStringArray(new Object[]{null})); + @Test + public void testToPrimitive_intNull() { + final Integer[] iArray = null; + assertNull(ArrayUtils.toPrimitive(iArray, Integer.MIN_VALUE)); } + // testToPrimitive/Object for long + // ----------------------------------------------------------------------- @Test - public void testToStringArray_array_string() { - assertNull(ArrayUtils.toStringArray(null, "")); + public void testToPrimitive_long() { + final Long[] b = null; + assertNull(ArrayUtils.toPrimitive(b)); - assertArrayEquals(new String[0], ArrayUtils.toStringArray(new Object[0], "")); + assertSame(ArrayUtils.EMPTY_LONG_ARRAY, + ArrayUtils.toPrimitive(new Long[0])); - final Object[] array = new Object[]{1, null, "test"}; - assertArrayEquals(new String[]{"1", "valueForNullElements", "test"}, - ArrayUtils.toStringArray(array, "valueForNullElements")); + assertArrayEquals(new long[]{Long.MIN_VALUE, Long.MAX_VALUE, 9999999}, ArrayUtils.toPrimitive(new Long[]{Long.valueOf(Long.MIN_VALUE), + Long.valueOf(Long.MAX_VALUE), Long.valueOf(9999999)})); + + assertThrows(NullPointerException.class, + () -> ArrayUtils.toPrimitive(new Long[]{Long.valueOf(Long.MIN_VALUE), null})); } @Test - public void testShuffle() { - final String[] array1 = new String[]{"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"}; - final String[] array2 = ArrayUtils.clone(array1); + public void testToPrimitive_long_long() { + final Long[] l = null; + assertNull(ArrayUtils.toPrimitive(l, Long.MIN_VALUE)); - ArrayUtils.shuffle(array1, new Random(SEED)); - assertFalse(Arrays.equals(array1, array2)); - for (final String element : array2) { - assertTrue(ArrayUtils.contains(array1, element), "Element " + element + " not found"); - } - } + assertSame(ArrayUtils.EMPTY_LONG_ARRAY, + ArrayUtils.toPrimitive(new Long[0], 1)); - @Test - public void testShuffleBoolean() { - final boolean[] array1 = new boolean[]{true, false, true, true, false, false, true, false, false, true}; - final boolean[] array2 = ArrayUtils.clone(array1); + assertArrayEquals(new long[]{Long.MIN_VALUE, Long.MAX_VALUE, 9999999}, ArrayUtils.toPrimitive(new Long[]{Long.valueOf(Long.MIN_VALUE), + Long.valueOf(Long.MAX_VALUE), Long.valueOf(9999999)}, 1)); - ArrayUtils.shuffle(array1, new Random(SEED)); - assertFalse(Arrays.equals(array1, array2)); - assertEquals(5, ArrayUtils.removeAllOccurrences(array1, true).length); + assertArrayEquals(new long[]{Long.MIN_VALUE, Long.MAX_VALUE, 9999999}, ArrayUtils.toPrimitive(new Long[]{Long.valueOf(Long.MIN_VALUE), + null, Long.valueOf(9999999)}, Long.MAX_VALUE)); } + // testToPrimitive/Object for short + // ----------------------------------------------------------------------- @Test - public void testShuffleByte() { - final byte[] array1 = new byte[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; - final byte[] array2 = ArrayUtils.clone(array1); + public void testToPrimitive_short() { + final Short[] b = null; + assertNull(ArrayUtils.toPrimitive(b)); - ArrayUtils.shuffle(array1, new Random(SEED)); - assertFalse(Arrays.equals(array1, array2)); - for (final byte element : array2) { - assertTrue(ArrayUtils.contains(array1, element), "Element " + element + " not found"); - } - } + assertSame(ArrayUtils.EMPTY_SHORT_ARRAY, ArrayUtils.toPrimitive(new Short[0])); - @Test - public void testShuffleChar() { - final char[] array1 = new char[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; - final char[] array2 = ArrayUtils.clone(array1); + assertArrayEquals(new short[]{Short.MIN_VALUE, Short.MAX_VALUE, (short) 9999999}, ArrayUtils.toPrimitive(new Short[]{Short.valueOf(Short.MIN_VALUE), + Short.valueOf(Short.MAX_VALUE), Short.valueOf((short) 9999999)})); - ArrayUtils.shuffle(array1, new Random(SEED)); - assertFalse(Arrays.equals(array1, array2)); - for (final char element : array2) { - assertTrue(ArrayUtils.contains(array1, element), "Element " + element + " not found"); - } + assertThrows(NullPointerException.class, + () -> ArrayUtils.toPrimitive(new Short[]{Short.valueOf(Short.MIN_VALUE), null})); } @Test - public void testShuffleShort() { - final short[] array1 = new short[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; - final short[] array2 = ArrayUtils.clone(array1); + public void testToPrimitive_short_short() { + final Short[] s = null; + assertNull(ArrayUtils.toPrimitive(s, Short.MIN_VALUE)); - ArrayUtils.shuffle(array1, new Random(SEED)); - assertFalse(Arrays.equals(array1, array2)); - for (final short element : array2) { - assertTrue(ArrayUtils.contains(array1, element), "Element " + element + " not found"); - } - } + assertSame(ArrayUtils.EMPTY_SHORT_ARRAY, ArrayUtils.toPrimitive(new Short[0], + Short.MIN_VALUE)); - @Test - public void testShuffleInt() { - final int[] array1 = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; - final int[] array2 = ArrayUtils.clone(array1); + assertArrayEquals(new short[]{Short.MIN_VALUE, Short.MAX_VALUE, (short) 9999999}, ArrayUtils.toPrimitive(new Short[]{Short.valueOf(Short.MIN_VALUE), + Short.valueOf(Short.MAX_VALUE), Short.valueOf((short) 9999999)}, Short.MIN_VALUE)); - ArrayUtils.shuffle(array1, new Random(SEED)); - assertFalse(Arrays.equals(array1, array2)); - for (final int element : array2) { - assertTrue(ArrayUtils.contains(array1, element), "Element " + element + " not found"); - } + assertArrayEquals(new short[]{Short.MIN_VALUE, Short.MAX_VALUE, (short) 9999999}, ArrayUtils.toPrimitive(new Short[]{Short.valueOf(Short.MIN_VALUE), null, + Short.valueOf((short) 9999999)}, Short.MAX_VALUE)); } + //----------------------------------------------------------------------- @Test - public void testShuffleLong() { - final long[] array1 = new long[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; - final long[] array2 = ArrayUtils.clone(array1); + public void testToString() { + assertEquals("{}", ArrayUtils.toString(null)); + assertEquals("{}", ArrayUtils.toString(new Object[0])); + assertEquals("{}", ArrayUtils.toString(new String[0])); + assertEquals("{}", ArrayUtils.toString(new String[]{null})); + assertEquals("{pink,blue}", ArrayUtils.toString(new String[]{"pink", "blue"})); - ArrayUtils.shuffle(array1, new Random(SEED)); - assertFalse(Arrays.equals(array1, array2)); - for (final long element : array2) { - assertTrue(ArrayUtils.contains(array1, element), "Element " + element + " not found"); - } + assertEquals("", ArrayUtils.toString(null, "")); + assertEquals("{}", ArrayUtils.toString(new Object[0], "")); + assertEquals("{}", ArrayUtils.toString(new String[0], "")); + assertEquals("{}", ArrayUtils.toString(new String[]{null}, "")); + assertEquals("{pink,blue}", ArrayUtils.toString(new String[]{"pink", "blue"}, "")); } @Test - public void testShuffleFloat() { - final float[] array1 = new float[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; - final float[] array2 = ArrayUtils.clone(array1); + public void testToStringArray_array() { + assertNull(ArrayUtils.toStringArray(null)); - ArrayUtils.shuffle(array1, new Random(SEED)); - assertFalse(Arrays.equals(array1, array2)); - for (final float element : array2) { - assertTrue(ArrayUtils.contains(array1, element), "Element " + element + " not found"); - } - } + assertArrayEquals(new String[0], ArrayUtils.toStringArray(new Object[0])); - @Test - public void testShuffleDouble() { - final double[] array1 = new double[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; - final double[] array2 = ArrayUtils.clone(array1); + final Object[] array = new Object[]{1, 2, 3, "array", "test"}; + assertArrayEquals(new String[]{"1", "2", "3", "array", "test"}, ArrayUtils.toStringArray(array)); - ArrayUtils.shuffle(array1, new Random(SEED)); - assertFalse(Arrays.equals(array1, array2)); - for (final double element : array2) { - assertTrue(ArrayUtils.contains(array1, element), "Element " + element + " not found"); - } + assertThrows(NullPointerException.class, () -> ArrayUtils.toStringArray(new Object[]{null})); } @Test - public void testIsArrayIndexValid() { - assertFalse(ArrayUtils.isArrayIndexValid(null, 0)); - final String[] array = new String[1]; + public void testToStringArray_array_string() { + assertNull(ArrayUtils.toStringArray(null, "")); - //too big - assertFalse(ArrayUtils.isArrayIndexValid(array, 1)); + assertArrayEquals(new String[0], ArrayUtils.toStringArray(new Object[0], "")); - //negative index - assertFalse(ArrayUtils.isArrayIndexValid(array, -1)); + final Object[] array = new Object[]{1, null, "test"}; + assertArrayEquals(new String[]{"1", "valueForNullElements", "test"}, + ArrayUtils.toStringArray(array, "valueForNullElements")); + } - //good to go - assertTrue(ArrayUtils.isArrayIndexValid(array, 0)); + @Test + public void textIndexesOfInt() { + int[] array = null; + final BitSet emptySet = new BitSet(); + final BitSet testSet = new BitSet(); + assertEquals(emptySet, ArrayUtils.indexesOf(array, 0)); + array = new int[]{0, 1, 2, 3, 0}; + testSet.set(0); + testSet.set(4); + assertEquals(testSet, ArrayUtils.indexesOf(array, 0)); + testSet.clear(); + testSet.set(1); + assertEquals(testSet, ArrayUtils.indexesOf(array, 1)); + testSet.clear(); + testSet.set(2); + assertEquals(testSet, ArrayUtils.indexesOf(array, 2)); + testSet.clear(); + testSet.set(3); + assertEquals(testSet, ArrayUtils.indexesOf(array, 3)); + assertEquals(emptySet, ArrayUtils.indexesOf(array, 99)); } } From 5b699d076518cbf2dddc286f65cb06d0873dae16 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Fri, 12 Jun 2020 16:40:49 -0400 Subject: [PATCH 0103/3230] [LANG-1569] Add ArrayUtils.get(T[], index, T) to provide an out-of-bounds default value --- src/changes/changes.xml | 1 + .../org/apache/commons/lang3/ArrayUtils.java | 33 +++++++++ .../apache/commons/lang3/ArrayUtilsTest.java | 73 +++++++++++-------- 3 files changed, 77 insertions(+), 30 deletions(-) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index c34b0f692ce..61fc5727402 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -61,6 +61,7 @@ The type attribute can be add,update,fix,remove. CharSequenceUtils.regionMatches is wrong dealing with Georgian. Added the Locks class as a convenient possibility to deal with locked objects. Add to Functions: FailableBooleanSupplier, FailableIntSupplier, FailableLongSupplier, FailableDoubleSupplier, and so on. + Add ArrayUtils.get(T[], index, T) to provide an out-of-bounds default value. diff --git a/src/main/java/org/apache/commons/lang3/ArrayUtils.java b/src/main/java/org/apache/commons/lang3/ArrayUtils.java index c620c7983a0..074341afd72 100644 --- a/src/main/java/org/apache/commons/lang3/ArrayUtils.java +++ b/src/main/java/org/apache/commons/lang3/ArrayUtils.java @@ -1655,6 +1655,39 @@ private static Object copyArrayGrow1(final Object array, final Class newArray return Array.newInstance(newArrayComponentType, 1); } + /** + * Gets the nTh element of an array or null if the index is out of bounds or the array is null. + * + * @param The type of array elements. + * @param array The array to index. + * @param index The index + * @return the nTh element of an array or null if the index is out of bounds or the array is null. + * @since 3.11 + */ + public static T get(final T[] array, final int index) { + return get(array, index, null); + } + + /** + * Gets the nTh element of an array or a default value if the index is out of bounds. + * + * @param The type of array elements. + * @param array The array to index. + * @param index The index + * @param defaultValue The return value of the given index is out of bounds. + * @return the nTh element of an array or a default value if the index is out of bounds. + * @since 3.11 + */ + public static T get(final T[] array, final int index, T defaultValue) { + if (array == null) { + return defaultValue; + } + if (index >= 0 && index < array.length) { + return array[index]; + } + return defaultValue; + } + //----------------------------------------------------------------------- /** *

      Returns the length of the specified array. diff --git a/src/test/java/org/apache/commons/lang3/ArrayUtilsTest.java b/src/test/java/org/apache/commons/lang3/ArrayUtilsTest.java index 686f4647266..ffa076d719e 100644 --- a/src/test/java/org/apache/commons/lang3/ArrayUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/ArrayUtilsTest.java @@ -47,16 +47,15 @@ public class ArrayUtilsTest { private class TestClass { } - + /** A predefined seed used to initialize {@link Random} in order to get predictable results */ private static final long SEED = 16111981L; - + @SafeVarargs private static T[] toArrayPropagatingType(final T... items) { return ArrayUtils.toArray(items); } - //----------------------------------------------------------------------- private void assertIsEquals(final Object array1, final Object array2, final Object array3) { assertTrue(ArrayUtils.isEquals(array1, array1)); assertTrue(ArrayUtils.isEquals(array2, array2)); @@ -69,7 +68,6 @@ private void assertIsEquals(final Object array1, final Object array2, final Obje assertFalse(ArrayUtils.isEquals(array2, array1)); } - //----------------------------------------------------------------------- /** * Tests generic array creation with parameters of same type. */ @@ -101,7 +99,6 @@ public void testArrayCreationWithGeneralReturnType() { assertTrue(obj instanceof String[]); } - //----------------------------------------------------------------------- @Test public void testClone() { assertArrayEquals(null, ArrayUtils.clone((Object[]) null)); @@ -192,7 +189,6 @@ public void testCloneShort() { assertNotSame(original, cloned); } - //----------------------------------------------------------------------- @Test public void testConstructor() { assertNotNull(new ArrayUtils()); @@ -281,8 +277,6 @@ public void testContainsDouble() { assertFalse(ArrayUtils.contains(array, (double) 99)); } - //----------------------------------------------------------------------- - @SuppressWarnings("cast") @Test public void testContainsDoubleTolerance() { @@ -363,7 +357,47 @@ public void testEmptyArrayCreation() { assertEquals(0, array.length); } - // ------------------------------------------------------------------------ + @Test + public void testGet() { + assertNull(ArrayUtils.get(null, -1)); + assertNull(ArrayUtils.get(null, 0)); + assertNull(ArrayUtils.get(null, 1)); + final String[] array0 = {}; + assertNull(ArrayUtils.get(array0, -1)); + assertNull(ArrayUtils.get(array0, 0)); + assertNull(ArrayUtils.get(array0, 1)); + final String[] array1 = { StringUtils.EMPTY }; + assertEquals(null, ArrayUtils.get(array1, -1)); + assertEquals(StringUtils.EMPTY, ArrayUtils.get(array1, 0)); + assertEquals(null, ArrayUtils.get(array1, 1)); + } + + @Test + public void testGetDefault() { + // null default + { + assertNull(ArrayUtils.get(null, -1, null)); + assertNull(ArrayUtils.get(null, 0, null)); + assertNull(ArrayUtils.get(null, 1, null)); + final String[] array0 = {}; + assertNull(ArrayUtils.get(array0, -1, null)); + assertNull(ArrayUtils.get(array0, 0, null)); + assertNull(ArrayUtils.get(array0, 1, null)); + final String[] array1 = { StringUtils.EMPTY }; + assertEquals(null, ArrayUtils.get(array1, -1, null)); + assertEquals(StringUtils.EMPTY, ArrayUtils.get(array1, 0, null)); + assertEquals(null, ArrayUtils.get(array1, 1, null)); + } + // non-null default + { + final String defaultValue = "defaultValue"; + final String[] array1 = { StringUtils.EMPTY }; + assertEquals(defaultValue, ArrayUtils.get(array1, -1, defaultValue)); + assertEquals(StringUtils.EMPTY, ArrayUtils.get(array1, 0, defaultValue)); + assertEquals(defaultValue, ArrayUtils.get(array1, 1, defaultValue)); + } + } + @Test public void testGetLength() { assertEquals(0, ArrayUtils.getLength(null)); @@ -419,7 +453,6 @@ public void testGetLength() { assertThrows(IllegalArgumentException.class, () -> ArrayUtils.getLength("notAnArray")); } - //----------------------------------------------------------------------- @Test public void testHashCode() { final long[][] array1 = new long[][]{{2, 5}, {4, 5}}; @@ -885,7 +918,6 @@ public void testIndexesOfWithStartIndex() { } - //----------------------------------------------------------------------- @Test public void testIndexOf() { final Object[] array = new Object[]{"0", "1", "2", "3", null, "0"}; @@ -900,7 +932,6 @@ public void testIndexOf() { assertEquals(-1, ArrayUtils.indexOf(array, "notInArray")); } - //----------------------------------------------------------------------- @Test public void testIndexOfBoolean() { boolean[] array = null; @@ -930,7 +961,6 @@ public void testIndexOfBooleanWithStartIndex() { assertEquals(-1, ArrayUtils.indexOf(array, false, -1)); } - //----------------------------------------------------------------------- @Test public void testIndexOfByte() { byte[] array = null; @@ -957,7 +987,6 @@ public void testIndexOfByteWithStartIndex() { assertEquals(-1, ArrayUtils.indexOf(array, (byte) 0, 6)); } - //----------------------------------------------------------------------- @Test public void testIndexOfChar() { char[] array = null; @@ -984,7 +1013,6 @@ public void testIndexOfCharWithStartIndex() { assertEquals(-1, ArrayUtils.indexOf(array, 'a', 6)); } - //----------------------------------------------------------------------- @SuppressWarnings("cast") @Test public void testIndexOfDouble() { @@ -1049,7 +1077,6 @@ public void testIndexOfDoubleWithStartIndexTolerance() { assertEquals(1, ArrayUtils.indexOf(array, 1.00001324, -300, 0.0001)); } - //----------------------------------------------------------------------- @SuppressWarnings("cast") @Test public void testIndexOfFloat() { @@ -1082,7 +1109,6 @@ public void testIndexOfFloatWithStartIndex() { assertEquals(-1, ArrayUtils.indexOf(array, (float) 0, 6)); } - //----------------------------------------------------------------------- @Test public void testIndexOfInt() { int[] array = null; @@ -1109,7 +1135,6 @@ public void testIndexOfIntWithStartIndex() { assertEquals(-1, ArrayUtils.indexOf(array, 0, 6)); } - //----------------------------------------------------------------------- @Test public void testIndexOfLong() { long[] array = null; @@ -1136,7 +1161,6 @@ public void testIndexOfLongWithStartIndex() { assertEquals(-1, ArrayUtils.indexOf(array, 0, 6)); } - //----------------------------------------------------------------------- @Test public void testIndexOfShort() { short[] array = null; @@ -1505,8 +1529,6 @@ public void testIsSortedDouble() { assertFalse(ArrayUtils.isSorted(array)); } - //----------------------------------------------------------------------- - @Test public void testIsSortedFloat() { float[] array = null; @@ -2249,7 +2271,6 @@ public void testNullToEmptyStringNull() { assertArrayEquals(ArrayUtils.EMPTY_STRING_ARRAY, ArrayUtils.nullToEmpty((String[]) null)); } - //----------------------------------------------------------------------- @Test public void testReverse() { final StringBuffer str1 = new StringBuffer("pick"); @@ -2667,7 +2688,6 @@ public void testReverseShortRange() { assertNull(array); } - //----------------------------------------------------------------------- @Test public void testSameLength() { final Object[] nullArray = null; @@ -4256,7 +4276,6 @@ public void testSameLengthShort() { assertTrue(ArrayUtils.isSameLength(twoArray, twoArray)); } - //----------------------------------------------------------------------- @Test public void testSameType() { assertThrows(IllegalArgumentException.class, () -> ArrayUtils.isSameType(null, null)); @@ -4469,7 +4488,6 @@ public void testShiftChar() { assertEquals(2, array[3]); } - //----------------------------------------------------------------------- @Test public void testShiftDouble() { final double[] array = new double[]{1, 2, 3, 4}; @@ -5545,7 +5563,6 @@ public void testSwapByteRange() { assertEquals(3, array[2]); } - //----------------------------------------------------------------------- @Test public void testSwapChar() { char[] array = new char[]{1, 2, 3}; @@ -6034,7 +6051,6 @@ public void testSwapShortRange() { assertEquals(3, array[2]); } - //----------------------------------------------------------------------- @Test public void testToMap() { Map map = ArrayUtils.toMap(new String[][]{{"foo", "bar"}, {"hello", "world"}}); @@ -6090,8 +6106,6 @@ public Object setValue(final Object value) { assertEquals(Collections.singletonMap("key", "value1"), map); } - //----------------------------------------------------------------------- - @Test public void testToObject_boolean() { final boolean[] b = null; @@ -6447,7 +6461,6 @@ public void testToPrimitive_short_short() { Short.valueOf((short) 9999999)}, Short.MAX_VALUE)); } - //----------------------------------------------------------------------- @Test public void testToString() { assertEquals("{}", ArrayUtils.toString(null)); From b2412284a3f85b8d8602610d8b840bf65cdfe839 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Fri, 12 Jun 2020 16:41:10 -0400 Subject: [PATCH 0104/3230] [LANG-1569] Add ArrayUtils.get(T[], index, T) to provide an out-of-bounds default value --- src/main/java/org/apache/commons/lang3/ArrayUtils.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/apache/commons/lang3/ArrayUtils.java b/src/main/java/org/apache/commons/lang3/ArrayUtils.java index 074341afd72..b89cd565b0c 100644 --- a/src/main/java/org/apache/commons/lang3/ArrayUtils.java +++ b/src/main/java/org/apache/commons/lang3/ArrayUtils.java @@ -1678,7 +1678,7 @@ public static T get(final T[] array, final int index) { * @return the nTh element of an array or a default value if the index is out of bounds. * @since 3.11 */ - public static T get(final T[] array, final int index, T defaultValue) { + public static T get(final T[] array, final int index, final T defaultValue) { if (array == null) { return defaultValue; } From 96a8969c13305dfe787847a84e362e66461428e7 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Fri, 12 Jun 2020 17:36:10 -0400 Subject: [PATCH 0105/3230] Remove trailing white space. --- src/main/java/org/apache/commons/lang3/ArrayUtils.java | 4 ++-- src/test/java/org/apache/commons/lang3/ArrayUtilsTest.java | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/ArrayUtils.java b/src/main/java/org/apache/commons/lang3/ArrayUtils.java index b89cd565b0c..87ee055cf87 100644 --- a/src/main/java/org/apache/commons/lang3/ArrayUtils.java +++ b/src/main/java/org/apache/commons/lang3/ArrayUtils.java @@ -1657,7 +1657,7 @@ private static Object copyArrayGrow1(final Object array, final Class newArray /** * Gets the nTh element of an array or null if the index is out of bounds or the array is null. - * + * * @param The type of array elements. * @param array The array to index. * @param index The index @@ -1670,7 +1670,7 @@ public static T get(final T[] array, final int index) { /** * Gets the nTh element of an array or a default value if the index is out of bounds. - * + * * @param The type of array elements. * @param array The array to index. * @param index The index diff --git a/src/test/java/org/apache/commons/lang3/ArrayUtilsTest.java b/src/test/java/org/apache/commons/lang3/ArrayUtilsTest.java index ffa076d719e..db9b5abb673 100644 --- a/src/test/java/org/apache/commons/lang3/ArrayUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/ArrayUtilsTest.java @@ -47,10 +47,10 @@ public class ArrayUtilsTest { private class TestClass { } - + /** A predefined seed used to initialize {@link Random} in order to get predictable results */ private static final long SEED = 16111981L; - + @SafeVarargs private static T[] toArrayPropagatingType(final T... items) { return ArrayUtils.toArray(items); From 874cc143284feb8a469e3d41e05543663cffeafb Mon Sep 17 00:00:00 2001 From: Edgar Asatryan <17509127+nstdio@users.noreply.github.com> Date: Sat, 13 Jun 2020 18:39:41 +0400 Subject: [PATCH 0106/3230] [LANG-1550] Optimize ArrayUtils::isArrayIndexValid method. (#551) * [LANG-1550] Optimize ArrayUtils::isArrayIndexValid method. --- .../java/org/apache/commons/lang3/ArrayUtils.java | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/ArrayUtils.java b/src/main/java/org/apache/commons/lang3/ArrayUtils.java index 87ee055cf87..ee1b2157c6a 100644 --- a/src/main/java/org/apache/commons/lang3/ArrayUtils.java +++ b/src/main/java/org/apache/commons/lang3/ArrayUtils.java @@ -3111,6 +3111,13 @@ public static T[] insert(final int index, final T[] array, final T... values /** * Returns whether a given array can safely be accessed at the given index. + * + *

      +     * ArrayUtils.isArrayIndexValid(null, 0)       = false
      +     * ArrayUtils.isArrayIndexValid([], 0)         = false
      +     * ArrayUtils.isArrayIndexValid(["a"], 0)      = true
      +     * 
      + * * @param the component type of the array * @param array the array to inspect, may be null * @param index the index of the array to be inspected @@ -3118,11 +3125,7 @@ public static T[] insert(final int index, final T[] array, final T... values * @since 3.8 */ public static boolean isArrayIndexValid(final T[] array, final int index) { - if (getLength(array) == 0 || array.length <= index) { - return false; - } - - return index >= 0; + return index >= 0 && getLength(array) > index; } /** From 2d21e19f063733a12add17f9933cd9270eb246d1 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sat, 13 Jun 2020 10:41:31 -0400 Subject: [PATCH 0107/3230] [LANG-1550] Optimize ArrayUtils::isArrayIndexValid method. #551. --- src/changes/changes.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 61fc5727402..50d063ae75b 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -62,6 +62,7 @@ The type attribute can be add,update,fix,remove. Added the Locks class as a convenient possibility to deal with locked objects. Add to Functions: FailableBooleanSupplier, FailableIntSupplier, FailableLongSupplier, FailableDoubleSupplier, and so on. Add ArrayUtils.get(T[], index, T) to provide an out-of-bounds default value. + Optimize ArrayUtils::isArrayIndexValid method. #551.
      From 7651124bec8a74366fcc70af41ccaa2e441dec3b Mon Sep 17 00:00:00 2001 From: XenoAmess Date: Sat, 13 Jun 2020 22:44:05 +0800 Subject: [PATCH 0108/3230] [LANG-1561] use List.sort instead of Collection.sort (#546) * use_List_sort * Update MethodUtils.java * Update ObjectToStringComparatorTest.java --- .../java/org/apache/commons/lang3/reflect/MethodUtils.java | 3 +-- .../lang3/compare/ObjectToStringComparatorTest.java | 7 +++---- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/reflect/MethodUtils.java b/src/main/java/org/apache/commons/lang3/reflect/MethodUtils.java index 1d76ce611c0..a706ab04254 100644 --- a/src/main/java/org/apache/commons/lang3/reflect/MethodUtils.java +++ b/src/main/java/org/apache/commons/lang3/reflect/MethodUtils.java @@ -25,7 +25,6 @@ import java.lang.reflect.TypeVariable; import java.util.ArrayList; import java.util.Arrays; -import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.LinkedHashSet; @@ -694,7 +693,7 @@ public static Method getMatchingAccessibleMethod(final Class cls, } // Sort methods by signature to force deterministic result - Collections.sort(matchingMethods, METHOD_BY_SIGNATURE); + matchingMethods.sort(METHOD_BY_SIGNATURE); Method bestMatch = null; for (final Method method : matchingMethods) { diff --git a/src/test/java/org/apache/commons/lang3/compare/ObjectToStringComparatorTest.java b/src/test/java/org/apache/commons/lang3/compare/ObjectToStringComparatorTest.java index c233cf1c296..489c3101df6 100644 --- a/src/test/java/org/apache/commons/lang3/compare/ObjectToStringComparatorTest.java +++ b/src/test/java/org/apache/commons/lang3/compare/ObjectToStringComparatorTest.java @@ -20,7 +20,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Arrays; -import java.util.Collections; import java.util.List; import org.junit.jupiter.api.Test; @@ -47,7 +46,7 @@ public String toString() { @Test public void testNull() { final List things = Arrays.asList(null, new Thing("y"), null); - Collections.sort(things, ObjectToStringComparator.INSTANCE); + things.sort(ObjectToStringComparator.INSTANCE); assertEquals("y", things.get(0).string); assertEquals(null, things.get(1)); assertEquals(null, things.get(2)); @@ -56,7 +55,7 @@ public void testNull() { @Test public void testNullToString() { final List things = Arrays.asList(new Thing(null), new Thing("y"), new Thing(null)); - Collections.sort(things, ObjectToStringComparator.INSTANCE); + things.sort(ObjectToStringComparator.INSTANCE); assertEquals("y", things.get(0).string); assertEquals(null, things.get(1).string); assertEquals(null, things.get(2).string); @@ -65,7 +64,7 @@ public void testNullToString() { @Test public void testSortCollection() { final List things = Arrays.asList(new Thing("z"), new Thing("y"), new Thing("x")); - Collections.sort(things, ObjectToStringComparator.INSTANCE); + things.sort(ObjectToStringComparator.INSTANCE); assertEquals("x", things.get(0).string); assertEquals("y", things.get(1).string); assertEquals("z", things.get(2).string); From 773f276c2332f3a79fb1c225e723d02dcfbbcb3e Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sat, 13 Jun 2020 10:45:08 -0400 Subject: [PATCH 0109/3230] [LANG-1561] Use List.sort instead of Collection.sort #546. --- src/changes/changes.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 50d063ae75b..415c08677ae 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -63,6 +63,7 @@ The type attribute can be add,update,fix,remove. Add to Functions: FailableBooleanSupplier, FailableIntSupplier, FailableLongSupplier, FailableDoubleSupplier, and so on. Add ArrayUtils.get(T[], index, T) to provide an out-of-bounds default value. Optimize ArrayUtils::isArrayIndexValid method. #551. + Use List.sort instead of Collection.sort #546. From 011c8bdc921efc27d7904109579893d579bd99f5 Mon Sep 17 00:00:00 2001 From: XenoAmess Date: Sat, 13 Jun 2020 22:46:16 +0800 Subject: [PATCH 0110/3230] [LANG-1563] use StandardCharsets.UTF_8 (#548) * use_StandardCharsets_UTF_8 * Update StringEscapeUtilsTest.java --- src/test/java/org/apache/commons/lang3/CharsetsTestCase.java | 5 +++-- .../java/org/apache/commons/lang3/RandomStringUtilsTest.java | 3 ++- .../java/org/apache/commons/lang3/StringEscapeUtilsTest.java | 3 +-- 3 files changed, 6 insertions(+), 5 deletions(-) diff --git a/src/test/java/org/apache/commons/lang3/CharsetsTestCase.java b/src/test/java/org/apache/commons/lang3/CharsetsTestCase.java index 1819ea70a82..1d39d07961e 100644 --- a/src/test/java/org/apache/commons/lang3/CharsetsTestCase.java +++ b/src/test/java/org/apache/commons/lang3/CharsetsTestCase.java @@ -18,6 +18,7 @@ package org.apache.commons.lang3; import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; @@ -31,14 +32,14 @@ public class CharsetsTestCase { public void testToCharset_Charset() { Assertions.assertEquals(Charset.defaultCharset(), Charsets.toCharset((Charset) null)); Assertions.assertEquals(Charset.defaultCharset(), Charsets.toCharset(Charset.defaultCharset())); - Assertions.assertEquals(Charset.forName("UTF-8"), Charsets.toCharset(Charset.forName("UTF-8"))); + Assertions.assertEquals(StandardCharsets.UTF_8, Charsets.toCharset(StandardCharsets.UTF_8)); } @Test public void testToCharset_String() { Assertions.assertEquals(Charset.defaultCharset(), Charsets.toCharset((String) null)); Assertions.assertEquals(Charset.defaultCharset(), Charsets.toCharset(Charset.defaultCharset().name())); - Assertions.assertEquals(Charset.forName("UTF-8"), Charsets.toCharset("UTF-8")); + Assertions.assertEquals(StandardCharsets.UTF_8, Charsets.toCharset("UTF-8")); } @Test diff --git a/src/test/java/org/apache/commons/lang3/RandomStringUtilsTest.java b/src/test/java/org/apache/commons/lang3/RandomStringUtilsTest.java index aee483449a2..09df879d08d 100644 --- a/src/test/java/org/apache/commons/lang3/RandomStringUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/RandomStringUtilsTest.java @@ -31,6 +31,7 @@ import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; import java.util.Random; import org.junit.jupiter.api.Test; @@ -488,7 +489,7 @@ private double chiSquare(final int[] expected, final int[] observed) { @Test public void testLang100() { final int size = 5000; - final Charset charset = Charset.forName("UTF-8"); + final Charset charset = StandardCharsets.UTF_8; final String orig = RandomStringUtils.random(size); final byte[] bytes = orig.getBytes(charset); final String copy = new String(bytes, charset); diff --git a/src/test/java/org/apache/commons/lang3/StringEscapeUtilsTest.java b/src/test/java/org/apache/commons/lang3/StringEscapeUtilsTest.java index 92ea003460a..933364afeab 100644 --- a/src/test/java/org/apache/commons/lang3/StringEscapeUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/StringEscapeUtilsTest.java @@ -27,7 +27,6 @@ import java.io.StringWriter; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; -import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; @@ -479,7 +478,7 @@ public void testEscapeHtmlHighUnicode() { // codepoint: U+1D362 final byte[] data = new byte[] { (byte) 0xF0, (byte) 0x9D, (byte) 0x8D, (byte) 0xA2 }; - final String original = new String(data, Charset.forName("UTF8")); + final String original = new String(data, StandardCharsets.UTF_8); final String escaped = StringEscapeUtils.escapeHtml4( original ); assertEquals(original, escaped, "High Unicode should not have been escaped"); From 34fcd18ae7a34a9f62a7e836a94150f39acdfa69 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sat, 13 Jun 2020 10:46:58 -0400 Subject: [PATCH 0111/3230] [LANG-1563] use StandardCharsets.UTF_8 #548. --- src/changes/changes.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 415c08677ae..5459b7b43f6 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -64,6 +64,7 @@ The type attribute can be add,update,fix,remove. Add ArrayUtils.get(T[], index, T) to provide an out-of-bounds default value. Optimize ArrayUtils::isArrayIndexValid method. #551. Use List.sort instead of Collection.sort #546. + Use StandardCharsets.UTF_8 #548. From 9078cdc8c4320296219a42efa304b21d2e87f0e2 Mon Sep 17 00:00:00 2001 From: XenoAmess Date: Sat, 13 Jun 2020 22:49:59 +0800 Subject: [PATCH 0112/3230] use_Math_max_min (#547) --- .../org/apache/commons/lang3/ArrayUtils.java | 18 +++++++++--------- .../org/apache/commons/lang3/Conversion.java | 2 +- .../apache/commons/lang3/text/StrBuilder.java | 6 +++--- .../commons/lang3/time/FastDatePrinter.java | 2 +- 4 files changed, 14 insertions(+), 14 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/ArrayUtils.java b/src/main/java/org/apache/commons/lang3/ArrayUtils.java index ee1b2157c6a..dd9b5ca1eed 100644 --- a/src/main/java/org/apache/commons/lang3/ArrayUtils.java +++ b/src/main/java/org/apache/commons/lang3/ArrayUtils.java @@ -6523,7 +6523,7 @@ public static void reverse(final boolean[] array, final int startIndexInclusive, if (array == null) { return; } - int i = startIndexInclusive < 0 ? 0 : startIndexInclusive; + int i = Math.max(startIndexInclusive, 0); int j = Math.min(array.length, endIndexExclusive) - 1; boolean tmp; while (j > i) { @@ -6570,7 +6570,7 @@ public static void reverse(final byte[] array, final int startIndexInclusive, fi if (array == null) { return; } - int i = startIndexInclusive < 0 ? 0 : startIndexInclusive; + int i = Math.max(startIndexInclusive, 0); int j = Math.min(array.length, endIndexExclusive) - 1; byte tmp; while (j > i) { @@ -6617,7 +6617,7 @@ public static void reverse(final char[] array, final int startIndexInclusive, fi if (array == null) { return; } - int i = startIndexInclusive < 0 ? 0 : startIndexInclusive; + int i = Math.max(startIndexInclusive, 0); int j = Math.min(array.length, endIndexExclusive) - 1; char tmp; while (j > i) { @@ -6664,7 +6664,7 @@ public static void reverse(final double[] array, final int startIndexInclusive, if (array == null) { return; } - int i = startIndexInclusive < 0 ? 0 : startIndexInclusive; + int i = Math.max(startIndexInclusive, 0); int j = Math.min(array.length, endIndexExclusive) - 1; double tmp; while (j > i) { @@ -6711,7 +6711,7 @@ public static void reverse(final float[] array, final int startIndexInclusive, f if (array == null) { return; } - int i = startIndexInclusive < 0 ? 0 : startIndexInclusive; + int i = Math.max(startIndexInclusive, 0); int j = Math.min(array.length, endIndexExclusive) - 1; float tmp; while (j > i) { @@ -6758,7 +6758,7 @@ public static void reverse(final int[] array, final int startIndexInclusive, fin if (array == null) { return; } - int i = startIndexInclusive < 0 ? 0 : startIndexInclusive; + int i = Math.max(startIndexInclusive, 0); int j = Math.min(array.length, endIndexExclusive) - 1; int tmp; while (j > i) { @@ -6805,7 +6805,7 @@ public static void reverse(final long[] array, final int startIndexInclusive, fi if (array == null) { return; } - int i = startIndexInclusive < 0 ? 0 : startIndexInclusive; + int i = Math.max(startIndexInclusive, 0); int j = Math.min(array.length, endIndexExclusive) - 1; long tmp; while (j > i) { @@ -6856,7 +6856,7 @@ public static void reverse(final Object[] array, final int startIndexInclusive, if (array == null) { return; } - int i = startIndexInclusive < 0 ? 0 : startIndexInclusive; + int i = Math.max(startIndexInclusive, 0); int j = Math.min(array.length, endIndexExclusive) - 1; Object tmp; while (j > i) { @@ -6903,7 +6903,7 @@ public static void reverse(final short[] array, final int startIndexInclusive, f if (array == null) { return; } - int i = startIndexInclusive < 0 ? 0 : startIndexInclusive; + int i = Math.max(startIndexInclusive, 0); int j = Math.min(array.length, endIndexExclusive) - 1; short tmp; while (j > i) { diff --git a/src/main/java/org/apache/commons/lang3/Conversion.java b/src/main/java/org/apache/commons/lang3/Conversion.java index 18873d917b9..e7107013152 100644 --- a/src/main/java/org/apache/commons/lang3/Conversion.java +++ b/src/main/java/org/apache/commons/lang3/Conversion.java @@ -1534,7 +1534,7 @@ public static byte[] uuidToByteArray(final UUID src, final byte[] dst, final int if (nBytes > 16) { throw new IllegalArgumentException("nBytes is greater than 16"); } - longToByteArray(src.getMostSignificantBits(), 0, dst, dstPos, nBytes > 8 ? 8 : nBytes); + longToByteArray(src.getMostSignificantBits(), 0, dst, dstPos, Math.min(nBytes, 8)); if (nBytes >= 8) { longToByteArray(src.getLeastSignificantBits(), 0, dst, dstPos + 8, nBytes - 8); } diff --git a/src/main/java/org/apache/commons/lang3/text/StrBuilder.java b/src/main/java/org/apache/commons/lang3/text/StrBuilder.java index 21c88e42529..0fabc10013e 100644 --- a/src/main/java/org/apache/commons/lang3/text/StrBuilder.java +++ b/src/main/java/org/apache/commons/lang3/text/StrBuilder.java @@ -2420,7 +2420,7 @@ public int indexOf(final char ch) { * @return the first index of the character, or -1 if not found */ public int indexOf(final char ch, int startIndex) { - startIndex = (startIndex < 0 ? 0 : startIndex); + startIndex = (Math.max(startIndex, 0)); if (startIndex >= size) { return -1; } @@ -2456,7 +2456,7 @@ public int indexOf(final String str) { * @return the first index of the string, or -1 if not found */ public int indexOf(final String str, int startIndex) { - startIndex = (startIndex < 0 ? 0 : startIndex); + startIndex = (Math.max(startIndex, 0)); if (str == null || startIndex >= size) { return -1; } @@ -2511,7 +2511,7 @@ public int indexOf(final StrMatcher matcher) { * @return the first index matched, or -1 if not found */ public int indexOf(final StrMatcher matcher, int startIndex) { - startIndex = (startIndex < 0 ? 0 : startIndex); + startIndex = (Math.max(startIndex, 0)); if (matcher == null || startIndex >= size) { return -1; } diff --git a/src/main/java/org/apache/commons/lang3/time/FastDatePrinter.java b/src/main/java/org/apache/commons/lang3/time/FastDatePrinter.java index 888d3fb6019..48cd49bfed2 100644 --- a/src/main/java/org/apache/commons/lang3/time/FastDatePrinter.java +++ b/src/main/java/org/apache/commons/lang3/time/FastDatePrinter.java @@ -214,7 +214,7 @@ protected List parsePattern() { if (tokenLen == 2) { rule = TwoDigitYearField.INSTANCE; } else { - rule = selectNumberRule(Calendar.YEAR, tokenLen < 4 ? 4 : tokenLen); + rule = selectNumberRule(Calendar.YEAR, Math.max(tokenLen, 4)); } if (c == 'Y') { rule = new WeekYear((NumberRule) rule); From 2f7a3a811805375d37415e12f6435d04be694ea2 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sat, 13 Jun 2020 10:51:05 -0400 Subject: [PATCH 0113/3230] [LANG-1562] use Math.max and min #547. --- src/changes/changes.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 5459b7b43f6..13cf6d2354b 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -65,6 +65,7 @@ The type attribute can be add,update,fix,remove. Optimize ArrayUtils::isArrayIndexValid method. #551. Use List.sort instead of Collection.sort #546. Use StandardCharsets.UTF_8 #548. + Use Math.max and min #547. From 386c1e2f37f77aedbfb624800bab51319bf3a9fd Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sat, 13 Jun 2020 10:55:46 -0400 Subject: [PATCH 0114/3230] Simplify lambdas. --- .../org/apache/commons/lang3/StreamsTest.java | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/src/test/java/org/apache/commons/lang3/StreamsTest.java b/src/test/java/org/apache/commons/lang3/StreamsTest.java index 3e17ed1bdc4..a0b79f60c13 100644 --- a/src/test/java/org/apache/commons/lang3/StreamsTest.java +++ b/src/test/java/org/apache/commons/lang3/StreamsTest.java @@ -46,7 +46,7 @@ class StreamsTest { @Test void testSimpleStreamMap() { final List input = Arrays.asList("1", "2", "3", "4", "5", "6"); - final List output = Functions.stream(input).map(s -> Integer.valueOf(s)).collect(Collectors.toList()); + final List output = Functions.stream(input).map(Integer::valueOf).collect(Collectors.toList()); assertEquals(6, output.size()); for (int i = 0; i < 6; i++) { assertEquals(i+1, output.get(i).intValue()); @@ -56,7 +56,7 @@ void testSimpleStreamMap() { @Test void testSimpleStreamMapFailing() { final List input = Arrays.asList("1", "2", "3", "4 ", "5", "6"); - final Executable testMethod = () -> Functions.stream(input).map(s -> Integer.valueOf(s)).collect(Collectors.toList()); + final Executable testMethod = () -> Functions.stream(input).map(Integer::valueOf).collect(Collectors.toList()); final NumberFormatException thrown = assertThrows(NumberFormatException.class, testMethod); assertEquals("For input string: \"4 \"", thrown.getMessage()); } @@ -130,10 +130,8 @@ Stream simpleStreamForEachFailing() { void testSimpleStreamFilter() { final List input = Arrays.asList("1", "2", "3", "4", "5", "6"); final List output = Functions.stream(input) - .map(s -> Integer.valueOf(s)) - .filter(i -> { - return i.intValue() %2 == 0; - }) + .map(Integer::valueOf) + .filter(i -> (i.intValue() %2 == 0)) .collect(Collectors.toList()); assertEvenNumbers(output); } @@ -160,7 +158,7 @@ protected FailablePredicate asIntPredicate(fin Stream simpleStreamFilterFailing() { final List input = Arrays.asList("1", "2", "3", "4", "5", "6"); final List output = Functions.stream(input) - .map(s -> Integer.valueOf(s)) + .map(Integer::valueOf) .filter(asIntPredicate(null)) .collect(Collectors.toList()); assertEvenNumbers(output); @@ -170,7 +168,7 @@ Stream simpleStreamFilterFailing() { dynamicTest("IllegalArgumentException", () -> { final IllegalArgumentException iae = new IllegalArgumentException("Invalid argument: " + 5); final Executable testMethod = () -> Functions.stream(input) - .map(s -> Integer.valueOf(s)) + .map(Integer::valueOf) .filter(asIntPredicate(iae)) .collect(Collectors.toList()); final IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, testMethod); @@ -180,7 +178,7 @@ Stream simpleStreamFilterFailing() { dynamicTest("OutOfMemoryError", () -> { final OutOfMemoryError oome = new OutOfMemoryError(); final Executable testMethod = () -> Functions.stream(input) - .map(s -> Integer.valueOf(s)) + .map(Integer::valueOf) .filter(asIntPredicate(oome)) .collect(Collectors.toList()); final OutOfMemoryError thrown = assertThrows(OutOfMemoryError.class, testMethod); @@ -190,7 +188,7 @@ Stream simpleStreamFilterFailing() { dynamicTest("SAXException", () -> { final SAXException se = new SAXException(); final Executable testMethod = () -> Functions.stream(input) - .map(s -> Integer.valueOf(s)) + .map(Integer::valueOf) .filter(asIntPredicate(se)) .collect(Collectors.toList()); final UndeclaredThrowableException thrown = assertThrows(UndeclaredThrowableException.class, testMethod); From f2d376ae01d59cf89a87f0114e21f9a5d4bc4885 Mon Sep 17 00:00:00 2001 From: XenoAmess Date: Sat, 13 Jun 2020 22:57:51 +0800 Subject: [PATCH 0115/3230] [LANG-1564] use Collections.singletonList insteadof Arrays.asList when there be only one element. (#549) * asList * Update TypeUtilsTest.java --- .../commons/lang3/text/translate/NumericEntityUnescaper.java | 3 ++- src/test/java/org/apache/commons/lang3/ObjectUtilsTest.java | 4 ++-- .../java/org/apache/commons/lang3/reflect/TypeUtilsTest.java | 3 +-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/text/translate/NumericEntityUnescaper.java b/src/main/java/org/apache/commons/lang3/text/translate/NumericEntityUnescaper.java index b9da84a9856..e765825ab2a 100644 --- a/src/main/java/org/apache/commons/lang3/text/translate/NumericEntityUnescaper.java +++ b/src/main/java/org/apache/commons/lang3/text/translate/NumericEntityUnescaper.java @@ -19,6 +19,7 @@ import java.io.IOException; import java.io.Writer; import java.util.Arrays; +import java.util.Collections; import java.util.EnumSet; /** @@ -62,7 +63,7 @@ public NumericEntityUnescaper(final OPTION... options) { if (options.length > 0) { this.options = EnumSet.copyOf(Arrays.asList(options)); } else { - this.options = EnumSet.copyOf(Arrays.asList(OPTION.semiColonRequired)); + this.options = EnumSet.copyOf(Collections.singletonList(OPTION.semiColonRequired)); } } diff --git a/src/test/java/org/apache/commons/lang3/ObjectUtilsTest.java b/src/test/java/org/apache/commons/lang3/ObjectUtilsTest.java index 373f40ca76c..aab3a4e77e7 100644 --- a/src/test/java/org/apache/commons/lang3/ObjectUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/ObjectUtilsTest.java @@ -243,10 +243,10 @@ public void testHashCodeMulti_multiple_nullArray() { @Test public void testHashCodeMulti_multiple_likeList() { - final List list0 = new ArrayList<>(Arrays.asList()); + final List list0 = new ArrayList<>(Collections.emptyList()); assertEquals(list0.hashCode(), ObjectUtils.hashCodeMulti()); - final List list1 = new ArrayList<>(Arrays.asList("a")); + final List list1 = new ArrayList<>(Collections.singletonList("a")); assertEquals(list1.hashCode(), ObjectUtils.hashCodeMulti("a")); final List list2 = new ArrayList<>(Arrays.asList("a", "b")); diff --git a/src/test/java/org/apache/commons/lang3/reflect/TypeUtilsTest.java b/src/test/java/org/apache/commons/lang3/reflect/TypeUtilsTest.java index eeaaa8c41a4..d029c088a86 100644 --- a/src/test/java/org/apache/commons/lang3/reflect/TypeUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/reflect/TypeUtilsTest.java @@ -32,7 +32,6 @@ import java.lang.reflect.WildcardType; import java.net.URI; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; @@ -504,7 +503,7 @@ public void testGetTypeArguments() { assertEquals(Integer.class, typeVarAssigns.get(treeSetTypeVar), "Type argument of Comparable from int: " + typeArg); - final Collection col = Arrays.asList(); + final Collection col = Collections.emptyList(); typeVarAssigns = TypeUtils.getTypeArguments(List.class, Collection.class); treeSetTypeVar = Comparable.class.getTypeParameters()[0]; assertFalse(typeVarAssigns.containsKey(treeSetTypeVar), From a21cdb512100349b4021effc9cdb65690c5d1684 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sat, 13 Jun 2020 10:58:39 -0400 Subject: [PATCH 0116/3230] [LANG-1564] Use Collections.singletonList insteadof Arrays.asList when there be only one element. #549. --- src/changes/changes.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 13cf6d2354b..75cf342bb35 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -65,7 +65,7 @@ The type attribute can be add,update,fix,remove. Optimize ArrayUtils::isArrayIndexValid method. #551. Use List.sort instead of Collection.sort #546. Use StandardCharsets.UTF_8 #548. - Use Math.max and min #547. + [LANG-1564] use Collections.singletonList insteadof Arrays.asList when there be only one element. #549. From 8e61b090ceaaf7b108f0df175e9edbeae8d37642 Mon Sep 17 00:00:00 2001 From: XenoAmess Date: Sat, 13 Jun 2020 23:04:11 +0800 Subject: [PATCH 0117/3230] fix javadoc (#545) --- src/main/java/org/apache/commons/lang3/SystemUtils.java | 2 +- .../java/org/apache/commons/lang3/reflect/MethodUtils.java | 4 ++-- .../java/org/apache/commons/lang3/StringEscapeUtilsTest.java | 2 +- .../org/apache/commons/lang3/time/DateUtilsRoundingTest.java | 1 - 4 files changed, 4 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/SystemUtils.java b/src/main/java/org/apache/commons/lang3/SystemUtils.java index e3c300c3e1c..2d6a97bf8a3 100644 --- a/src/main/java/org/apache/commons/lang3/SystemUtils.java +++ b/src/main/java/org/apache/commons/lang3/SystemUtils.java @@ -669,7 +669,7 @@ public class SystemUtils { * sync with that System property. *

      * - * @deprecated Use {@link System#lineSeparator} instead, since it does not require a privilege check. + * @deprecated Use {@link System#lineSeparator()} instead, since it does not require a privilege check. * @since Java 1.1 */ @Deprecated diff --git a/src/main/java/org/apache/commons/lang3/reflect/MethodUtils.java b/src/main/java/org/apache/commons/lang3/reflect/MethodUtils.java index a706ab04254..1e9b96ee1a8 100644 --- a/src/main/java/org/apache/commons/lang3/reflect/MethodUtils.java +++ b/src/main/java/org/apache/commons/lang3/reflect/MethodUtils.java @@ -983,8 +983,8 @@ public static A getAnnotation(final Method method, final } /** - *

      Gets a combination of {@link ClassUtils#getAllSuperclasses}(Class)} and - * {@link ClassUtils#getAllInterfaces}(Class)}, one from superclasses, one + *

      Gets a combination of {@link ClassUtils#getAllSuperclasses(Class)} and + * {@link ClassUtils#getAllInterfaces(Class)}, one from superclasses, one * from interfaces, and so on in a breadth first way.

      * * @param cls the class to look up, may be {@code null} diff --git a/src/test/java/org/apache/commons/lang3/StringEscapeUtilsTest.java b/src/test/java/org/apache/commons/lang3/StringEscapeUtilsTest.java index 933364afeab..29dda0da957 100644 --- a/src/test/java/org/apache/commons/lang3/StringEscapeUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/StringEscapeUtilsTest.java @@ -88,7 +88,7 @@ public void testEscapeJavaWithSlash() { final String expected = input; final String actual = StringEscapeUtils.escapeJava(input); - /** + /* * In 2.4 StringEscapeUtils.escapeJava(String) escapes '/' characters, which are not a valid character to escape * in a Java string. */ diff --git a/src/test/java/org/apache/commons/lang3/time/DateUtilsRoundingTest.java b/src/test/java/org/apache/commons/lang3/time/DateUtilsRoundingTest.java index c1c1d403bf8..65b0ec4bca3 100644 --- a/src/test/java/org/apache/commons/lang3/time/DateUtilsRoundingTest.java +++ b/src/test/java/org/apache/commons/lang3/time/DateUtilsRoundingTest.java @@ -592,7 +592,6 @@ public void testTruncateSecond() throws Exception { /** * Test DateUtils.truncate()-method with Calendar.SECOND * - * @throws Exception so we don't have to catch it * @since 3.0 */ @Test From dc35ebc48c00fbe45c1a2c4d4ba31fab8cf197a4 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sat, 13 Jun 2020 11:04:52 -0400 Subject: [PATCH 0118/3230] [LANG-1560] Refine Javadoc #545. --- src/changes/changes.xml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 75cf342bb35..b4957d166df 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -65,7 +65,8 @@ The type attribute can be add,update,fix,remove. Optimize ArrayUtils::isArrayIndexValid method. #551. Use List.sort instead of Collection.sort #546. Use StandardCharsets.UTF_8 #548. - [LANG-1564] use Collections.singletonList insteadof Arrays.asList when there be only one element. #549. + Use Collections.singletonList insteadof Arrays.asList when there be only one element. #549. + Refine Javadoc #545.
      From 2238145f563e911c02d6179afb27e883c0ec6b37 Mon Sep 17 00:00:00 2001 From: XenoAmess Date: Sat, 13 Jun 2020 23:06:06 +0800 Subject: [PATCH 0119/3230] array_style (#537) --- .../org/apache/commons/lang3/StringUtils.java | 14 ++++---- .../lang3/exception/ExceptionUtils.java | 6 ++-- .../lang3/reflect/ConstructorUtils.java | 4 +-- .../apache/commons/lang3/text/StrBuilder.java | 22 ++++++------- .../apache/commons/lang3/text/StrMatcher.java | 2 +- .../commons/lang3/text/StrTokenizer.java | 4 +-- .../lang3/builder/CompareToBuilderTest.java | 12 +++---- .../lang3/builder/EqualsBuilderTest.java | 8 ++--- .../commons/lang3/text/StrTokenizerTest.java | 32 +++++++++---------- 9 files changed, 52 insertions(+), 52 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/StringUtils.java b/src/main/java/org/apache/commons/lang3/StringUtils.java index 4f20fd82c36..f9143c52f3c 100644 --- a/src/main/java/org/apache/commons/lang3/StringUtils.java +++ b/src/main/java/org/apache/commons/lang3/StringUtils.java @@ -541,7 +541,7 @@ public static String capitalize(final String str) { return str; } - final int newCodePoints[] = new int[strLen]; // cannot be longer than the char array + final int[] newCodePoints = new int[strLen]; // cannot be longer than the char array int outOffset = 0; newCodePoints[outOffset++] = newCodePoint; // copy the first codepoint for (int inOffset = Character.charCount(firstCodepoint); inOffset < strLen; ) { @@ -2311,7 +2311,7 @@ public static int getLevenshteinDistance(CharSequence s, CharSequence t) { m = t.length(); } - final int p[] = new int[n + 1]; + final int[] p = new int[n + 1]; // indexes into strings s and t int i; // iterates through s int j; // iterates through t @@ -2452,9 +2452,9 @@ distance is O(nm), but a bound of k allows us to reduce it to O(km) time by only m = t.length(); } - int p[] = new int[n + 1]; // 'previous' cost array, horizontally - int d[] = new int[n + 1]; // cost array, horizontally - int _d[]; // placeholder to assist in swapping p and d + int[] p = new int[n + 1]; // 'previous' cost array, horizontally + int[] d = new int[n + 1]; // cost array, horizontally + int[] _d; // placeholder to assist in swapping p and d // fill in starting table values final int boundary = Math.min(n, threshold) + 1; @@ -8863,7 +8863,7 @@ public static String swapCase(final String str) { } final int strLen = str.length(); - final int newCodePoints[] = new int[strLen]; // cannot be longer than the char array + final int[] newCodePoints = new int[strLen]; // cannot be longer than the char array int outOffset = 0; for (int i = 0; i < strLen; ) { final int oldCodepoint = str.codePointAt(i); @@ -9207,7 +9207,7 @@ public static String uncapitalize(final String str) { return str; } - final int newCodePoints[] = new int[strLen]; // cannot be longer than the char array + final int[] newCodePoints = new int[strLen]; // cannot be longer than the char array int outOffset = 0; newCodePoints[outOffset++] = newCodePoint; // copy the first codepoint for (int inOffset = Character.charCount(firstCodepoint); inOffset < strLen; ) { diff --git a/src/main/java/org/apache/commons/lang3/exception/ExceptionUtils.java b/src/main/java/org/apache/commons/lang3/exception/ExceptionUtils.java index 205e1ae6761..5b48b0e43b1 100644 --- a/src/main/java/org/apache/commons/lang3/exception/ExceptionUtils.java +++ b/src/main/java/org/apache/commons/lang3/exception/ExceptionUtils.java @@ -259,7 +259,7 @@ public static String[] getRootCauseStackTrace(final Throwable throwable) { if (throwable == null) { return ArrayUtils.EMPTY_STRING_ARRAY; } - final Throwable throwables[] = getThrowables(throwable); + final Throwable[] throwables = getThrowables(throwable); final int count = throwables.length; final List frames = new ArrayList<>(); List nextTrace = getStackFrameList(throwables[count - 1]); @@ -633,7 +633,7 @@ public static void printRootCauseStackTrace(final Throwable throwable, final Pri return; } Validate.notNull(stream, "The PrintStream must not be null"); - final String trace[] = getRootCauseStackTrace(throwable); + final String[] trace = getRootCauseStackTrace(throwable); for (final String element : trace) { stream.println(element); } @@ -664,7 +664,7 @@ public static void printRootCauseStackTrace(final Throwable throwable, final Pri return; } Validate.notNull(writer, "The PrintWriter must not be null"); - final String trace[] = getRootCauseStackTrace(throwable); + final String[] trace = getRootCauseStackTrace(throwable); for (final String element : trace) { writer.println(element); } diff --git a/src/main/java/org/apache/commons/lang3/reflect/ConstructorUtils.java b/src/main/java/org/apache/commons/lang3/reflect/ConstructorUtils.java index 082bc89d0d8..72e6be61d9a 100644 --- a/src/main/java/org/apache/commons/lang3/reflect/ConstructorUtils.java +++ b/src/main/java/org/apache/commons/lang3/reflect/ConstructorUtils.java @@ -81,7 +81,7 @@ public static T invokeConstructor(final Class cls, Object... args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { args = ArrayUtils.nullToEmpty(args); - final Class parameterTypes[] = ClassUtils.toClass(args); + final Class[] parameterTypes = ClassUtils.toClass(args); return invokeConstructor(cls, args, parameterTypes); } @@ -145,7 +145,7 @@ public static T invokeExactConstructor(final Class cls, Object... args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { args = ArrayUtils.nullToEmpty(args); - final Class parameterTypes[] = ClassUtils.toClass(args); + final Class[] parameterTypes = ClassUtils.toClass(args); return invokeExactConstructor(cls, args, parameterTypes); } diff --git a/src/main/java/org/apache/commons/lang3/text/StrBuilder.java b/src/main/java/org/apache/commons/lang3/text/StrBuilder.java index 0fabc10013e..d8b215951a3 100644 --- a/src/main/java/org/apache/commons/lang3/text/StrBuilder.java +++ b/src/main/java/org/apache/commons/lang3/text/StrBuilder.java @@ -363,7 +363,7 @@ public char[] toCharArray() { if (size == 0) { return ArrayUtils.EMPTY_CHAR_ARRAY; } - final char chars[] = new char[size]; + final char[] chars = new char[size]; System.arraycopy(buffer, 0, chars, 0, size); return chars; } @@ -384,7 +384,7 @@ public char[] toCharArray(final int startIndex, int endIndex) { if (len == 0) { return ArrayUtils.EMPTY_CHAR_ARRAY; } - final char chars[] = new char[len]; + final char[] chars = new char[len]; System.arraycopy(buffer, startIndex, chars, 0, len); return chars; } @@ -414,7 +414,7 @@ public char[] getChars(char[] destination) { * @throws NullPointerException if the array is null * @throws IndexOutOfBoundsException if any index is invalid */ - public void getChars(final int startIndex, final int endIndex, final char destination[], final int destinationIndex) { + public void getChars(final int startIndex, final int endIndex, final char[] destination, final int destinationIndex) { if (startIndex < 0) { throw new StringIndexOutOfBoundsException(startIndex); } @@ -1640,7 +1640,7 @@ public StrBuilder insert(final int index, String str) { * @return this, to enable chaining * @throws IndexOutOfBoundsException if the index is invalid */ - public StrBuilder insert(final int index, final char chars[]) { + public StrBuilder insert(final int index, final char[] chars) { validateIndex(index); if (chars == null) { return insert(index, nullText); @@ -1666,7 +1666,7 @@ public StrBuilder insert(final int index, final char chars[]) { * @return this, to enable chaining * @throws IndexOutOfBoundsException if any index is invalid */ - public StrBuilder insert(final int index, final char chars[], final int offset, final int length) { + public StrBuilder insert(final int index, final char[] chars, final int offset, final int length) { validateIndex(index); if (chars == null) { return insert(index, nullText); @@ -2772,8 +2772,8 @@ public boolean equalsIgnoreCase(final StrBuilder other) { if (this.size != other.size) { return false; } - final char thisBuf[] = this.buffer; - final char otherBuf[] = other.buffer; + final char[] thisBuf = this.buffer; + final char[] otherBuf = other.buffer; for (int i = size - 1; i >= 0; i--) { final char c1 = thisBuf[i]; final char c2 = otherBuf[i]; @@ -2801,8 +2801,8 @@ public boolean equals(final StrBuilder other) { if (this.size != other.size) { return false; } - final char thisBuf[] = this.buffer; - final char otherBuf[] = other.buffer; + final char[] thisBuf = this.buffer; + final char[] otherBuf = other.buffer; for (int i = size - 1; i >= 0; i--) { if (thisBuf[i] != otherBuf[i]) { return false; @@ -2830,7 +2830,7 @@ public boolean equals(final Object obj) { */ @Override public int hashCode() { - final char buf[] = buffer; + final char[] buf = buffer; int hash = 0; for (int i = size - 1; i >= 0; i--) { hash = 31 * hash + buf[i]; @@ -2987,7 +2987,7 @@ public int read() { /** {@inheritDoc} */ @Override - public int read(final char b[], final int off, int len) { + public int read(final char[] b, final int off, int len) { if (off < 0 || len < 0 || off > b.length || (off + len) > b.length || (off + len) < 0) { throw new IndexOutOfBoundsException(); diff --git a/src/main/java/org/apache/commons/lang3/text/StrMatcher.java b/src/main/java/org/apache/commons/lang3/text/StrMatcher.java index 97d01c0c656..79801ee4d31 100644 --- a/src/main/java/org/apache/commons/lang3/text/StrMatcher.java +++ b/src/main/java/org/apache/commons/lang3/text/StrMatcher.java @@ -284,7 +284,7 @@ static final class CharSetMatcher extends StrMatcher { * * @param chars the characters to match, must not be null */ - CharSetMatcher(final char chars[]) { + CharSetMatcher(final char[] chars) { super(); this.chars = chars.clone(); Arrays.sort(this.chars); diff --git a/src/main/java/org/apache/commons/lang3/text/StrTokenizer.java b/src/main/java/org/apache/commons/lang3/text/StrTokenizer.java index 8a5c33c9b63..23e87b87d8d 100644 --- a/src/main/java/org/apache/commons/lang3/text/StrTokenizer.java +++ b/src/main/java/org/apache/commons/lang3/text/StrTokenizer.java @@ -110,9 +110,9 @@ public class StrTokenizer implements ListIterator, Cloneable { } /** The text to work on. */ - private char chars[]; + private char[] chars; /** The parsed tokens */ - private String tokens[]; + private String[] tokens; /** The current iteration position */ private int tokenPos; diff --git a/src/test/java/org/apache/commons/lang3/builder/CompareToBuilderTest.java b/src/test/java/org/apache/commons/lang3/builder/CompareToBuilderTest.java index e0ff46cf696..7311ee347a7 100644 --- a/src/test/java/org/apache/commons/lang3/builder/CompareToBuilderTest.java +++ b/src/test/java/org/apache/commons/lang3/builder/CompareToBuilderTest.java @@ -884,9 +884,9 @@ public void testMultiBooleanArray() { @Test public void testRaggedArray() { - final long array1[][] = new long[2][]; - final long array2[][] = new long[2][]; - final long array3[][] = new long[3][]; + final long[][] array1 = new long[2][]; + final long[][] array2 = new long[2][]; + final long[][] array3 = new long[3][]; for (int i = 0; i < array1.length; ++i) { array1[i] = new long[2]; array2[i] = new long[2]; @@ -912,9 +912,9 @@ public void testRaggedArray() { @Test public void testMixedArray() { - final Object array1[] = new Object[2]; - final Object array2[] = new Object[2]; - final Object array3[] = new Object[2]; + final Object[] array1 = new Object[2]; + final Object[] array2 = new Object[2]; + final Object[] array3 = new Object[2]; for (int i = 0; i < array1.length; ++i) { array1[i] = new long[2]; array2[i] = new long[2]; diff --git a/src/test/java/org/apache/commons/lang3/builder/EqualsBuilderTest.java b/src/test/java/org/apache/commons/lang3/builder/EqualsBuilderTest.java index d487bac04f7..f0fab3914d9 100644 --- a/src/test/java/org/apache/commons/lang3/builder/EqualsBuilderTest.java +++ b/src/test/java/org/apache/commons/lang3/builder/EqualsBuilderTest.java @@ -925,8 +925,8 @@ public void testMultiBooleanArray() { @Test public void testRaggedArray() { - final long array1[][] = new long[2][]; - final long array2[][] = new long[2][]; + final long[][] array1 = new long[2][]; + final long[][] array2 = new long[2][]; for (int i = 0; i < array1.length; ++i) { array1[i] = new long[2]; array2[i] = new long[2]; @@ -943,8 +943,8 @@ public void testRaggedArray() { @Test public void testMixedArray() { - final Object array1[] = new Object[2]; - final Object array2[] = new Object[2]; + final Object[] array1 = new Object[2]; + final Object[] array2 = new Object[2]; for (int i = 0; i < array1.length; ++i) { array1[i] = new long[2]; array2[i] = new long[2]; diff --git a/src/test/java/org/apache/commons/lang3/text/StrTokenizerTest.java b/src/test/java/org/apache/commons/lang3/text/StrTokenizerTest.java index 7609eeee39b..acb18e74363 100644 --- a/src/test/java/org/apache/commons/lang3/text/StrTokenizerTest.java +++ b/src/test/java/org/apache/commons/lang3/text/StrTokenizerTest.java @@ -58,9 +58,9 @@ public void test1() { tok.setQuoteChar('"'); tok.setIgnoredMatcher(StrMatcher.trimMatcher()); tok.setIgnoreEmptyTokens(false); - final String tokens[] = tok.getTokenArray(); + final String[] tokens = tok.getTokenArray(); - final String expected[] = new String[]{"a", "b", "c", "d;\"e", "f", "", "", ""}; + final String[] expected = new String[]{"a", "b", "c", "d;\"e", "f", "", "", ""}; assertEquals(expected.length, tokens.length, ArrayUtils.toString(tokens)); for (int i = 0; i < expected.length; i++) { @@ -79,9 +79,9 @@ public void test2() { tok.setQuoteChar('"'); tok.setIgnoredMatcher(StrMatcher.noneMatcher()); tok.setIgnoreEmptyTokens(false); - final String tokens[] = tok.getTokenArray(); + final String[] tokens = tok.getTokenArray(); - final String expected[] = new String[]{"a", "b", "c ", "d;\"e", "f", " ", " ", ""}; + final String[] expected = new String[]{"a", "b", "c ", "d;\"e", "f", " ", " ", ""}; assertEquals(expected.length, tokens.length, ArrayUtils.toString(tokens)); for (int i = 0; i < expected.length; i++) { @@ -100,9 +100,9 @@ public void test3() { tok.setQuoteChar('"'); tok.setIgnoredMatcher(StrMatcher.noneMatcher()); tok.setIgnoreEmptyTokens(false); - final String tokens[] = tok.getTokenArray(); + final String[] tokens = tok.getTokenArray(); - final String expected[] = new String[]{"a", "b", " c", "d;\"e", "f", " ", " ", ""}; + final String[] expected = new String[]{"a", "b", " c", "d;\"e", "f", " ", " ", ""}; assertEquals(expected.length, tokens.length, ArrayUtils.toString(tokens)); for (int i = 0; i < expected.length; i++) { @@ -121,9 +121,9 @@ public void test4() { tok.setQuoteChar('"'); tok.setIgnoredMatcher(StrMatcher.trimMatcher()); tok.setIgnoreEmptyTokens(true); - final String tokens[] = tok.getTokenArray(); + final String[] tokens = tok.getTokenArray(); - final String expected[] = new String[]{"a", "b", "c", "d;\"e", "f"}; + final String[] expected = new String[]{"a", "b", "c", "d;\"e", "f"}; assertEquals(expected.length, tokens.length, ArrayUtils.toString(tokens)); for (int i = 0; i < expected.length; i++) { @@ -143,9 +143,9 @@ public void test5() { tok.setIgnoredMatcher(StrMatcher.trimMatcher()); tok.setIgnoreEmptyTokens(false); tok.setEmptyTokenAsNull(true); - final String tokens[] = tok.getTokenArray(); + final String[] tokens = tok.getTokenArray(); - final String expected[] = new String[]{"a", "b", "c", "d;\"e", "f", null, null, null}; + final String[] expected = new String[]{"a", "b", "c", "d;\"e", "f", null, null, null}; assertEquals(expected.length, tokens.length, ArrayUtils.toString(tokens)); for (int i = 0; i < expected.length; i++) { @@ -165,9 +165,9 @@ public void test6() { tok.setIgnoredMatcher(StrMatcher.trimMatcher()); tok.setIgnoreEmptyTokens(false); // tok.setTreatingEmptyAsNull(true); - final String tokens[] = tok.getTokenArray(); + final String[] tokens = tok.getTokenArray(); - final String expected[] = new String[]{"a", "b", " c", "d;\"e", "f", null, null, null}; + final String[] expected = new String[]{"a", "b", " c", "d;\"e", "f", null, null, null}; int nextCount = 0; while (tok.hasNext()) { @@ -198,9 +198,9 @@ public void test7() { tok.setQuoteMatcher(StrMatcher.doubleQuoteMatcher()); tok.setIgnoredMatcher(StrMatcher.noneMatcher()); tok.setIgnoreEmptyTokens(false); - final String tokens[] = tok.getTokenArray(); + final String[] tokens = tok.getTokenArray(); - final String expected[] = new String[]{"a", "", "", "b", "c", "d e", "f", ""}; + final String[] expected = new String[]{"a", "", "", "b", "c", "d e", "f", ""}; assertEquals(expected.length, tokens.length, ArrayUtils.toString(tokens)); for (int i = 0; i < expected.length; i++) { @@ -219,9 +219,9 @@ public void test8() { tok.setQuoteMatcher(StrMatcher.doubleQuoteMatcher()); tok.setIgnoredMatcher(StrMatcher.noneMatcher()); tok.setIgnoreEmptyTokens(true); - final String tokens[] = tok.getTokenArray(); + final String[] tokens = tok.getTokenArray(); - final String expected[] = new String[]{"a", "b", "c", "d e", "f"}; + final String[] expected = new String[]{"a", "b", "c", "d e", "f"}; assertEquals(expected.length, tokens.length, ArrayUtils.toString(tokens)); for (int i = 0; i < expected.length; i++) { From 367f39ee29d5536d1e3e5e39f5c0d8ec41eee6fb Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sat, 13 Jun 2020 11:06:56 -0400 Subject: [PATCH 0120/3230] [LANG-1553] Change array style from `int a[]` to `int[] a` #537. --- src/changes/changes.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index b4957d166df..060625aa9df 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -67,6 +67,7 @@ The type attribute can be add,update,fix,remove. Use StandardCharsets.UTF_8 #548. Use Collections.singletonList insteadof Arrays.asList when there be only one element. #549. Refine Javadoc #545. + Change array style from `int a[]` to `int[] a` #537. From 6dd1cf3c6d03cabcd660f536ec625fde1396e950 Mon Sep 17 00:00:00 2001 From: XenoAmess Date: Sat, 13 Jun 2020 23:08:33 +0800 Subject: [PATCH 0121/3230] addAll_to_constructor (#536) --- .../apache/commons/lang3/text/ExtendedMessageFormatTest.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/test/java/org/apache/commons/lang3/text/ExtendedMessageFormatTest.java b/src/test/java/org/apache/commons/lang3/text/ExtendedMessageFormatTest.java index a7e8b3bdf62..cf89945976f 100644 --- a/src/test/java/org/apache/commons/lang3/text/ExtendedMessageFormatTest.java +++ b/src/test/java/org/apache/commons/lang3/text/ExtendedMessageFormatTest.java @@ -115,8 +115,7 @@ public void testExtendedAndBuiltInFormats() { final String extendedPattern = "Name: {0,upper} "; final String pattern = extendedPattern + builtinsPattern; - final HashSet testLocales = new HashSet<>(); - testLocales.addAll(Arrays.asList(DateFormat.getAvailableLocales())); + final HashSet testLocales = new HashSet<>(Arrays.asList(DateFormat.getAvailableLocales())); testLocales.retainAll(Arrays.asList(NumberFormat.getAvailableLocales())); testLocales.add(null); From 57d4777d288022281e5d6befcb02a86e45d0dd44 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sat, 13 Jun 2020 11:09:03 -0400 Subject: [PATCH 0122/3230] [LANG-1552] Change from addAll to constructors for some List #536. --- src/changes/changes.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 060625aa9df..9f9880cfa74 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -68,6 +68,7 @@ The type attribute can be add,update,fix,remove. Use Collections.singletonList insteadof Arrays.asList when there be only one element. #549. Refine Javadoc #545. Change array style from `int a[]` to `int[] a` #537. + Change from addAll to constructors for some List #536. From 0e17c1e93c5a5e5adf930d945a3235cc09361d7c Mon Sep 17 00:00:00 2001 From: XenoAmess Date: Sat, 13 Jun 2020 23:11:17 +0800 Subject: [PATCH 0123/3230] fix_typos (#539) --- .../org/apache/commons/lang3/ClassLoaderUtils.java | 4 ++-- src/main/java/org/apache/commons/lang3/Locks.java | 4 ++-- .../apache/commons/lang3/reflect/MemberUtils.java | 4 ++-- .../org/apache/commons/lang3/time/DateUtils.java | 4 ++-- .../java/org/apache/commons/lang3/EnumUtilsTest.java | 12 ++++++------ .../apache/commons/lang3/event/EventUtilsTest.java | 8 ++++---- .../lang3/text/ExtendedMessageFormatTest.java | 6 +++--- .../commons/lang3/time/FastDateParserTest.java | 2 +- 8 files changed, 22 insertions(+), 22 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/ClassLoaderUtils.java b/src/main/java/org/apache/commons/lang3/ClassLoaderUtils.java index 95cdd2aabab..a87156a0859 100644 --- a/src/main/java/org/apache/commons/lang3/ClassLoaderUtils.java +++ b/src/main/java/org/apache/commons/lang3/ClassLoaderUtils.java @@ -31,7 +31,7 @@ public class ClassLoaderUtils { * Converts the given class loader to a String calling {@link #toString(URLClassLoader)}. * * @param classLoader to URLClassLoader to convert. - * @return the formated string. + * @return the formatted string. */ public static String toString(final ClassLoader classLoader) { if (classLoader instanceof URLClassLoader) { @@ -45,7 +45,7 @@ public static String toString(final ClassLoader classLoader) { * {@code "URLClassLoader.toString() + [URL1, URL2, ...]"}. * * @param classLoader to URLClassLoader to convert. - * @return the formated string. + * @return the formatted string. */ public static String toString(final URLClassLoader classLoader) { return classLoader + Arrays.toString(classLoader.getURLs()); diff --git a/src/main/java/org/apache/commons/lang3/Locks.java b/src/main/java/org/apache/commons/lang3/Locks.java index 6bb800b5cfe..b8fcc45b4aa 100644 --- a/src/main/java/org/apache/commons/lang3/Locks.java +++ b/src/main/java/org/apache/commons/lang3/Locks.java @@ -37,7 +37,7 @@ * references to the locked object. Instead, use references to the lock. *
    2. If you want to access the locked object, create a {@link FailableConsumer}. The consumer * will receive the locked object as a parameter. For convenience, the consumer may be - * implemented as a Lamba. Then invoke {@link Locks.Lock#runReadLocked(FailableConsumer)}, + * implemented as a Lambda. Then invoke {@link Locks.Lock#runReadLocked(FailableConsumer)}, * or {@link Locks.Lock#runWriteLocked(FailableConsumer)}, passing the consumer.
    3. *
    4. As an alternative, if you need to produce a result object, you may use a * {@link FailableFunction}. This function may also be implemented as a Lambda. To @@ -51,7 +51,7 @@ * private final Lock<PrintStream> lock; * * public SimpleLogger(OutputStream out) { - * PrintStream ps = new Printstream(out); + * PrintStream ps = new PrintStream(out); * lock = Locks.lock(ps); * } * diff --git a/src/main/java/org/apache/commons/lang3/reflect/MemberUtils.java b/src/main/java/org/apache/commons/lang3/reflect/MemberUtils.java index 73fa2f1c03d..83b9ca5a0ca 100644 --- a/src/main/java/org/apache/commons/lang3/reflect/MemberUtils.java +++ b/src/main/java/org/apache/commons/lang3/reflect/MemberUtils.java @@ -162,14 +162,14 @@ private static float getTotalTransformationCost(final Class[] srcArgs, final // When isVarArgs is true, srcArgs and dstArgs may differ in length. // There are two special cases to consider: final boolean noVarArgsPassed = srcArgs.length < destArgs.length; - final boolean explicitArrayForVarags = srcArgs.length == destArgs.length && srcArgs[srcArgs.length-1] != null && srcArgs[srcArgs.length-1].isArray(); + final boolean explicitArrayForVarargs = srcArgs.length == destArgs.length && srcArgs[srcArgs.length-1] != null && srcArgs[srcArgs.length-1].isArray(); final float varArgsCost = 0.001f; final Class destClass = destArgs[destArgs.length-1].getComponentType(); if (noVarArgsPassed) { // When no varargs passed, the best match is the most generic matching type, not the most specific. totalCost += getObjectTransformationCost(destClass, Object.class) + varArgsCost; - } else if (explicitArrayForVarags) { + } else if (explicitArrayForVarargs) { final Class sourceClass = srcArgs[srcArgs.length-1].getComponentType(); totalCost += getObjectTransformationCost(sourceClass, destClass) + varArgsCost; } else { diff --git a/src/main/java/org/apache/commons/lang3/time/DateUtils.java b/src/main/java/org/apache/commons/lang3/time/DateUtils.java index 300b7ea94ee..078c21e6af9 100644 --- a/src/main/java/org/apache/commons/lang3/time/DateUtils.java +++ b/src/main/java/org/apache/commons/lang3/time/DateUtils.java @@ -352,7 +352,7 @@ public static Date parseDateStrictly(final String str, final Locale locale, fina * If no parse patterns match, a ParseException is thrown.

      * * @param str the date to parse, not null - * @param locale the locale to use when interpretting the pattern, can be null in which + * @param locale the locale to use when interpreting the pattern, can be null in which * case the default system locale is used * @param parsePatterns the date format patterns to use, see SimpleDateFormat, not null * @param lenient Specify whether or not date/time parsing is to be lenient. @@ -1055,7 +1055,7 @@ private static void modify(final Calendar val, final int field, final ModifyType if (aField[0] == Calendar.DATE) { //If we're going to drop the DATE field's value, // we want to do this our own way. - //We need to subtrace 1 since the date has a minimum of 1 + //We need to subtract 1 since the date has a minimum of 1 offset = val.get(Calendar.DATE) - 1; //If we're above 15 days adjustment, that means we're in the // bottom half of the month and should stay accordingly. diff --git a/src/test/java/org/apache/commons/lang3/EnumUtilsTest.java b/src/test/java/org/apache/commons/lang3/EnumUtilsTest.java index 1e79f457146..1f9d3a3d6fb 100644 --- a/src/test/java/org/apache/commons/lang3/EnumUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/EnumUtilsTest.java @@ -292,7 +292,7 @@ public void test_generateBitVector() { assertEquals(6L, EnumUtils.generateBitVector(Traffic.class, EnumSet.of(Traffic.AMBER, Traffic.GREEN))); assertEquals(7L, EnumUtils.generateBitVector(Traffic.class, EnumSet.of(Traffic.RED, Traffic.AMBER, Traffic.GREEN))); - // 64 values Enum (to test whether no int<->long jdk convertion issue exists) + // 64 values Enum (to test whether no int<->long jdk conversion issue exists) assertEquals((1L << 31), EnumUtils.generateBitVector(Enum64.class, EnumSet.of(Enum64.A31))); assertEquals((1L << 32), EnumUtils.generateBitVector(Enum64.class, EnumSet.of(Enum64.A32))); assertEquals((1L << 63), EnumUtils.generateBitVector(Enum64.class, EnumSet.of(Enum64.A63))); @@ -310,7 +310,7 @@ public void test_generateBitVectors() { assertArrayEquals(EnumUtils.generateBitVectors(Traffic.class, EnumSet.of(Traffic.AMBER, Traffic.GREEN)), 6L); assertArrayEquals(EnumUtils.generateBitVectors(Traffic.class, EnumSet.of(Traffic.RED, Traffic.AMBER, Traffic.GREEN)), 7L); - // 64 values Enum (to test whether no int<->long jdk convertion issue exists) + // 64 values Enum (to test whether no int<->long jdk conversion issue exists) assertArrayEquals(EnumUtils.generateBitVectors(Enum64.class, EnumSet.of(Enum64.A31)), (1L << 31)); assertArrayEquals(EnumUtils.generateBitVectors(Enum64.class, EnumSet.of(Enum64.A32)), (1L << 32)); assertArrayEquals(EnumUtils.generateBitVectors(Enum64.class, EnumSet.of(Enum64.A63)), (1L << 63)); @@ -334,7 +334,7 @@ public void test_generateBitVectorFromArray() { //gracefully handles duplicates: assertEquals(7L, EnumUtils.generateBitVector(Traffic.class, Traffic.RED, Traffic.AMBER, Traffic.GREEN, Traffic.GREEN)); - // 64 values Enum (to test whether no int<->long jdk convertion issue exists) + // 64 values Enum (to test whether no int<->long jdk conversion issue exists) assertEquals((1L << 31), EnumUtils.generateBitVector(Enum64.class, Enum64.A31)); assertEquals((1L << 32), EnumUtils.generateBitVector(Enum64.class, Enum64.A32)); assertEquals((1L << 63), EnumUtils.generateBitVector(Enum64.class, Enum64.A63)); @@ -354,7 +354,7 @@ public void test_generateBitVectorsFromArray() { //gracefully handles duplicates: assertArrayEquals(EnumUtils.generateBitVectors(Traffic.class, Traffic.RED, Traffic.AMBER, Traffic.GREEN, Traffic.GREEN), 7L); - // 64 values Enum (to test whether no int<->long jdk convertion issue exists) + // 64 values Enum (to test whether no int<->long jdk conversion issue exists) assertArrayEquals(EnumUtils.generateBitVectors(Enum64.class, Enum64.A31), (1L << 31)); assertArrayEquals(EnumUtils.generateBitVectors(Enum64.class, Enum64.A32), (1L << 32)); assertArrayEquals(EnumUtils.generateBitVectors(Enum64.class, Enum64.A63), (1L << 63)); @@ -393,7 +393,7 @@ public void test_processBitVector() { assertEquals(EnumSet.of(Traffic.AMBER, Traffic.GREEN), EnumUtils.processBitVector(Traffic.class, 6L)); assertEquals(EnumSet.of(Traffic.RED, Traffic.AMBER, Traffic.GREEN), EnumUtils.processBitVector(Traffic.class, 7L)); - // 64 values Enum (to test whether no int<->long jdk convertion issue exists) + // 64 values Enum (to test whether no int<->long jdk conversion issue exists) assertEquals(EnumSet.of(Enum64.A31), EnumUtils.processBitVector(Enum64.class, (1L << 31))); assertEquals(EnumSet.of(Enum64.A32), EnumUtils.processBitVector(Enum64.class, (1L << 32))); assertEquals(EnumSet.of(Enum64.A63), EnumUtils.processBitVector(Enum64.class, (1L << 63))); @@ -430,7 +430,7 @@ public void test_processBitVectors() { assertEquals(EnumSet.of(Traffic.AMBER, Traffic.GREEN), EnumUtils.processBitVectors(Traffic.class, 666L, 6L)); assertEquals(EnumSet.of(Traffic.RED, Traffic.AMBER, Traffic.GREEN), EnumUtils.processBitVectors(Traffic.class, 666L, 7L)); - // 64 values Enum (to test whether no int<->long jdk convertion issue exists) + // 64 values Enum (to test whether no int<->long jdk conversion issue exists) assertEquals(EnumSet.of(Enum64.A31), EnumUtils.processBitVectors(Enum64.class, (1L << 31))); assertEquals(EnumSet.of(Enum64.A32), EnumUtils.processBitVectors(Enum64.class, (1L << 32))); assertEquals(EnumSet.of(Enum64.A63), EnumUtils.processBitVectors(Enum64.class, (1L << 63))); diff --git a/src/test/java/org/apache/commons/lang3/event/EventUtilsTest.java b/src/test/java/org/apache/commons/lang3/event/EventUtilsTest.java index 1736e1380aa..6352301ade8 100644 --- a/src/test/java/org/apache/commons/lang3/event/EventUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/event/EventUtilsTest.java @@ -55,7 +55,7 @@ public void testConstructor() { @Test public void testAddEventListener() { final PropertyChangeSource src = new PropertyChangeSource(); - final EventCountingInvociationHandler handler = new EventCountingInvociationHandler(); + final EventCountingInvocationHandler handler = new EventCountingInvocationHandler(); final PropertyChangeListener listener = handler.createListener(PropertyChangeListener.class); assertEquals(0, handler.getEventCount("propertyChange")); EventUtils.addEventListener(src, PropertyChangeListener.class, listener); @@ -67,7 +67,7 @@ public void testAddEventListener() { @Test public void testAddEventListenerWithNoAddMethod() { final PropertyChangeSource src = new PropertyChangeSource(); - final EventCountingInvociationHandler handler = new EventCountingInvociationHandler(); + final EventCountingInvocationHandler handler = new EventCountingInvocationHandler(); final ObjectChangeListener listener = handler.createListener(ObjectChangeListener.class); final IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> EventUtils.addEventListener(src, ObjectChangeListener.class, listener)); @@ -88,7 +88,7 @@ public void testAddEventListenerThrowsException() { @Test public void testAddEventListenerWithPrivateAddMethod() { final PropertyChangeSource src = new PropertyChangeSource(); - final EventCountingInvociationHandler handler = new EventCountingInvociationHandler(); + final EventCountingInvocationHandler handler = new EventCountingInvocationHandler(); final VetoableChangeListener listener = handler.createListener(VetoableChangeListener.class); final IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> EventUtils.addEventListener(src, VetoableChangeListener.class, listener)); @@ -161,7 +161,7 @@ public int getCount() { } - private static class EventCountingInvociationHandler implements InvocationHandler { + private static class EventCountingInvocationHandler implements InvocationHandler { private final Map eventCounts = new TreeMap<>(); public L createListener(final Class listenerType) { diff --git a/src/test/java/org/apache/commons/lang3/text/ExtendedMessageFormatTest.java b/src/test/java/org/apache/commons/lang3/text/ExtendedMessageFormatTest.java index cf89945976f..4a3ad319981 100644 --- a/src/test/java/org/apache/commons/lang3/text/ExtendedMessageFormatTest.java +++ b/src/test/java/org/apache/commons/lang3/text/ExtendedMessageFormatTest.java @@ -291,7 +291,7 @@ public void testBuiltInNumberFormat() { @Test public void testEqualsHashcode() { final Map fmtRegistry = Collections.singletonMap("testfmt", new LowerCaseFormatFactory()); - final Map otherRegitry = Collections.singletonMap("testfmt", new UpperCaseFormatFactory()); + final Map otherRegistry = Collections.singletonMap("testfmt", new UpperCaseFormatFactory()); final String pattern = "Pattern: {0,testfmt}"; final ExtendedMessageFormat emf = new ExtendedMessageFormat(pattern, Locale.US, fmtRegistry); @@ -318,7 +318,7 @@ public void testEqualsHashcode() { assertNotEquals(emf.hashCode(), other.hashCode(), "pattern, hashcode()"); // Different registry - other = new ExtendedMessageFormat(pattern, Locale.US, otherRegitry); + other = new ExtendedMessageFormat(pattern, Locale.US, otherRegistry); assertNotEquals(emf, other, "registry, equals()"); assertNotEquals(emf.hashCode(), other.hashCode(), "registry, hashcode()"); @@ -354,7 +354,7 @@ private void checkBuiltInFormat(final String pattern, final Map fmtRe /** * Create an ExtendedMessageFormat for the specified pattern and locale and check the - * formated output matches the expected result for the parameters. + * formatted output matches the expected result for the parameters. * @param pattern string * @param registryUnused map (currently unused) * @param args Object[] diff --git a/src/test/java/org/apache/commons/lang3/time/FastDateParserTest.java b/src/test/java/org/apache/commons/lang3/time/FastDateParserTest.java index f7e2bd4cd48..529d662336f 100644 --- a/src/test/java/org/apache/commons/lang3/time/FastDateParserTest.java +++ b/src/test/java/org/apache/commons/lang3/time/FastDateParserTest.java @@ -1,7 +1,7 @@ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with - * this work for additional inparserion regarding copyright ownership. + * 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 From 0eb4a8f87f11632535afd3a52ce06bd5606383c3 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sat, 13 Jun 2020 11:12:24 -0400 Subject: [PATCH 0124/3230] [LANG-1554] Fix typos #539. --- src/changes/changes.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 9f9880cfa74..99439e46ddf 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -69,6 +69,7 @@ The type attribute can be add,update,fix,remove. Refine Javadoc #545. Change array style from `int a[]` to `int[] a` #537. Change from addAll to constructors for some List #536. + Fix typos #539. From 29b87d5cea51c2e087592db4f2bae7c290efde3d Mon Sep 17 00:00:00 2001 From: XenoAmess Date: Sat, 13 Jun 2020 23:14:45 +0800 Subject: [PATCH 0125/3230] it_shall_not_named_`ignored`_ (#540) --- .../java/org/apache/commons/lang3/reflect/FieldUtils.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/reflect/FieldUtils.java b/src/main/java/org/apache/commons/lang3/reflect/FieldUtils.java index 4d2ce164da3..2a78f5885a0 100644 --- a/src/main/java/org/apache/commons/lang3/reflect/FieldUtils.java +++ b/src/main/java/org/apache/commons/lang3/reflect/FieldUtils.java @@ -740,11 +740,11 @@ public static void removeFinalModifier(final Field field, final boolean forceAcc } } } - } catch (final NoSuchFieldException | IllegalAccessException ignored) { + } catch (final NoSuchFieldException | IllegalAccessException e) { if (SystemUtils.isJavaVersionAtLeast(JavaVersion.JAVA_12)) { throw new UnsupportedOperationException( "In java 12+ final cannot be removed.", - ignored + e ); } // else no exception is thrown because we can modify final. From a9be3ec55bb764f02acf5bb438aee7e1ab660942 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sat, 13 Jun 2020 11:15:29 -0400 Subject: [PATCH 0126/3230] [LANG-1555] Ignored exception `ignored`, should not be called so #540. --- src/changes/changes.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 99439e46ddf..aeb94bfde57 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -70,6 +70,7 @@ The type attribute can be add,update,fix,remove. Change array style from `int a[]` to `int[] a` #537. Change from addAll to constructors for some List #536. Fix typos #539. + Ignored exception `ignored`, should not be called so #540. From fb2d228380eba79585099e4c5737b3e764864d0b Mon Sep 17 00:00:00 2001 From: XenoAmess Date: Sat, 13 Jun 2020 23:17:52 +0800 Subject: [PATCH 0127/3230] simplify_if (#543) --- .../java/org/apache/commons/lang3/builder/ToStringStyle.java | 2 +- .../org/apache/commons/lang3/StringUtilsEqualsIndexOfTest.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/builder/ToStringStyle.java b/src/main/java/org/apache/commons/lang3/builder/ToStringStyle.java index 83d0b5f7533..aa834969851 100644 --- a/src/main/java/org/apache/commons/lang3/builder/ToStringStyle.java +++ b/src/main/java/org/apache/commons/lang3/builder/ToStringStyle.java @@ -439,7 +439,7 @@ public void appendEnd(final StringBuffer buffer, final Object object) { protected void removeLastFieldSeparator(final StringBuffer buffer) { final int len = buffer.length(); final int sepLen = fieldSeparator.length(); - if (len > 0 && sepLen > 0 && len >= sepLen) { + if (sepLen > 0 && len >= sepLen) { boolean match = true; for (int i = 0; i < sepLen; i++) { if (buffer.charAt(len - 1 - i) != fieldSeparator.charAt(sepLen - 1 - i)) { diff --git a/src/test/java/org/apache/commons/lang3/StringUtilsEqualsIndexOfTest.java b/src/test/java/org/apache/commons/lang3/StringUtilsEqualsIndexOfTest.java index 642f973421c..32a9f58dc35 100644 --- a/src/test/java/org/apache/commons/lang3/StringUtilsEqualsIndexOfTest.java +++ b/src/test/java/org/apache/commons/lang3/StringUtilsEqualsIndexOfTest.java @@ -76,7 +76,7 @@ public CharSequence subSequence(final int start, final int end) { @Override public boolean equals(final Object obj) { - if (obj == null || !(obj instanceof CustomCharSequence)) { + if (!(obj instanceof CustomCharSequence)) { return false; } final CustomCharSequence other = (CustomCharSequence) obj; From 1e0b744dd274a9fb82f075c2bbe2164b02a623e3 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sat, 13 Jun 2020 11:18:27 -0400 Subject: [PATCH 0128/3230] [LANG-1558] Simplify if as some conditions are covered by others #543. --- src/changes/changes.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index aeb94bfde57..6c7d13cb45a 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -71,6 +71,7 @@ The type attribute can be add,update,fix,remove. Change from addAll to constructors for some List #536. Fix typos #539. Ignored exception `ignored`, should not be called so #540. + Simplify if as some conditions are covered by others #543. From 48ee23a7dda0caa8b737507ed3485cda7a1924b2 Mon Sep 17 00:00:00 2001 From: XenoAmess Date: Sat, 13 Jun 2020 23:19:29 +0800 Subject: [PATCH 0129/3230] Sting_to_StringBuilder (#544) --- .../apache/commons/lang3/StringUtilsTest.java | 24 +++++++++---------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/src/test/java/org/apache/commons/lang3/StringUtilsTest.java b/src/test/java/org/apache/commons/lang3/StringUtilsTest.java index a1eb66a579c..5c252d777bf 100644 --- a/src/test/java/org/apache/commons/lang3/StringUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/StringUtilsTest.java @@ -60,29 +60,29 @@ public class StringUtilsTest { static final String NON_TRIMMABLE; static { - String ws = ""; - String nws = ""; + StringBuilder ws = new StringBuilder(); + StringBuilder nws = new StringBuilder(); final String hs = String.valueOf(((char) 160)); - String tr = ""; - String ntr = ""; + StringBuilder tr = new StringBuilder(); + StringBuilder ntr = new StringBuilder(); for (int i = 0; i < Character.MAX_VALUE; i++) { if (Character.isWhitespace((char) i)) { - ws += String.valueOf((char) i); + ws.append(String.valueOf((char) i)); if (i > 32) { - ntr += String.valueOf((char) i); + ntr.append(String.valueOf((char) i)); } } else if (i < 40) { - nws += String.valueOf((char) i); + nws.append(String.valueOf((char) i)); } } for (int i = 0; i <= 32; i++) { - tr += String.valueOf((char) i); + tr.append(String.valueOf((char) i)); } - WHITESPACE = ws; - NON_WHITESPACE = nws; + WHITESPACE = ws.toString(); + NON_WHITESPACE = nws.toString(); HARD_SPACE = hs; - TRIMMABLE = tr; - NON_TRIMMABLE = ntr; + TRIMMABLE = tr.toString(); + NON_TRIMMABLE = ntr.toString(); } private static final String[] ARRAY_LIST = {"foo", "bar", "baz"}; From 995dba307c9dd9e27dd602c3e1d5250c7d556643 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sat, 13 Jun 2020 11:20:23 -0400 Subject: [PATCH 0130/3230] [LANG-1559] convert Sting to StringBuilder in some test code. #544. --- src/changes/changes.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 6c7d13cb45a..812f5350f7a 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -72,6 +72,7 @@ The type attribute can be add,update,fix,remove. Fix typos #539. Ignored exception `ignored`, should not be called so #540. Simplify if as some conditions are covered by others #543. + Convert Sting to StringBuilder in some test code. #544. From d62d4e21ef20ee01e65cbf5257e04d6b572aa73b Mon Sep 17 00:00:00 2001 From: Edwin Delgado H <1545116+edelgadoh@users.noreply.github.com> Date: Sat, 13 Jun 2020 12:31:07 -0300 Subject: [PATCH 0131/3230] [LANG-1528] replaceEachRepeatedly gives IllegalStateException (#505) * Fix https://issues.apache.org/jira/browse/LANG-1528 * Fix https://issues.apache.org/jira/browse/LANG-1528 Co-authored-by: Edwin DH --- .../org/apache/commons/lang3/StringUtils.java | 19 +++++++++++------ .../apache/commons/lang3/StringUtilsTest.java | 21 ++++++++++--------- 2 files changed, 24 insertions(+), 16 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/StringUtils.java b/src/main/java/org/apache/commons/lang3/StringUtils.java index f9143c52f3c..7dc92861927 100644 --- a/src/main/java/org/apache/commons/lang3/StringUtils.java +++ b/src/main/java/org/apache/commons/lang3/StringUtils.java @@ -25,6 +25,8 @@ import java.util.List; import java.util.Locale; import java.util.Objects; +import java.util.HashSet; +import java.util.Set; import java.util.function.Supplier; import java.util.regex.Pattern; @@ -6684,14 +6686,19 @@ private static String replaceEach( // mchyzer Performance note: This creates very few new objects (one major goal) // let me know if there are performance requests, we can create a harness to measure - if (isEmpty(text) || ArrayUtils.isEmpty(searchList) || ArrayUtils.isEmpty(replacementList)) { - return text; - } - // if recursing, this shouldn't be less than 0 if (timeToLive < 0) { - throw new IllegalStateException("Aborting to protect against StackOverflowError - " + - "output of one loop is the input of another"); + Set searchSet = new HashSet<>(Arrays.asList(searchList)); + Set replacementSet = new HashSet<>(Arrays.asList(replacementList)); + searchSet.retainAll(replacementSet); + if (searchSet.size() > 0) { + throw new IllegalStateException("Aborting to protect against StackOverflowError - " + + "output of one loop is the input of another"); + } + } + + if (isEmpty(text) || ArrayUtils.isEmpty(searchList) || ArrayUtils.isEmpty(replacementList) || (ArrayUtils.isNotEmpty(searchList) && timeToLive == -1)) { + return text; } final int searchLength = searchList.length; diff --git a/src/test/java/org/apache/commons/lang3/StringUtilsTest.java b/src/test/java/org/apache/commons/lang3/StringUtilsTest.java index 5c252d777bf..a83a34befb4 100644 --- a/src/test/java/org/apache/commons/lang3/StringUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/StringUtilsTest.java @@ -1894,16 +1894,17 @@ public void testReplace_StringStringArrayStringArray() { public void testReplace_StringStringArrayStringArrayBoolean() { //JAVADOC TESTS START assertNull(StringUtils.replaceEachRepeatedly(null, new String[]{"a"}, new String[]{"b"})); - assertEquals(StringUtils.replaceEachRepeatedly("", new String[]{"a"}, new String[]{"b"}), ""); - assertEquals(StringUtils.replaceEachRepeatedly("aba", null, null), "aba"); - assertEquals(StringUtils.replaceEachRepeatedly("aba", new String[0], null), "aba"); - assertEquals(StringUtils.replaceEachRepeatedly("aba", null, new String[0]), "aba"); - assertEquals(StringUtils.replaceEachRepeatedly("aba", new String[0], null), "aba"); - - assertEquals(StringUtils.replaceEachRepeatedly("aba", new String[]{"a"}, new String[]{""}), "b"); - assertEquals(StringUtils.replaceEachRepeatedly("aba", new String[]{null}, new String[]{"a"}), "aba"); - assertEquals(StringUtils.replaceEachRepeatedly("abcde", new String[]{"ab", "d"}, new String[]{"w", "t"}), "wcte"); - assertEquals(StringUtils.replaceEachRepeatedly("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"}), "tcte"); + assertEquals("", StringUtils.replaceEachRepeatedly("", new String[]{"a"}, new String[]{"b"})); + assertEquals("aba", StringUtils.replaceEachRepeatedly("aba", null, null)); + assertEquals("aba", StringUtils.replaceEachRepeatedly("aba", new String[0], null)); + assertEquals("aba", StringUtils.replaceEachRepeatedly("aba", null, new String[0])); + assertEquals("aba", StringUtils.replaceEachRepeatedly("aba", new String[0], null)); + + assertEquals("b", StringUtils.replaceEachRepeatedly("aba", new String[]{"a"}, new String[]{""})); + assertEquals("aba", StringUtils.replaceEachRepeatedly("aba", new String[]{null}, new String[]{"a"})); + assertEquals("wcte", StringUtils.replaceEachRepeatedly("abcde", new String[]{"ab", "d"}, new String[]{"w", "t"})); + assertEquals("tcte", StringUtils.replaceEachRepeatedly("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"})); + assertEquals("blaan", StringUtils.replaceEachRepeatedly("blllaan", new String[]{"llaan"}, new String[]{"laan"}) ); assertThrows( IllegalStateException.class, From 553a3a75dfafbf50d7efd8d6e88da71a637a2aa7 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sat, 13 Jun 2020 11:33:08 -0400 Subject: [PATCH 0132/3230] [LANG-1528] StringUtils.replaceEachRepeatedly gives IllegalStateException #505. --- src/changes/changes.xml | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 812f5350f7a..7df3f372c7e 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -62,17 +62,17 @@ The type attribute can be add,update,fix,remove. Added the Locks class as a convenient possibility to deal with locked objects. Add to Functions: FailableBooleanSupplier, FailableIntSupplier, FailableLongSupplier, FailableDoubleSupplier, and so on. Add ArrayUtils.get(T[], index, T) to provide an out-of-bounds default value. - Optimize ArrayUtils::isArrayIndexValid method. #551. - Use List.sort instead of Collection.sort #546. - Use StandardCharsets.UTF_8 #548. - Use Collections.singletonList insteadof Arrays.asList when there be only one element. #549. - Refine Javadoc #545. - Change array style from `int a[]` to `int[] a` #537. - Change from addAll to constructors for some List #536. - Fix typos #539. - Ignored exception `ignored`, should not be called so #540. - Simplify if as some conditions are covered by others #543. - Convert Sting to StringBuilder in some test code. #544. + Optimize ArrayUtils::isArrayIndexValid method. #551. + Use List.sort instead of Collection.sort #546. + Use StandardCharsets.UTF_8 #548. + Use Collections.singletonList insteadof Arrays.asList when there be only one element. #549. + Refine Javadoc #545. + Change array style from `int a[]` to `int[] a` #537. + Change from addAll to constructors for some List #536. + Fix typos #539. + Ignored exception `ignored`, should not be called so #540. + Simplify if as some conditions are covered by others #543. + StringUtils.replaceEachRepeatedly gives IllegalStateException #505. From 496eb10372c0161eac4729e758d789357adfcc0f Mon Sep 17 00:00:00 2001 From: Edgar Asatryan <17509127+nstdio@users.noreply.github.com> Date: Sat, 13 Jun 2020 22:05:33 +0400 Subject: [PATCH 0133/3230] Use ArrayUtils::isArrayIndexValid method in ArrayUtils::get. (#552) --- src/main/java/org/apache/commons/lang3/ArrayUtils.java | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/ArrayUtils.java b/src/main/java/org/apache/commons/lang3/ArrayUtils.java index dd9b5ca1eed..ffd250de48f 100644 --- a/src/main/java/org/apache/commons/lang3/ArrayUtils.java +++ b/src/main/java/org/apache/commons/lang3/ArrayUtils.java @@ -1679,13 +1679,7 @@ public static T get(final T[] array, final int index) { * @since 3.11 */ public static T get(final T[] array, final int index, final T defaultValue) { - if (array == null) { - return defaultValue; - } - if (index >= 0 && index < array.length) { - return array[index]; - } - return defaultValue; + return isArrayIndexValid(array, index) ? array[index] : defaultValue; } //----------------------------------------------------------------------- From 628044f75ab1b38541090d5aa4e932d36b18078b Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sat, 13 Jun 2020 16:04:57 -0400 Subject: [PATCH 0134/3230] Sort methods. --- src/test/java/org/apache/commons/lang3/FunctionsTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/test/java/org/apache/commons/lang3/FunctionsTest.java b/src/test/java/org/apache/commons/lang3/FunctionsTest.java index 3c462f83e33..bf73add6837 100644 --- a/src/test/java/org/apache/commons/lang3/FunctionsTest.java +++ b/src/test/java/org/apache/commons/lang3/FunctionsTest.java @@ -116,9 +116,9 @@ public void test() throws Throwable { } public static class Testable { - private Throwable throwable; - private P acceptedPrimitiveObject; private T acceptedObject; + private P acceptedPrimitiveObject; + private Throwable throwable; Testable(final Throwable throwable) { this.throwable = throwable; From 306dbb0cb01f565bf04d8879cad9b413d94d4af5 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sat, 13 Jun 2020 16:06:26 -0400 Subject: [PATCH 0135/3230] Add missiing "test --- src/test/java/org/apache/commons/lang3/FunctionsTest.java | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/test/java/org/apache/commons/lang3/FunctionsTest.java b/src/test/java/org/apache/commons/lang3/FunctionsTest.java index bf73add6837..51699c225dd 100644 --- a/src/test/java/org/apache/commons/lang3/FunctionsTest.java +++ b/src/test/java/org/apache/commons/lang3/FunctionsTest.java @@ -235,6 +235,12 @@ public void testObjLong(T object, long i) throws Throwable { } } + @Test + public void testConstructor() { + // We allow this, which must be an omission to make the ctor private. + new Functions(); + } + @Test void testAcceptBiConsumer() { final IllegalStateException ise = new IllegalStateException(); From 494a4db395718d2cd9880ee02144ebff7c57ad27 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sat, 13 Jun 2020 16:09:58 -0400 Subject: [PATCH 0136/3230] Disable Clirr since we use JApiCmp. --- pom.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/pom.xml b/pom.xml index d8f68a9f80a..428266fbfcc 100644 --- a/pom.xml +++ b/pom.xml @@ -605,6 +605,7 @@ 4.0.0 false + true 1.21 From 31d7eea1c6205066b91c79f19219a436b26e9060 Mon Sep 17 00:00:00 2001 From: Edgar Asatryan <17509127+nstdio@users.noreply.github.com> Date: Sun, 14 Jun 2020 02:30:38 +0400 Subject: [PATCH 0137/3230] [LANG-1570] JavaVersion enum constants for Java 14 and 15. (#553) --- .../org/apache/commons/lang3/JavaVersion.java | 18 ++++++++++++++++++ .../apache/commons/lang3/JavaVersionTest.java | 6 +++++- 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/apache/commons/lang3/JavaVersion.java b/src/main/java/org/apache/commons/lang3/JavaVersion.java index e287c9ffec8..d275607b9a4 100644 --- a/src/main/java/org/apache/commons/lang3/JavaVersion.java +++ b/src/main/java/org/apache/commons/lang3/JavaVersion.java @@ -115,6 +115,20 @@ public enum JavaVersion { */ JAVA_13(13.0f, "13"), + /** + * Java 14 + * + * @since 3.11 + */ + JAVA_14(14.0f, "14"), + + /** + * Java 15 + * + * @since 3.11 + */ + JAVA_15(15.0f, "15"), + /** * The most recent java version. Mainly introduced to avoid to break when a new version of Java is used. */ @@ -224,6 +238,10 @@ static JavaVersion get(final String nom) { return JAVA_12; } else if ("13".equals(nom)) { return JAVA_13; + } else if ("14".equals(nom)) { + return JAVA_14; + } else if ("15".equals(nom)) { + return JAVA_15; } final float v = toFloatVersion(nom); if ((v - 1.) < 1.) { // then we need to check decimals > .9 diff --git a/src/test/java/org/apache/commons/lang3/JavaVersionTest.java b/src/test/java/org/apache/commons/lang3/JavaVersionTest.java index 64d8f820a72..c06b57c6b82 100644 --- a/src/test/java/org/apache/commons/lang3/JavaVersionTest.java +++ b/src/test/java/org/apache/commons/lang3/JavaVersionTest.java @@ -25,6 +25,8 @@ import static org.apache.commons.lang3.JavaVersion.JAVA_11; import static org.apache.commons.lang3.JavaVersion.JAVA_12; import static org.apache.commons.lang3.JavaVersion.JAVA_13; +import static org.apache.commons.lang3.JavaVersion.JAVA_14; +import static org.apache.commons.lang3.JavaVersion.JAVA_15; import static org.apache.commons.lang3.JavaVersion.JAVA_1_1; import static org.apache.commons.lang3.JavaVersion.JAVA_1_2; import static org.apache.commons.lang3.JavaVersion.JAVA_1_3; @@ -62,10 +64,12 @@ public void testGetJavaVersion() { assertEquals(JAVA_11, get("11"), "11 failed"); assertEquals(JAVA_12, get("12"), "12 failed"); assertEquals(JAVA_13, get("13"), "13 failed"); + assertEquals(JAVA_14, get("14"), "14 failed"); + assertEquals(JAVA_15, get("15"), "15 failed"); assertEquals(JAVA_RECENT, get("1.10"), "1.10 failed"); // assertNull("2.10 unexpectedly worked", get("2.10")); assertEquals(get("1.5"), getJavaVersion("1.5"), "Wrapper method failed"); - assertEquals(JAVA_RECENT, get("14"), "Unhandled"); // LANG-1384 + assertEquals(JAVA_RECENT, get("16"), "Unhandled"); // LANG-1384 } @Test From 4e3151a8ff86a5c00b2b660e6598c5d5d60ce004 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sat, 13 Jun 2020 18:31:58 -0400 Subject: [PATCH 0138/3230] [LANG-1570] JavaVersion enum constants for Java 14 and 15. #553. --- src/changes/changes.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 7df3f372c7e..14a2aa972ad 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -73,6 +73,7 @@ The type attribute can be add,update,fix,remove. Ignored exception `ignored`, should not be called so #540. Simplify if as some conditions are covered by others #543. StringUtils.replaceEachRepeatedly gives IllegalStateException #505. + JavaVersion enum constants for Java 14 and 15. #553. From 78c1c7f9ab79cbdb8fe4469e41858a9308257cda Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sat, 13 Jun 2020 18:32:37 -0400 Subject: [PATCH 0139/3230] [LANG-1570] JavaVersion enum constants for Java 14 and 15. #553. --- src/changes/changes.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 14a2aa972ad..68e38bd51ac 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -73,7 +73,7 @@ The type attribute can be add,update,fix,remove. Ignored exception `ignored`, should not be called so #540. Simplify if as some conditions are covered by others #543. StringUtils.replaceEachRepeatedly gives IllegalStateException #505. - JavaVersion enum constants for Java 14 and 15. #553. + Add JavaVersion enum constants for Java 14 and 15. #553. From 797d550a92d7df12ebc83e3c5e3fafa61a2a8ce3 Mon Sep 17 00:00:00 2001 From: XenoAmess Date: Sun, 14 Jun 2020 06:33:29 +0800 Subject: [PATCH 0140/3230] [LANG-1556] Use Java 8 lambdas and Map operations. (#541) * java8 * refine * rebase --- src/main/java/org/apache/commons/lang3/Streams.java | 4 +--- .../apache/commons/lang3/concurrent/TimedSemaphore.java | 2 +- .../commons/lang3/exception/DefaultExceptionContext.java | 8 +------- .../org/apache/commons/lang3/reflect/MethodUtils.java | 2 +- .../java/org/apache/commons/lang3/reflect/TypeUtils.java | 6 ++++-- .../org/apache/commons/lang3/time/FastDateParser.java | 2 +- .../java/org/apache/commons/lang3/ArrayUtilsTest.java | 2 +- src/test/java/org/apache/commons/lang3/FunctionsTest.java | 6 +++--- 8 files changed, 13 insertions(+), 19 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/Streams.java b/src/main/java/org/apache/commons/lang3/Streams.java index 337a0fd79c9..125aefec9fd 100644 --- a/src/main/java/org/apache/commons/lang3/Streams.java +++ b/src/main/java/org/apache/commons/lang3/Streams.java @@ -450,9 +450,7 @@ public Supplier> supplier() { @Override public BiConsumer, O> accumulator() { - return (list, o) -> { - list.add(o); - }; + return List::add; } @Override diff --git a/src/main/java/org/apache/commons/lang3/concurrent/TimedSemaphore.java b/src/main/java/org/apache/commons/lang3/concurrent/TimedSemaphore.java index 6bea0694036..23c3cf3eb46 100644 --- a/src/main/java/org/apache/commons/lang3/concurrent/TimedSemaphore.java +++ b/src/main/java/org/apache/commons/lang3/concurrent/TimedSemaphore.java @@ -417,7 +417,7 @@ protected ScheduledExecutorService getExecutorService() { * @return a future object representing the task scheduled */ protected ScheduledFuture startTimer() { - return getExecutorService().scheduleAtFixedRate(() -> endOfPeriod(), getPeriod(), getPeriod(), getUnit()); + return getExecutorService().scheduleAtFixedRate(this::endOfPeriod, getPeriod(), getPeriod(), getUnit()); } /** diff --git a/src/main/java/org/apache/commons/lang3/exception/DefaultExceptionContext.java b/src/main/java/org/apache/commons/lang3/exception/DefaultExceptionContext.java index 20a3e177263..638674261e2 100644 --- a/src/main/java/org/apache/commons/lang3/exception/DefaultExceptionContext.java +++ b/src/main/java/org/apache/commons/lang3/exception/DefaultExceptionContext.java @@ -19,7 +19,6 @@ import java.io.Serializable; import java.util.ArrayList; import java.util.HashSet; -import java.util.Iterator; import java.util.List; import java.util.Set; @@ -60,12 +59,7 @@ public DefaultExceptionContext addContextValue(final String label, final Object */ @Override public DefaultExceptionContext setContextValue(final String label, final Object value) { - for (final Iterator> iter = contextValues.iterator(); iter.hasNext();) { - final Pair p = iter.next(); - if (StringUtils.equals(label, p.getKey())) { - iter.remove(); - } - } + contextValues.removeIf(p -> StringUtils.equals(label, p.getKey())); addContextValue(label, value); return this; } diff --git a/src/main/java/org/apache/commons/lang3/reflect/MethodUtils.java b/src/main/java/org/apache/commons/lang3/reflect/MethodUtils.java index 1e9b96ee1a8..63260e8dfde 100644 --- a/src/main/java/org/apache/commons/lang3/reflect/MethodUtils.java +++ b/src/main/java/org/apache/commons/lang3/reflect/MethodUtils.java @@ -60,7 +60,7 @@ */ public class MethodUtils { - private static final Comparator METHOD_BY_SIGNATURE = (m1, m2) -> m1.toString().compareTo(m2.toString()); + private static final Comparator METHOD_BY_SIGNATURE = Comparator.comparing(Method::toString); /** *

      {@link MethodUtils} instances should NOT be constructed in standard programming. diff --git a/src/main/java/org/apache/commons/lang3/reflect/TypeUtils.java b/src/main/java/org/apache/commons/lang3/reflect/TypeUtils.java index aea37a7f882..a20f62b16af 100644 --- a/src/main/java/org/apache/commons/lang3/reflect/TypeUtils.java +++ b/src/main/java/org/apache/commons/lang3/reflect/TypeUtils.java @@ -875,8 +875,10 @@ private static Map, Type> getTypeArguments( // map the arguments to their respective type variables for (int i = 0; i < typeParams.length; i++) { final Type typeArg = typeArgs[i]; - typeVarAssigns.put(typeParams[i], typeVarAssigns.containsKey(typeArg) ? typeVarAssigns - .get(typeArg) : typeArg); + typeVarAssigns.put( + typeParams[i], + typeVarAssigns.getOrDefault(typeArg, typeArg) + ); } if (toClass.equals(cls)) { diff --git a/src/main/java/org/apache/commons/lang3/time/FastDateParser.java b/src/main/java/org/apache/commons/lang3/time/FastDateParser.java index 233cf3f675c..fcc8dcf0549 100644 --- a/src/main/java/org/apache/commons/lang3/time/FastDateParser.java +++ b/src/main/java/org/apache/commons/lang3/time/FastDateParser.java @@ -94,7 +94,7 @@ public class FastDateParser implements DateParser, Serializable { // comparator used to sort regex alternatives // alternatives should be ordered longer first, and shorter last. ('february' before 'feb') // all entries must be lowercase by locale. - private static final Comparator LONGER_FIRST_LOWERCASE = (left, right) -> right.compareTo(left); + private static final Comparator LONGER_FIRST_LOWERCASE = Comparator.reverseOrder(); /** *

      Constructs a new FastDateParser.

      diff --git a/src/test/java/org/apache/commons/lang3/ArrayUtilsTest.java b/src/test/java/org/apache/commons/lang3/ArrayUtilsTest.java index db9b5abb673..78d61f0a703 100644 --- a/src/test/java/org/apache/commons/lang3/ArrayUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/ArrayUtilsTest.java @@ -1499,7 +1499,7 @@ public void testIsSortedChar() { @Test public void testIsSortedComparator() { - final Comparator c = (o1, o2) -> o2.compareTo(o1); + final Comparator c = Comparator.reverseOrder(); Integer[] array = null; assertTrue(ArrayUtils.isSorted(array, c)); diff --git a/src/test/java/org/apache/commons/lang3/FunctionsTest.java b/src/test/java/org/apache/commons/lang3/FunctionsTest.java index 51699c225dd..3a4128b0219 100644 --- a/src/test/java/org/apache/commons/lang3/FunctionsTest.java +++ b/src/test/java/org/apache/commons/lang3/FunctionsTest.java @@ -579,7 +579,7 @@ void testAsCallable() { FailureOnOddInvocations.invocations = 0; final FailableCallable failableCallable = FailureOnOddInvocations::new; final Callable callable = Functions.asCallable(failableCallable); - final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, () -> callable.call()); + final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, callable::call); final Throwable cause = e.getCause(); assertNotNull(cause); assertTrue(cause instanceof SomeException); @@ -663,7 +663,7 @@ public void testAsPredicate() { void testAsRunnable() { FailureOnOddInvocations.invocations = 0; final Runnable runnable = Functions.asRunnable(FailureOnOddInvocations::new); - final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, () -> runnable.run()); + final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, runnable::run); final Throwable cause = e.getCause(); assertNotNull(cause); assertTrue(cause instanceof SomeException); @@ -678,7 +678,7 @@ public void testAsSupplier() { FailureOnOddInvocations.invocations = 0; final FailableSupplier failableSupplier = FailureOnOddInvocations::new; final Supplier supplier = Functions.asSupplier(failableSupplier); - final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, () -> supplier.get()); + final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, supplier::get); final Throwable cause = e.getCause(); assertNotNull(cause); assertTrue(cause instanceof SomeException); From e2c0396660c19e2839000e0b9ffddbf956c40292 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sat, 13 Jun 2020 18:34:51 -0400 Subject: [PATCH 0141/3230] [LANG-1556] Use Java 8 lambdas and Map operations. #541 --- src/changes/changes.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 68e38bd51ac..d8af54e9d00 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -74,6 +74,7 @@ The type attribute can be add,update,fix,remove. Simplify if as some conditions are covered by others #543. StringUtils.replaceEachRepeatedly gives IllegalStateException #505. Add JavaVersion enum constants for Java 14 and 15. #553. + Use Java 8 lambdas and Map operations.
      From 9fcd9c86edc05a0bd25f8eb73cf840400e5e6b95 Mon Sep 17 00:00:00 2001 From: XenoAmess Date: Sun, 14 Jun 2020 07:04:23 +0800 Subject: [PATCH 0142/3230] fix checkstyle. --- src/test/java/org/apache/commons/lang3/FunctionsTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/org/apache/commons/lang3/FunctionsTest.java b/src/test/java/org/apache/commons/lang3/FunctionsTest.java index 3a4128b0219..907f6e49e4b 100644 --- a/src/test/java/org/apache/commons/lang3/FunctionsTest.java +++ b/src/test/java/org/apache/commons/lang3/FunctionsTest.java @@ -240,7 +240,7 @@ public void testConstructor() { // We allow this, which must be an omission to make the ctor private. new Functions(); } - + @Test void testAcceptBiConsumer() { final IllegalStateException ise = new IllegalStateException(); From 1406f67252c3ef919c1045ab2183fb03d2bd5464 Mon Sep 17 00:00:00 2001 From: XenoAmess Date: Sun, 14 Jun 2020 21:43:59 +0800 Subject: [PATCH 0143/3230] [LANG-1565] change removeLastFieldSeparator to use endsWith (#550) * change_removeLastFieldSeparator_to_use_endsWith * stylecheck * revert mis-changes about orders of imports. --- .../commons/lang3/builder/ToStringStyle.java | 15 ++------------- 1 file changed, 2 insertions(+), 13 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/builder/ToStringStyle.java b/src/main/java/org/apache/commons/lang3/builder/ToStringStyle.java index aa834969851..9b115739bcf 100644 --- a/src/main/java/org/apache/commons/lang3/builder/ToStringStyle.java +++ b/src/main/java/org/apache/commons/lang3/builder/ToStringStyle.java @@ -437,19 +437,8 @@ public void appendEnd(final StringBuffer buffer, final Object object) { * @since 2.0 */ protected void removeLastFieldSeparator(final StringBuffer buffer) { - final int len = buffer.length(); - final int sepLen = fieldSeparator.length(); - if (sepLen > 0 && len >= sepLen) { - boolean match = true; - for (int i = 0; i < sepLen; i++) { - if (buffer.charAt(len - 1 - i) != fieldSeparator.charAt(sepLen - 1 - i)) { - match = false; - break; - } - } - if (match) { - buffer.setLength(len - sepLen); - } + if (StringUtils.endsWith(buffer, fieldSeparator)) { + buffer.setLength(buffer.length() - fieldSeparator.length()); } } From ab7b6734d3fbcffd75d0550c68530dbe1da708fa Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sun, 14 Jun 2020 09:44:53 -0400 Subject: [PATCH 0144/3230] [LANG-1565] change removeLastFieldSeparator to use endsWith #550. --- src/changes/changes.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index d8af54e9d00..b44baa78903 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -75,6 +75,7 @@ The type attribute can be add,update,fix,remove. StringUtils.replaceEachRepeatedly gives IllegalStateException #505. Add JavaVersion enum constants for Java 14 and 15. #553. Use Java 8 lambdas and Map operations. + Change removeLastFieldSeparator to use endsWith #550. From 677604fb8439a39e1f97343026c64928afcb121a Mon Sep 17 00:00:00 2001 From: XenoAmess Date: Sun, 14 Jun 2020 21:46:53 +0800 Subject: [PATCH 0145/3230] [LANG-1557] Change a Pattern to a static final field, for not letting it compile each time the function invoked. (#542) * Pattern_to_static_ * move the constants to head of the file. * Simplify private comment. Co-authored-by: Gary Gregory --- src/main/java/org/apache/commons/lang3/StringUtils.java | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/StringUtils.java b/src/main/java/org/apache/commons/lang3/StringUtils.java index 7dc92861927..507cba02e93 100644 --- a/src/main/java/org/apache/commons/lang3/StringUtils.java +++ b/src/main/java/org/apache/commons/lang3/StringUtils.java @@ -179,6 +179,11 @@ public class StringUtils { */ private static final int PAD_LIMIT = 8192; + /** + * Pattern used in {@link #stripAccents(String)}. + */ + private static final Pattern STRIP_ACCENTS_PATTERN = Pattern.compile("\\p{InCombiningDiacriticalMarks}+"); //$NON-NLS-1$ + // Abbreviating //----------------------------------------------------------------------- /** @@ -8215,11 +8220,10 @@ public static String stripAccents(final String input) { if (input == null) { return null; } - final Pattern pattern = Pattern.compile("\\p{InCombiningDiacriticalMarks}+"); //$NON-NLS-1$ final StringBuilder decomposed = new StringBuilder(Normalizer.normalize(input, Normalizer.Form.NFD)); convertRemainingAccentCharacters(decomposed); // Note that this doesn't correctly remove ligatures... - return pattern.matcher(decomposed).replaceAll(EMPTY); + return STRIP_ACCENTS_PATTERN.matcher(decomposed).replaceAll(EMPTY); } // StripAll From 9d1c7bc17c8344d751e1a5aaa8c94f4cd7118f73 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sun, 14 Jun 2020 09:47:49 -0400 Subject: [PATCH 0146/3230] LANG-1557] Change a Pattern to a static final field, for not letting it compile each time the function invoked. #542 --- src/changes/changes.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index b44baa78903..69a8b365d7f 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -76,6 +76,7 @@ The type attribute can be add,update,fix,remove. Add JavaVersion enum constants for Java 14 and 15. #553. Use Java 8 lambdas and Map operations. Change removeLastFieldSeparator to use endsWith #550. + Change a Pattern to a static final field, for not letting it compile each time the function invoked. #542. From 133327272a3c7466ff53acff875b473556d0a4b2 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sun, 14 Jun 2020 14:59:02 -0400 Subject: [PATCH 0147/3230] Sort members. --- .../java/org/apache/commons/lang3/FunctionsTest.java | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/test/java/org/apache/commons/lang3/FunctionsTest.java b/src/test/java/org/apache/commons/lang3/FunctionsTest.java index 907f6e49e4b..043f135fbf8 100644 --- a/src/test/java/org/apache/commons/lang3/FunctionsTest.java +++ b/src/test/java/org/apache/commons/lang3/FunctionsTest.java @@ -235,12 +235,6 @@ public void testObjLong(T object, long i) throws Throwable { } } - @Test - public void testConstructor() { - // We allow this, which must be an omission to make the ctor private. - new Functions(); - } - @Test void testAcceptBiConsumer() { final IllegalStateException ise = new IllegalStateException(); @@ -698,6 +692,12 @@ void testCallable() { assertNotNull(instance); } + @Test + public void testConstructor() { + // We allow this, which must be an omission to make the ctor private. + new Functions(); + } + @Test public void testGetAsBooleanSupplier() { final IllegalStateException ise = new IllegalStateException(); From 7f90306f909e6dba46be275c0f492c8de353b492 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sun, 14 Jun 2020 19:27:23 -0400 Subject: [PATCH 0148/3230] [LANG-1568] More failable functional interfaces to match JRE functional interfaces. --- .../org/apache/commons/lang3/Functions.java | 476 ++++- .../apache/commons/lang3/FunctionsTest.java | 1562 ++++++++++++++--- 2 files changed, 1798 insertions(+), 240 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/Functions.java b/src/main/java/org/apache/commons/lang3/Functions.java index 0f701f498bf..0eeef4473ac 100644 --- a/src/main/java/org/apache/commons/lang3/Functions.java +++ b/src/main/java/org/apache/commons/lang3/Functions.java @@ -27,18 +27,36 @@ import java.util.function.BiPredicate; import java.util.function.BooleanSupplier; import java.util.function.Consumer; +import java.util.function.DoubleBinaryOperator; import java.util.function.DoubleConsumer; +import java.util.function.DoubleFunction; import java.util.function.DoubleSupplier; +import java.util.function.DoubleToIntFunction; +import java.util.function.DoubleToLongFunction; import java.util.function.Function; +import java.util.function.IntBinaryOperator; import java.util.function.IntConsumer; +import java.util.function.IntFunction; import java.util.function.IntSupplier; +import java.util.function.IntToDoubleFunction; +import java.util.function.IntToLongFunction; +import java.util.function.LongBinaryOperator; import java.util.function.LongConsumer; +import java.util.function.LongFunction; import java.util.function.LongSupplier; +import java.util.function.LongToDoubleFunction; +import java.util.function.LongToIntFunction; import java.util.function.ObjDoubleConsumer; import java.util.function.ObjIntConsumer; import java.util.function.ObjLongConsumer; import java.util.function.Predicate; import java.util.function.Supplier; +import java.util.function.ToDoubleBiFunction; +import java.util.function.ToDoubleFunction; +import java.util.function.ToIntBiFunction; +import java.util.function.ToIntFunction; +import java.util.function.ToLongBiFunction; +import java.util.function.ToLongFunction; import java.util.stream.Stream; import org.apache.commons.lang3.Streams.FailableStream; @@ -79,7 +97,7 @@ public class Functions { /** - * A functional interface like {@link BiConsumer} that declares a Throwable. + * A functional interface like {@link BiConsumer} that declares a {@code Throwable}. * * @param Consumed type 1. * @param Consumed type 2. @@ -99,15 +117,15 @@ public interface FailableBiConsumer { } /** - * A functional interface like {@link BiFunction} that declares a Throwable. + * A functional interface like {@link BiFunction} that declares a {@code Throwable}. * - * @param Input type 1. - * @param Input type 2. + * @param Input type 1. + * @param Input type 2. * @param Return type. * @param Thrown exception. */ @FunctionalInterface - public interface FailableBiFunction { + public interface FailableBiFunction { /** * Applies this function. @@ -115,20 +133,20 @@ public interface FailableBiFunction { * @param input1 the first input for the function * @param input2 the second input for the function * @return the result of the function - * @throws T if the function fails + * @throws T Thrown when the function fails. */ - R apply(I1 input1, I2 input2) throws T; + R apply(O1 input1, O2 input2) throws T; } /** - * A functional interface like {@link BiPredicate} that declares a Throwable. + * A functional interface like {@link BiPredicate} that declares a {@code Throwable}. * - * @param Predicate type 1. - * @param Predicate type 2. + * @param Predicate type 1. + * @param Predicate type 2. * @param Thrown exception. */ @FunctionalInterface - public interface FailableBiPredicate { + public interface FailableBiPredicate { /** * Tests the predicate. @@ -138,11 +156,11 @@ public interface FailableBiPredicate { * @return the predicate's evaluation * @throws T if the predicate fails */ - boolean test(I1 object1, I2 object2) throws T; + boolean test(O1 object1, O2 object2) throws T; } /** - * A functional interface like {@link BooleanSupplier} that declares a Throwable. + * A functional interface like {@link BooleanSupplier} that declares a {@code Throwable}. * * @param Thrown exception. * @since 3.11 @@ -160,7 +178,7 @@ public interface FailableBooleanSupplier { } /** - * A functional interface like {@link java.util.concurrent.Callable} that declares a Throwable. + * A functional interface like {@link java.util.concurrent.Callable} that declares a {@code Throwable}. * * @param Return type. * @param Thrown exception. @@ -178,7 +196,7 @@ public interface FailableCallable { } /** - * A functional interface like {@link Consumer} that declares a Throwable. + * A functional interface like {@link Consumer} that declares a {@code Throwable}. * * @param Consumed type 1. * @param Thrown exception. @@ -196,7 +214,27 @@ public interface FailableConsumer { } /** - * A functional interface like {@link DoubleConsumer} that declares a Throwable. + * A functional interface like {@link DoubleBinaryOperator} that declares a {@code Throwable}. + * + * @param Thrown exception. + * @since 3.11 + */ + @FunctionalInterface + public interface FailableDoubleBinaryOperator { + + /** + * Applies this operator to the given operands. + * + * @param left the first operand + * @param right the second operand + * @return the operator result + * @throws T if the operation fails + */ + double applyAsDouble(double left, double right) throws T; + } + + /** + * A functional interface like {@link DoubleConsumer} that declares a {@code Throwable}. * * @param Thrown exception. * @since 3.11 @@ -214,7 +252,26 @@ public interface FailableDoubleConsumer { } /** - * A functional interface like {@link DoubleSupplier} that declares a Throwable. + * A functional interface like {@link DoubleFunction} that declares a {@code Throwable}. + * + * @param Return type. + * @param Thrown exception. + */ + @FunctionalInterface + public interface FailableDoubleFunction { + + /** + * Applies this function. + * + * @param input the input for the function + * @return the result of the function + * @throws T Thrown when the function fails. + */ + R apply(double input) throws T; + } + + /** + * A functional interface like {@link DoubleSupplier} that declares a {@code Throwable}. * * @param Thrown exception. * @since 3.11 @@ -232,7 +289,45 @@ public interface FailableDoubleSupplier { } /** - * A functional interface like {@link Function} that declares a Throwable. + * A functional interface like {@link DoubleToIntFunction} that declares a {@code Throwable}. + * + * @param Thrown exception. + * @since 3.11 + */ + @FunctionalInterface + public interface FailableDoubleToIntFunction { + + /** + * Applies this function to the given argument. + * + * @param value the function argument + * @return the function result + * @throws T Thrown when the function fails. + */ + int applyAsInt(double value) throws T; + } + + /** + * A functional interface like {@link DoubleToLongFunction} that declares a {@code Throwable}. + * + * @param Thrown exception. + * @since 3.11 + */ + @FunctionalInterface + public interface FailableDoubleToLongFunction { + + /** + * Applies this function to the given argument. + * + * @param value the function argument + * @return the function result + * @throws T if the operation fails + */ + int applyAsLong(double value) throws T; + } + + /** + * A functional interface like {@link Function} that declares a {@code Throwable}. * * @param Input type 1. * @param Return type. @@ -246,13 +341,33 @@ public interface FailableFunction { * * @param input the input for the function * @return the result of the function - * @throws T if the function fails + * @throws T Thrown when the function fails. */ R apply(I input) throws T; } /** - * A functional interface like {@link IntConsumer} that declares a Throwable. + * A functional interface like {@link IntBinaryOperator} that declares a {@code Throwable}. + * + * @param Thrown exception. + * @since 3.11 + */ + @FunctionalInterface + public interface FailableIntBinaryOperator { + + /** + * Applies this operator to the given operands. + * + * @param left the first operand + * @param right the second operand + * @return the operator result + * @throws T if the operation fails + */ + int applyAsInt(int left, int right) throws T; + } + + /** + * A functional interface like {@link IntConsumer} that declares a {@code Throwable}. * * @param Thrown exception. * @since 3.11 @@ -270,7 +385,26 @@ public interface FailableIntConsumer { } /** - * A functional interface like {@link IntSupplier} that declares a Throwable. + * A functional interface like {@link IntFunction} that declares a {@code Throwable}. + * + * @param Return type. + * @param Thrown exception. + */ + @FunctionalInterface + public interface FailableIntFunction { + + /** + * Applies this function. + * + * @param input the input for the function + * @return the result of the function + * @throws T Thrown when the function fails. + */ + R apply(int input) throws T; + } + + /** + * A functional interface like {@link IntSupplier} that declares a {@code Throwable}. * * @param Thrown exception. * @since 3.11 @@ -288,7 +422,65 @@ public interface FailableIntSupplier { } /** - * A functional interface like {@link LongConsumer} that declares a Throwable. + * A functional interface like {@link IntToDoubleFunction} that declares a {@code Throwable}. + * + * @param Thrown exception. + * @since 3.11 + */ + @FunctionalInterface + public interface FailableIntToDoubleFunction { + + /** + * Applies this function to the given argument. + * + * @param value the function argument + * @return the function result + * @throws T Thrown when the function fails. + */ + double applyAsDouble(int value) throws T; + } + + /** + * A functional interface like {@link IntToLongFunction} that declares a {@code Throwable}. + * + * @param Thrown exception. + * @since 3.11 + */ + @FunctionalInterface + public interface FailableIntToLongFunction { + + /** + * Applies this function to the given argument. + * + * @param value the function argument + * @return the function result + * @throws T Thrown when the function fails. + */ + long applyAsLong(int value) throws T; + } + + /** + * A functional interface like {@link LongBinaryOperator} that declares a {@code Throwable}. + * + * @param Thrown exception. + * @since 3.11 + */ + @FunctionalInterface + public interface FailableLongBinaryOperator { + + /** + * Applies this operator to the given operands. + * + * @param left the first operand + * @param right the second operand + * @return the operator result + * @throws T if the operation fails + */ + long applyAsLong(long left, long right) throws T; + } + + /** + * A functional interface like {@link LongConsumer} that declares a {@code Throwable}. * * @param Thrown exception. * @since 3.11 @@ -306,7 +498,26 @@ public interface FailableLongConsumer { } /** - * A functional interface like {@link LongSupplier} that declares a Throwable. + * A functional interface like {@link LongFunction} that declares a {@code Throwable}. + * + * @param Return type. + * @param Thrown exception. + */ + @FunctionalInterface + public interface FailableLongFunction { + + /** + * Applies this function. + * + * @param input the input for the function + * @return the result of the function + * @throws T Thrown when the function fails. + */ + R apply(long input) throws T; + } + + /** + * A functional interface like {@link LongSupplier} that declares a {@code Throwable}. * * @param Thrown exception. * @since 3.11 @@ -324,7 +535,45 @@ public interface FailableLongSupplier { } /** - * A functional interface like {@link ObjDoubleConsumer} that declares a Throwable. + * A functional interface like {@link LongToDoubleFunction} that declares a {@code Throwable}. + * + * @param Thrown exception. + * @since 3.11 + */ + @FunctionalInterface + public interface FailableLongToDoubleFunction { + + /** + * Applies this function to the given argument. + * + * @param value the function argument + * @return the function result + * @throws T Thrown when the function fails. + */ + double applyAsDouble(long value) throws T; + } + + /** + * A functional interface like {@link LongToIntFunction} that declares a {@code Throwable}. + * + * @param Thrown exception. + * @since 3.11 + */ + @FunctionalInterface + public interface FailableLongToIntFunction { + + /** + * Applies this function to the given argument. + * + * @param value the function argument + * @return the function result + * @throws T Thrown when the function fails. + */ + int applyAsInt(long value) throws T; + } + + /** + * A functional interface like {@link ObjDoubleConsumer} that declares a {@code Throwable}. * * @param the type of the object argument to the operation. * @param Thrown exception. @@ -344,7 +593,7 @@ public interface FailableObjDoubleConsumer { } /** - * A functional interface like {@link ObjIntConsumer} that declares a Throwable. + * A functional interface like {@link ObjIntConsumer} that declares a {@code Throwable}. * * @param the type of the object argument to the operation. * @param Thrown exception. @@ -364,7 +613,7 @@ public interface FailableObjIntConsumer { } /** - * A functional interface like {@link ObjLongConsumer} that declares a Throwable. + * A functional interface like {@link ObjLongConsumer} that declares a {@code Throwable}. * * @param the type of the object argument to the operation. * @param Thrown exception. @@ -384,7 +633,7 @@ public interface FailableObjLongConsumer { } /** - * A functional interface like {@link Predicate} that declares a Throwable. + * A functional interface like {@link Predicate} that declares a {@code Throwable}. * * @param Predicate type 1. * @param Thrown exception. @@ -403,7 +652,7 @@ public interface FailablePredicate { } /** - * A functional interface like {@link Runnable} that declares a Throwable. + * A functional interface like {@link Runnable} that declares a {@code Throwable}. * * @param Thrown exception. */ @@ -413,13 +662,13 @@ public interface FailableRunnable { /** * Runs the function. * - * @throws T if the function fails + * @throws T Thrown when the function fails. */ void run() throws T; } /** - * A functional interface like {@link Supplier} that declares a Throwable. + * A functional interface like {@link Supplier} that declares a {@code Throwable}. * * @param Return type. * @param Thrown exception. @@ -436,6 +685,132 @@ public interface FailableSupplier { R get() throws T; } + /** + * A functional interface like {@link ToDoubleBiFunction} that declares a {@code Throwable}. + * + * @param the type of the first argument to the function + * @param the type of the second argument to the function + * @param Thrown exception. + * @since 3.11 + */ + @FunctionalInterface + public interface FailableToDoubleBiFunction { + + /** + * Applies this function to the given arguments. + * + * @param t the first function argument + * @param u the second function argument + * @return the function result + * @throws T Thrown when the function fails. + */ + double applyAsDouble(O1 t, O2 u) throws T; + } + + /** + * A functional interface like {@link ToDoubleFunction} that declares a {@code Throwable}. + * + * @param the type of the first argument to the function + * @param Thrown exception. + * @since 3.11 + */ + @FunctionalInterface + public interface FailableToDoubleFunction { + + /** + * Applies this function to the given arguments. + * + * @param t the first function argument + * @return the function result + * @throws T Thrown when the function fails. + */ + double applyAsDouble(I t) throws T; + } + + /** + * A functional interface like {@link ToIntBiFunction} that declares a {@code Throwable}. + * + * @param the type of the first argument to the function + * @param the type of the second argument to the function + * @param Thrown exception. + * @since 3.11 + */ + @FunctionalInterface + public interface FailableToIntBiFunction { + + /** + * Applies this function to the given arguments. + * + * @param t the first function argument + * @param u the second function argument + * @return the function result + * @throws T Thrown when the function fails. + */ + int applyAsInt(O1 t, O2 u) throws T; + } + + /** + * A functional interface like {@link ToIntFunction} that declares a {@code Throwable}. + * + * @param the type of the first argument to the function + * @param Thrown exception. + * @since 3.11 + */ + @FunctionalInterface + public interface FailableToIntFunction { + + /** + * Applies this function to the given arguments. + * + * @param t the first function argument + * @return the function result + * @throws T Thrown when the function fails. + */ + int applyAsInt(I t) throws T; + } + + /** + * A functional interface like {@link ToLongBiFunction} that declares a {@code Throwable}. + * + * @param the type of the first argument to the function + * @param the type of the second argument to the function + * @param Thrown exception. + * @since 3.11 + */ + @FunctionalInterface + public interface FailableToLongBiFunction { + + /** + * Applies this function to the given arguments. + * + * @param t the first function argument + * @param u the second function argument + * @return the function result + * @throws T Thrown when the function fails. + */ + long applyAsLong(O1 t, O2 u) throws T; + } + + /** + * A functional interface like {@link ToLongFunction} that declares a {@code Throwable}. + * + * @param the type of the first argument to the function + * @param Thrown exception. + * @since 3.11 + */ + @FunctionalInterface + public interface FailableToLongFunction { + + /** + * Applies this function to the given arguments. + * + * @param t the first function argument + * @return the function result + * @throws T Thrown when the function fails. + */ + long applyAsLong(I t) throws T; + } + /** * Consumes a consumer and rethrows any exception as a {@link RuntimeException}. * @@ -505,14 +880,14 @@ public static void accept(final FailableLongConsumer co * @param function the function to apply * @param input1 the first input to apply {@code function} on * @param input2 the second input to apply {@code function} on - * @param the type of the first argument the function accepts - * @param the type of the second argument the function accepts + * @param the type of the first argument the function accepts + * @param the type of the second argument the function accepts * @param the return type of the function * @param the type of checked exception the function may throw * @return the value returned from the function */ - public static O apply(final FailableBiFunction function, - final I1 input1, final I2 input2) { + public static O apply(final FailableBiFunction function, + final O1 input1, final O2 input2) { return get(() -> function.apply(input1, input2)); } @@ -530,43 +905,58 @@ public static O apply(final FailableFunction function.apply(input)); } + /** + * Applies a function and rethrows any exception as a {@link RuntimeException}. + * + * @param function the function to apply + * @param left the first input to apply {@code function} on + * @param right the second input to apply {@code function} on + * @param the type of checked exception the function may throw + * @return the value returned from the function + * @since 3.11 + */ + public static double applyAsDouble(final FailableDoubleBinaryOperator function, + final double left, final double right) { + return getAsDouble(() -> function.applyAsDouble(left, right)); + } + /** * Converts the given {@link FailableBiConsumer} into a standard {@link BiConsumer}. * - * @param the type of the first argument of the consumers - * @param the type of the second argument of the consumers + * @param the type of the first argument of the consumers + * @param the type of the second argument of the consumers * @param consumer a failable {@code BiConsumer} * @return a standard {@code BiConsumer} * @since 3.10 */ - public static BiConsumer asBiConsumer(final FailableBiConsumer consumer) { + public static BiConsumer asBiConsumer(final FailableBiConsumer consumer) { return (input1, input2) -> accept(consumer, input1, input2); } /** * Converts the given {@link FailableBiFunction} into a standard {@link BiFunction}. * - * @param the type of the first argument of the input of the functions - * @param the type of the second argument of the input of the functions + * @param the type of the first argument of the input of the functions + * @param the type of the second argument of the input of the functions * @param the type of the output of the functions * @param function a {@code FailableBiFunction} * @return a standard {@code BiFunction} * @since 3.10 */ - public static BiFunction asBiFunction(final FailableBiFunction function) { + public static BiFunction asBiFunction(final FailableBiFunction function) { return (input1, input2) -> apply(function, input1, input2); } /** * Converts the given {@link FailableBiPredicate} into a standard {@link BiPredicate}. * - * @param the type of the first argument used by the predicates - * @param the type of the second argument used by the predicates + * @param the type of the first argument used by the predicates + * @param the type of the second argument used by the predicates * @param predicate a {@code FailableBiPredicate} * @return a standard {@code BiPredicate} * @since 3.10 */ - public static BiPredicate asBiPredicate(final FailableBiPredicate predicate) { + public static BiPredicate asBiPredicate(final FailableBiPredicate predicate) { return (input1, input2) -> test(predicate, input1, input2); } diff --git a/src/test/java/org/apache/commons/lang3/FunctionsTest.java b/src/test/java/org/apache/commons/lang3/FunctionsTest.java index 043f135fbf8..d114224f6d8 100644 --- a/src/test/java/org/apache/commons/lang3/FunctionsTest.java +++ b/src/test/java/org/apache/commons/lang3/FunctionsTest.java @@ -117,7 +117,8 @@ public void test() throws Throwable { public static class Testable { private T acceptedObject; - private P acceptedPrimitiveObject; + private P acceptedPrimitiveObject1; + private P acceptedPrimitiveObject2; private Throwable throwable; Testable(final Throwable throwable) { @@ -128,8 +129,12 @@ public T getAcceptedObject() { return acceptedObject; } - public P getAcceptedPrimitiveObject() { - return acceptedPrimitiveObject; + public P getAcceptedPrimitiveObject1() { + return acceptedPrimitiveObject1; + } + + public P getAcceptedPrimitiveObject2() { + return acceptedPrimitiveObject2; } public void setThrowable(final Throwable throwable) { @@ -140,105 +145,117 @@ public void test() throws Throwable { test(throwable); } + public Object test(Object input1, Object input2) throws Throwable { + test(throwable); + return acceptedObject; + } + public void test(final Throwable throwable) throws Throwable { if (throwable != null) { throw throwable; } } - public boolean testBooleanPrimitive() throws Throwable { - return testBooleanPrimitive(throwable); + public boolean testAsBooleanPrimitive() throws Throwable { + return testAsBooleanPrimitive(throwable); } - public boolean testBooleanPrimitive(final Throwable throwable) throws Throwable { + public boolean testAsBooleanPrimitive(final Throwable throwable) throws Throwable { if (throwable != null) { throw throwable; } return false; } - public void testDouble(double i) throws Throwable { - test(throwable); - acceptedPrimitiveObject = (P) ((Double) i); - } - - public double testDoublePrimitive() throws Throwable { - return testDoublePrimitive(throwable); + public double testAsDoublePrimitive() throws Throwable { + return testAsDoublePrimitive(throwable); } - public double testDoublePrimitive(final Throwable throwable) throws Throwable { + public double testAsDoublePrimitive(final Throwable throwable) throws Throwable { if (throwable != null) { throw throwable; } return 0; } - public void testInt(int i) throws Throwable { - test(throwable); - acceptedPrimitiveObject = (P) ((Integer) i); + public Integer testAsInteger() throws Throwable { + return testAsInteger(throwable); + } + + public Integer testAsInteger(final Throwable throwable) throws Throwable { + if (throwable != null) { + throw throwable; + } + return 0; } - public Integer testInteger() throws Throwable { - return testInteger(throwable); + public int testAsIntPrimitive() throws Throwable { + return testAsIntPrimitive(throwable); } - public Integer testInteger(final Throwable throwable) throws Throwable { + public int testAsIntPrimitive(final Throwable throwable) throws Throwable { if (throwable != null) { throw throwable; } return 0; } - public int testIntPrimitive() throws Throwable { - return testIntPrimitive(throwable); + public long testAsLongPrimitive() throws Throwable { + return testAsLongPrimitive(throwable); } - public int testIntPrimitive(final Throwable throwable) throws Throwable { + public long testAsLongPrimitive(final Throwable throwable) throws Throwable { if (throwable != null) { throw throwable; } return 0; } - public void testLong(long i) throws Throwable { + public void testDouble(double i) throws Throwable { test(throwable); - acceptedPrimitiveObject = (P) ((Long) i); + acceptedPrimitiveObject1 = (P) ((Double) i); } - public long testLongPrimitive() throws Throwable { - return testLongPrimitive(throwable); + public double testDoubleDouble(double i, double j) throws Throwable { + test(throwable); + acceptedPrimitiveObject1 = (P) ((Double) i); + acceptedPrimitiveObject2 = (P) ((Double) j); + return 3d; } - public long testLongPrimitive(final Throwable throwable) throws Throwable { - if (throwable != null) { - throw throwable; - } - return 0; + public void testInt(int i) throws Throwable { + test(throwable); + acceptedPrimitiveObject1 = (P) ((Integer) i); + } + + public void testLong(long i) throws Throwable { + test(throwable); + acceptedPrimitiveObject1 = (P) ((Long) i); } public void testObjDouble(T object, double i) throws Throwable { test(throwable); acceptedObject = object; - acceptedPrimitiveObject = (P) ((Double) i); + acceptedPrimitiveObject1 = (P) ((Double) i); } public void testObjInt(T object, int i) throws Throwable { test(throwable); acceptedObject = object; - acceptedPrimitiveObject = (P) ((Integer) i); + acceptedPrimitiveObject1 = (P) ((Integer) i); } public void testObjLong(T object, long i) throws Throwable { test(throwable); acceptedObject = object; - acceptedPrimitiveObject = (P) ((Long) i); + acceptedPrimitiveObject1 = (P) ((Long) i); } } @Test void testAcceptBiConsumer() { final IllegalStateException ise = new IllegalStateException(); - final Testable testable = new Testable(null); + final Testable testable = new Testable<>(null); Throwable e = assertThrows(IllegalStateException.class, () -> Functions.accept(Testable::test, testable, ise)); assertSame(ise, e); @@ -286,13 +303,13 @@ void testAcceptDoubleConsumer() { final Testable testable = new Testable<>(ise); Throwable e = assertThrows(IllegalStateException.class, () -> Functions.accept(testable::testDouble, 1d)); assertSame(ise, e); - assertNull(testable.getAcceptedPrimitiveObject()); + assertNull(testable.getAcceptedPrimitiveObject1()); final Error error = new OutOfMemoryError(); testable.setThrowable(error); e = assertThrows(OutOfMemoryError.class, () -> Functions.accept(testable::testDouble, 1d)); assertSame(error, e); - assertNull(testable.getAcceptedPrimitiveObject()); + assertNull(testable.getAcceptedPrimitiveObject1()); final IOException ioe = new IOException("Unknown I/O error"); testable.setThrowable(ioe); @@ -300,11 +317,11 @@ void testAcceptDoubleConsumer() { final Throwable t = e.getCause(); assertNotNull(t); assertSame(ioe, t); - assertNull(testable.getAcceptedPrimitiveObject()); + assertNull(testable.getAcceptedPrimitiveObject1()); testable.setThrowable(null); Functions.accept(testable::testDouble, 1d); - assertEquals(1, testable.getAcceptedPrimitiveObject()); + assertEquals(1, testable.getAcceptedPrimitiveObject1()); } @Test @@ -313,13 +330,13 @@ void testAcceptIntConsumer() { final Testable testable = new Testable<>(ise); Throwable e = assertThrows(IllegalStateException.class, () -> Functions.accept(testable::testInt, 1)); assertSame(ise, e); - assertNull(testable.getAcceptedPrimitiveObject()); + assertNull(testable.getAcceptedPrimitiveObject1()); final Error error = new OutOfMemoryError(); testable.setThrowable(error); e = assertThrows(OutOfMemoryError.class, () -> Functions.accept(testable::testInt, 1)); assertSame(error, e); - assertNull(testable.getAcceptedPrimitiveObject()); + assertNull(testable.getAcceptedPrimitiveObject1()); final IOException ioe = new IOException("Unknown I/O error"); testable.setThrowable(ioe); @@ -327,11 +344,11 @@ void testAcceptIntConsumer() { final Throwable t = e.getCause(); assertNotNull(t); assertSame(ioe, t); - assertNull(testable.getAcceptedPrimitiveObject()); + assertNull(testable.getAcceptedPrimitiveObject1()); testable.setThrowable(null); Functions.accept(testable::testInt, 1); - assertEquals(1, testable.getAcceptedPrimitiveObject()); + assertEquals(1, testable.getAcceptedPrimitiveObject1()); } @Test @@ -340,13 +357,13 @@ void testAcceptLongConsumer() { final Testable testable = new Testable<>(ise); Throwable e = assertThrows(IllegalStateException.class, () -> Functions.accept(testable::testLong, 1L)); assertSame(ise, e); - assertNull(testable.getAcceptedPrimitiveObject()); + assertNull(testable.getAcceptedPrimitiveObject1()); final Error error = new OutOfMemoryError(); testable.setThrowable(error); e = assertThrows(OutOfMemoryError.class, () -> Functions.accept(testable::testLong, 1L)); assertSame(error, e); - assertNull(testable.getAcceptedPrimitiveObject()); + assertNull(testable.getAcceptedPrimitiveObject1()); final IOException ioe = new IOException("Unknown I/O error"); testable.setThrowable(ioe); @@ -354,28 +371,29 @@ void testAcceptLongConsumer() { final Throwable t = e.getCause(); assertNotNull(t); assertSame(ioe, t); - assertNull(testable.getAcceptedPrimitiveObject()); + assertNull(testable.getAcceptedPrimitiveObject1()); testable.setThrowable(null); Functions.accept(testable::testLong, 1L); - assertEquals(1, testable.getAcceptedPrimitiveObject()); + assertEquals(1, testable.getAcceptedPrimitiveObject1()); } @Test void testAcceptObjDoubleConsumer() { final IllegalStateException ise = new IllegalStateException(); final Testable testable = new Testable<>(ise); - Throwable e = assertThrows(IllegalStateException.class, () -> Functions.accept(testable::testObjDouble, "X", 1d)); + Throwable e = assertThrows(IllegalStateException.class, + () -> Functions.accept(testable::testObjDouble, "X", 1d)); assertSame(ise, e); assertNull(testable.getAcceptedObject()); - assertNull(testable.getAcceptedPrimitiveObject()); + assertNull(testable.getAcceptedPrimitiveObject1()); final Error error = new OutOfMemoryError(); testable.setThrowable(error); e = assertThrows(OutOfMemoryError.class, () -> Functions.accept(testable::testObjDouble, "X", 1d)); assertSame(error, e); assertNull(testable.getAcceptedObject()); - assertNull(testable.getAcceptedPrimitiveObject()); + assertNull(testable.getAcceptedPrimitiveObject1()); final IOException ioe = new IOException("Unknown I/O error"); testable.setThrowable(ioe); @@ -384,12 +402,12 @@ void testAcceptObjDoubleConsumer() { assertNotNull(t); assertSame(ioe, t); assertNull(testable.getAcceptedObject()); - assertNull(testable.getAcceptedPrimitiveObject()); + assertNull(testable.getAcceptedPrimitiveObject1()); testable.setThrowable(null); Functions.accept(testable::testObjDouble, "X", 1d); assertEquals("X", testable.getAcceptedObject()); - assertEquals(1d, testable.getAcceptedPrimitiveObject()); + assertEquals(1d, testable.getAcceptedPrimitiveObject1()); } @Test @@ -399,14 +417,14 @@ void testAcceptObjIntConsumer() { Throwable e = assertThrows(IllegalStateException.class, () -> Functions.accept(testable::testObjInt, "X", 1)); assertSame(ise, e); assertNull(testable.getAcceptedObject()); - assertNull(testable.getAcceptedPrimitiveObject()); + assertNull(testable.getAcceptedPrimitiveObject1()); final Error error = new OutOfMemoryError(); testable.setThrowable(error); e = assertThrows(OutOfMemoryError.class, () -> Functions.accept(testable::testObjInt, "X", 1)); assertSame(error, e); assertNull(testable.getAcceptedObject()); - assertNull(testable.getAcceptedPrimitiveObject()); + assertNull(testable.getAcceptedPrimitiveObject1()); final IOException ioe = new IOException("Unknown I/O error"); testable.setThrowable(ioe); @@ -415,12 +433,12 @@ void testAcceptObjIntConsumer() { assertNotNull(t); assertSame(ioe, t); assertNull(testable.getAcceptedObject()); - assertNull(testable.getAcceptedPrimitiveObject()); + assertNull(testable.getAcceptedPrimitiveObject1()); testable.setThrowable(null); Functions.accept(testable::testObjInt, "X", 1); assertEquals("X", testable.getAcceptedObject()); - assertEquals(1, testable.getAcceptedPrimitiveObject()); + assertEquals(1, testable.getAcceptedPrimitiveObject1()); } @Test @@ -430,14 +448,14 @@ void testAcceptObjLongConsumer() { Throwable e = assertThrows(IllegalStateException.class, () -> Functions.accept(testable::testObjLong, "X", 1L)); assertSame(ise, e); assertNull(testable.getAcceptedObject()); - assertNull(testable.getAcceptedPrimitiveObject()); + assertNull(testable.getAcceptedPrimitiveObject1()); final Error error = new OutOfMemoryError(); testable.setThrowable(error); e = assertThrows(OutOfMemoryError.class, () -> Functions.accept(testable::testObjLong, "X", 1L)); assertSame(error, e); assertNull(testable.getAcceptedObject()); - assertNull(testable.getAcceptedPrimitiveObject()); + assertNull(testable.getAcceptedPrimitiveObject1()); final IOException ioe = new IOException("Unknown I/O error"); testable.setThrowable(ioe); @@ -446,244 +464,221 @@ void testAcceptObjLongConsumer() { assertNotNull(t); assertSame(ioe, t); assertNull(testable.getAcceptedObject()); - assertNull(testable.getAcceptedPrimitiveObject()); + assertNull(testable.getAcceptedPrimitiveObject1()); testable.setThrowable(null); Functions.accept(testable::testObjLong, "X", 1L); assertEquals("X", testable.getAcceptedObject()); - assertEquals(1L, testable.getAcceptedPrimitiveObject()); + assertEquals(1L, testable.getAcceptedPrimitiveObject1()); } @Test public void testApplyBiFunction() { final IllegalStateException ise = new IllegalStateException(); - final Testable testable = new Testable(null); - Throwable e = assertThrows(IllegalStateException.class, () -> Functions.apply(Testable::testInteger, testable, ise)); + final Testable testable = new Testable<>(null); + Throwable e = assertThrows(IllegalStateException.class, + () -> Functions.apply(Testable::testAsInteger, testable, ise)); assertSame(ise, e); final Error error = new OutOfMemoryError(); - e = assertThrows(OutOfMemoryError.class, () -> Functions.apply(Testable::testInteger, testable, error)); + e = assertThrows(OutOfMemoryError.class, () -> Functions.apply(Testable::testAsInteger, testable, error)); assertSame(error, e); final IOException ioe = new IOException("Unknown I/O error"); - e = assertThrows(UncheckedIOException.class, () -> Functions.apply(Testable::testInteger, testable, ioe)); + e = assertThrows(UncheckedIOException.class, () -> Functions.apply(Testable::testAsInteger, testable, ioe)); final Throwable t = e.getCause(); assertNotNull(t); assertSame(ioe, t); - final Integer i = Functions.apply(Testable::testInteger, testable, (Throwable) null); + final Integer i = Functions.apply(Testable::testAsInteger, testable, (Throwable) null); assertNotNull(i); assertEquals(0, i.intValue()); } + @Test + public void testApplyDoubleBinaryOperator() { + final IllegalStateException ise = new IllegalStateException(); + final Testable testable = new Testable<>(ise); + Throwable e = assertThrows(IllegalStateException.class, + () -> Functions.applyAsDouble(testable::testDoubleDouble, 1d, 2d)); + assertSame(ise, e); + + final Testable testable2 = new Testable<>(null); + final double i = Functions.applyAsDouble(testable2::testDoubleDouble, 1d, 2d); + assertEquals(3d, i); + } + @Test public void testApplyFunction() { final IllegalStateException ise = new IllegalStateException(); final Testable testable = new Testable<>(ise); - Throwable e = assertThrows(IllegalStateException.class, () -> Functions.apply(Testable::testInteger, testable)); + Throwable e = assertThrows(IllegalStateException.class, + () -> Functions.apply(Testable::testAsInteger, testable)); assertSame(ise, e); final Error error = new OutOfMemoryError(); testable.setThrowable(error); - e = assertThrows(OutOfMemoryError.class, () -> Functions.apply(Testable::testInteger, testable)); + e = assertThrows(OutOfMemoryError.class, () -> Functions.apply(Testable::testAsInteger, testable)); assertSame(error, e); final IOException ioe = new IOException("Unknown I/O error"); testable.setThrowable(ioe); - e = assertThrows(UncheckedIOException.class, () -> Functions.apply(Testable::testInteger, testable)); + e = assertThrows(UncheckedIOException.class, () -> Functions.apply(Testable::testAsInteger, testable)); final Throwable t = e.getCause(); assertNotNull(t); assertSame(ioe, t); testable.setThrowable(null); - final Integer i = Functions.apply(Testable::testInteger, testable); + final Integer i = Functions.apply(Testable::testAsInteger, testable); assertNotNull(i); assertEquals(0, i.intValue()); } @Test - void testAsBiConsumer() { - final IllegalStateException ise = new IllegalStateException(); - final Testable testable = new Testable(null); - final FailableBiConsumer failableBiConsumer = (t, th) -> { - t.setThrowable(th); t.test(); - }; - final BiConsumer consumer = Functions.asBiConsumer(failableBiConsumer); - Throwable e = assertThrows(IllegalStateException.class, () -> consumer.accept(testable, ise)); - assertSame(ise, e); - - final Error error = new OutOfMemoryError(); - e = assertThrows(OutOfMemoryError.class, () -> consumer.accept(testable, error)); - assertSame(error, e); - - final IOException ioe = new IOException("Unknown I/O error"); - testable.setThrowable(ioe); - e = assertThrows(UncheckedIOException.class, () -> consumer.accept(testable, ioe)); - final Throwable t = e.getCause(); - assertNotNull(t); - assertSame(ioe, t); - - consumer.accept(testable, null); + void testAsCallable() { + FailureOnOddInvocations.invocations = 0; + final FailableCallable failableCallable = FailureOnOddInvocations::new; + final Callable callable = Functions.asCallable(failableCallable); + final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, callable::call); + final Throwable cause = e.getCause(); + assertNotNull(cause); + assertTrue(cause instanceof SomeException); + assertEquals("Odd Invocation: 1", cause.getMessage()); + final FailureOnOddInvocations instance; + try { + instance = callable.call(); + } catch (final Exception ex) { + throw Functions.rethrow(ex); + } + assertNotNull(instance); } @Test - public void testAsBiFunction() { + void testAsConsumer() { final IllegalStateException ise = new IllegalStateException(); final Testable testable = new Testable<>(ise); - final FailableBiFunction failableBiFunction = (t, th) -> { - t.setThrowable(th); - return Integer.valueOf(t.testInteger()); - }; - final BiFunction biFunction = Functions.asBiFunction(failableBiFunction); - Throwable e = assertThrows(IllegalStateException.class, () -> biFunction.apply(testable, ise)); + final Consumer> consumer = Functions.asConsumer(Testable::test); + Throwable e = assertThrows(IllegalStateException.class, () -> consumer.accept(testable)); assertSame(ise, e); final Error error = new OutOfMemoryError(); testable.setThrowable(error); - e = assertThrows(OutOfMemoryError.class, () -> biFunction.apply(testable, error)); + e = assertThrows(OutOfMemoryError.class, () -> consumer.accept(testable)); assertSame(error, e); final IOException ioe = new IOException("Unknown I/O error"); testable.setThrowable(ioe); - e = assertThrows(UncheckedIOException.class, () -> biFunction.apply(testable, ioe)); + e = assertThrows(UncheckedIOException.class, () -> consumer.accept(testable)); final Throwable t = e.getCause(); assertNotNull(t); assertSame(ioe, t); - assertEquals(0, biFunction.apply(testable, null).intValue()); + testable.setThrowable(null); + Functions.accept(Testable::test, testable); } @Test - @DisplayName("Test that asPredicate(FailableBiPredicate) is converted to -> BiPredicate ") - public void testAsBiPredicate() { + void testAsRunnable() { FailureOnOddInvocations.invocations = 0; - final Functions.FailableBiPredicate failableBiPredicate = (t1, t2) -> FailureOnOddInvocations.failingBool(); - final BiPredicate predicate = Functions.asBiPredicate(failableBiPredicate); - final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, () -> predicate.test(null, null)); + final Runnable runnable = Functions.asRunnable(FailureOnOddInvocations::new); + final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, runnable::run); final Throwable cause = e.getCause(); assertNotNull(cause); assertTrue(cause instanceof SomeException); assertEquals("Odd Invocation: 1", cause.getMessage()); - final boolean instance = predicate.test(null, null); - assertNotNull(instance); + + // Even invocations, should not throw an exception + runnable.run(); } @Test - void testAsCallable() { + public void testAsSupplier() { FailureOnOddInvocations.invocations = 0; - final FailableCallable failableCallable = FailureOnOddInvocations::new; - final Callable callable = Functions.asCallable(failableCallable); - final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, callable::call); + final FailableSupplier failableSupplier = FailureOnOddInvocations::new; + final Supplier supplier = Functions.asSupplier(failableSupplier); + final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, supplier::get); final Throwable cause = e.getCause(); assertNotNull(cause); assertTrue(cause instanceof SomeException); assertEquals("Odd Invocation: 1", cause.getMessage()); - final FailureOnOddInvocations instance; - try { - instance = callable.call(); - } catch (final Exception ex) { - throw Functions.rethrow(ex); - } - assertNotNull(instance); + assertNotNull(supplier.get()); } @Test - void testAsConsumer() { + void testBiConsumer() { final IllegalStateException ise = new IllegalStateException(); - final Testable testable = new Testable<>(ise); - final Consumer consumer = Functions.asConsumer(Testable::test); - Throwable e = assertThrows(IllegalStateException.class, () -> consumer.accept(testable)); + final Testable testable = new Testable<>(null); + final FailableBiConsumer, Throwable, Throwable> failableBiConsumer = (t, th) -> { + t.setThrowable(th); + t.test(); + }; + final BiConsumer, Throwable> consumer = Functions.asBiConsumer(failableBiConsumer); + Throwable e = assertThrows(IllegalStateException.class, () -> consumer.accept(testable, ise)); assertSame(ise, e); final Error error = new OutOfMemoryError(); - testable.setThrowable(error); - e = assertThrows(OutOfMemoryError.class, () -> consumer.accept(testable)); + e = assertThrows(OutOfMemoryError.class, () -> consumer.accept(testable, error)); assertSame(error, e); final IOException ioe = new IOException("Unknown I/O error"); testable.setThrowable(ioe); - e = assertThrows(UncheckedIOException.class, () -> consumer.accept(testable)); + e = assertThrows(UncheckedIOException.class, () -> consumer.accept(testable, ioe)); final Throwable t = e.getCause(); assertNotNull(t); assertSame(ioe, t); - testable.setThrowable(null); - Functions.accept(Testable::test, testable); + consumer.accept(testable, null); } @Test - public void testAsFunction() { + public void testBiFunction() { final IllegalStateException ise = new IllegalStateException(); final Testable testable = new Testable<>(ise); - final FailableFunction failableFunction = th -> { - testable.setThrowable(th); - return Integer.valueOf(testable.testInteger()); + final FailableBiFunction, Throwable, Integer, Throwable> failableBiFunction = (t, th) -> { + t.setThrowable(th); + return Integer.valueOf(t.testAsInteger()); }; - final Function function = Functions.asFunction(failableFunction); - Throwable e = assertThrows(IllegalStateException.class, () -> function.apply(ise)); + final BiFunction, Throwable, Integer> biFunction = Functions.asBiFunction(failableBiFunction); + Throwable e = assertThrows(IllegalStateException.class, () -> biFunction.apply(testable, ise)); assertSame(ise, e); final Error error = new OutOfMemoryError(); testable.setThrowable(error); - e = assertThrows(OutOfMemoryError.class, () -> function.apply(error)); + e = assertThrows(OutOfMemoryError.class, () -> biFunction.apply(testable, error)); assertSame(error, e); final IOException ioe = new IOException("Unknown I/O error"); testable.setThrowable(ioe); - e = assertThrows(UncheckedIOException.class, () -> function.apply(ioe)); + e = assertThrows(UncheckedIOException.class, () -> biFunction.apply(testable, ioe)); final Throwable t = e.getCause(); assertNotNull(t); assertSame(ioe, t); - assertEquals(0, function.apply(null).intValue()); + assertEquals(0, biFunction.apply(testable, null).intValue()); } @Test - @DisplayName("Test that asPredicate(FailablePredicate) is converted to -> Predicate ") - public void testAsPredicate() { + @DisplayName("Test that asPredicate(FailableBiPredicate) is converted to -> BiPredicate ") + public void testBiPredicate() { FailureOnOddInvocations.invocations = 0; - final Functions.FailablePredicate failablePredicate = t -> FailureOnOddInvocations.failingBool(); - final Predicate predicate = Functions.asPredicate(failablePredicate); - final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, () -> predicate.test(null)); + final Functions.FailableBiPredicate failableBiPredicate = (t1, + t2) -> FailureOnOddInvocations.failingBool(); + final BiPredicate predicate = Functions.asBiPredicate(failableBiPredicate); + final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, + () -> predicate.test(null, null)); final Throwable cause = e.getCause(); assertNotNull(cause); assertTrue(cause instanceof SomeException); assertEquals("Odd Invocation: 1", cause.getMessage()); - final boolean instance = predicate.test(null); + final boolean instance = predicate.test(null, null); assertNotNull(instance); } - @Test - void testAsRunnable() { - FailureOnOddInvocations.invocations = 0; - final Runnable runnable = Functions.asRunnable(FailureOnOddInvocations::new); - final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, runnable::run); - final Throwable cause = e.getCause(); - assertNotNull(cause); - assertTrue(cause instanceof SomeException); - assertEquals("Odd Invocation: 1", cause.getMessage()); - - // Even invocations, should not throw an exception - runnable.run(); - } - - @Test - public void testAsSupplier() { - FailureOnOddInvocations.invocations = 0; - final FailableSupplier failableSupplier = FailureOnOddInvocations::new; - final Supplier supplier = Functions.asSupplier(failableSupplier); - final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, supplier::get); - final Throwable cause = e.getCause(); - assertNotNull(cause); - assertTrue(cause instanceof SomeException); - assertEquals("Odd Invocation: 1", cause.getMessage()); - assertNotNull(supplier.get()); - } - @Test void testCallable() { FailureOnOddInvocations.invocations = 0; - final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, () -> Functions.run(FailureOnOddInvocations::new)); + final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, + () -> Functions.run(FailureOnOddInvocations::new)); final Throwable cause = e.getCause(); assertNotNull(cause); assertTrue(cause instanceof SomeException); @@ -698,73 +693,102 @@ public void testConstructor() { new Functions(); } + @Test + public void testFunction() { + final IllegalStateException ise = new IllegalStateException(); + final Testable testable = new Testable<>(ise); + final FailableFunction failableFunction = th -> { + testable.setThrowable(th); + return Integer.valueOf(testable.testAsInteger()); + }; + final Function function = Functions.asFunction(failableFunction); + Throwable e = assertThrows(IllegalStateException.class, () -> function.apply(ise)); + assertSame(ise, e); + + final Error error = new OutOfMemoryError(); + testable.setThrowable(error); + e = assertThrows(OutOfMemoryError.class, () -> function.apply(error)); + assertSame(error, e); + + final IOException ioe = new IOException("Unknown I/O error"); + testable.setThrowable(ioe); + e = assertThrows(UncheckedIOException.class, () -> function.apply(ioe)); + final Throwable t = e.getCause(); + assertNotNull(t); + assertSame(ioe, t); + + assertEquals(0, function.apply(null).intValue()); + } + @Test public void testGetAsBooleanSupplier() { final IllegalStateException ise = new IllegalStateException(); final Testable testable = new Testable<>(ise); - Throwable e = assertThrows(IllegalStateException.class, () -> Functions.getAsBoolean(testable::testBooleanPrimitive)); + Throwable e = assertThrows(IllegalStateException.class, + () -> Functions.getAsBoolean(testable::testAsBooleanPrimitive)); assertSame(ise, e); final Error error = new OutOfMemoryError(); testable.setThrowable(error); - e = assertThrows(OutOfMemoryError.class, () -> Functions.getAsBoolean(testable::testBooleanPrimitive)); + e = assertThrows(OutOfMemoryError.class, () -> Functions.getAsBoolean(testable::testAsBooleanPrimitive)); assertSame(error, e); final IOException ioe = new IOException("Unknown I/O error"); testable.setThrowable(ioe); - e = assertThrows(UncheckedIOException.class, () -> Functions.getAsBoolean(testable::testBooleanPrimitive)); + e = assertThrows(UncheckedIOException.class, () -> Functions.getAsBoolean(testable::testAsBooleanPrimitive)); final Throwable t = e.getCause(); assertNotNull(t); assertSame(ioe, t); testable.setThrowable(null); - assertFalse(Functions.getAsBoolean(testable::testBooleanPrimitive)); + assertFalse(Functions.getAsBoolean(testable::testAsBooleanPrimitive)); } @Test public void testGetAsDoubleSupplier() { final IllegalStateException ise = new IllegalStateException(); final Testable testable = new Testable<>(ise); - Throwable e = assertThrows(IllegalStateException.class, () -> Functions.getAsDouble(testable::testDoublePrimitive)); + Throwable e = assertThrows(IllegalStateException.class, + () -> Functions.getAsDouble(testable::testAsDoublePrimitive)); assertSame(ise, e); final Error error = new OutOfMemoryError(); testable.setThrowable(error); - e = assertThrows(OutOfMemoryError.class, () -> Functions.getAsDouble(testable::testDoublePrimitive)); + e = assertThrows(OutOfMemoryError.class, () -> Functions.getAsDouble(testable::testAsDoublePrimitive)); assertSame(error, e); final IOException ioe = new IOException("Unknown I/O error"); testable.setThrowable(ioe); - e = assertThrows(UncheckedIOException.class, () -> Functions.getAsDouble(testable::testDoublePrimitive)); + e = assertThrows(UncheckedIOException.class, () -> Functions.getAsDouble(testable::testAsDoublePrimitive)); final Throwable t = e.getCause(); assertNotNull(t); assertSame(ioe, t); testable.setThrowable(null); - assertEquals(0, Functions.getAsDouble(testable::testDoublePrimitive)); + assertEquals(0, Functions.getAsDouble(testable::testAsDoublePrimitive)); } @Test public void testGetAsIntSupplier() { final IllegalStateException ise = new IllegalStateException(); final Testable testable = new Testable<>(ise); - Throwable e = assertThrows(IllegalStateException.class, () -> Functions.getAsInt(testable::testIntPrimitive)); + Throwable e = assertThrows(IllegalStateException.class, () -> Functions.getAsInt(testable::testAsIntPrimitive)); assertSame(ise, e); final Error error = new OutOfMemoryError(); testable.setThrowable(error); - e = assertThrows(OutOfMemoryError.class, () -> Functions.getAsInt(testable::testIntPrimitive)); + e = assertThrows(OutOfMemoryError.class, () -> Functions.getAsInt(testable::testAsIntPrimitive)); assertSame(error, e); final IOException ioe = new IOException("Unknown I/O error"); testable.setThrowable(ioe); - e = assertThrows(UncheckedIOException.class, () -> Functions.getAsInt(testable::testIntPrimitive)); + e = assertThrows(UncheckedIOException.class, () -> Functions.getAsInt(testable::testAsIntPrimitive)); final Throwable t = e.getCause(); assertNotNull(t); assertSame(ioe, t); testable.setThrowable(null); - final int i = Functions.getAsInt(testable::testInteger); + final int i = Functions.getAsInt(testable::testAsInteger); assertEquals(0, i); } @@ -772,30 +796,32 @@ public void testGetAsIntSupplier() { public void testGetAsLongSupplier() { final IllegalStateException ise = new IllegalStateException(); final Testable testable = new Testable<>(ise); - Throwable e = assertThrows(IllegalStateException.class, () -> Functions.getAsLong(testable::testLongPrimitive)); + Throwable e = assertThrows(IllegalStateException.class, + () -> Functions.getAsLong(testable::testAsLongPrimitive)); assertSame(ise, e); final Error error = new OutOfMemoryError(); testable.setThrowable(error); - e = assertThrows(OutOfMemoryError.class, () -> Functions.getAsLong(testable::testLongPrimitive)); + e = assertThrows(OutOfMemoryError.class, () -> Functions.getAsLong(testable::testAsLongPrimitive)); assertSame(error, e); final IOException ioe = new IOException("Unknown I/O error"); testable.setThrowable(ioe); - e = assertThrows(UncheckedIOException.class, () -> Functions.getAsLong(testable::testLongPrimitive)); + e = assertThrows(UncheckedIOException.class, () -> Functions.getAsLong(testable::testAsLongPrimitive)); final Throwable t = e.getCause(); assertNotNull(t); assertSame(ioe, t); testable.setThrowable(null); - final long i = Functions.getAsLong(testable::testLongPrimitive); + final long i = Functions.getAsLong(testable::testAsLongPrimitive); assertEquals(0, i); } @Test public void testGetFromSupplier() { FailureOnOddInvocations.invocations = 0; - final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, () -> Functions.run(FailureOnOddInvocations::new)); + final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, + () -> Functions.run(FailureOnOddInvocations::new)); final Throwable cause = e.getCause(); assertNotNull(cause); assertTrue(cause instanceof SomeException); @@ -808,31 +834,49 @@ public void testGetFromSupplier() { public void testGetSupplier() { final IllegalStateException ise = new IllegalStateException(); final Testable testable = new Testable<>(ise); - Throwable e = assertThrows(IllegalStateException.class, () -> Functions.get(testable::testInteger)); + Throwable e = assertThrows(IllegalStateException.class, () -> Functions.get(testable::testAsInteger)); assertSame(ise, e); final Error error = new OutOfMemoryError(); testable.setThrowable(error); - e = assertThrows(OutOfMemoryError.class, () -> Functions.get(testable::testInteger)); + e = assertThrows(OutOfMemoryError.class, () -> Functions.get(testable::testAsInteger)); assertSame(error, e); final IOException ioe = new IOException("Unknown I/O error"); testable.setThrowable(ioe); - e = assertThrows(UncheckedIOException.class, () -> Functions.get(testable::testInteger)); + e = assertThrows(UncheckedIOException.class, () -> Functions.get(testable::testAsInteger)); final Throwable t = e.getCause(); assertNotNull(t); assertSame(ioe, t); testable.setThrowable(null); - final Integer i = Functions.apply(Testable::testInteger, testable); + final Integer i = Functions.apply(Testable::testAsInteger, testable); assertNotNull(i); assertEquals(0, i.intValue()); } + @Test + @DisplayName("Test that asPredicate(FailablePredicate) is converted to -> Predicate ") + public void testPredicate() { + FailureOnOddInvocations.invocations = 0; + final Functions.FailablePredicate failablePredicate = t -> FailureOnOddInvocations + .failingBool(); + final Predicate predicate = Functions.asPredicate(failablePredicate); + final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, + () -> predicate.test(null)); + final Throwable cause = e.getCause(); + assertNotNull(cause); + assertTrue(cause instanceof SomeException); + assertEquals("Odd Invocation: 1", cause.getMessage()); + final boolean instance = predicate.test(null); + assertNotNull(instance); + } + @Test void testRunnable() { FailureOnOddInvocations.invocations = 0; - final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, () -> Functions.run(FailureOnOddInvocations::new)); + final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, + () -> Functions.run(FailureOnOddInvocations::new)); final Throwable cause = e.getCause(); assertNotNull(cause); assertTrue(cause instanceof SomeException); @@ -842,24 +886,1148 @@ void testRunnable() { Functions.run(FailureOnOddInvocations::new); } + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + void testThrows_FailableBiConsumer_Object_Throwable() { + new Functions.FailableBiConsumer() { + + @Override + public void accept(Object object1, Object object2) throws Throwable { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + void testThrows_FailableBiConsumer_String_IOException() { + new Functions.FailableBiConsumer() { + + @Override + public void accept(String object1, String object2) throws IOException { + throw new IOException("test"); + + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + void testThrows_FailableBiFunction_Object_Throwable() { + new Functions.FailableBiFunction() { + + @Override + public Object apply(Object input1, Object input2) throws Throwable { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + void testThrows_FailableBiFunction_String_IOException() { + new Functions.FailableBiFunction() { + + @Override + public String apply(String input1, String input2) throws IOException { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + void testThrows_FailableBiPredicate_Object_Throwable() { + new Functions.FailableBiPredicate() { + + @Override + public boolean test(Object object1, Object object2) throws Throwable { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + void testThrows_FailableBiPredicate_String_IOException() { + new Functions.FailableBiPredicate() { + + @Override + public boolean test(String object1, String object2) throws IOException { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + void testThrows_FailableBooleanSupplier_Object_Throwable() { + new Functions.FailableBooleanSupplier() { + + @Override + public boolean getAsBoolean() throws Throwable { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + void testThrows_FailableBooleanSupplier_String_IOException() { + new Functions.FailableBooleanSupplier() { + + @Override + public boolean getAsBoolean() throws IOException { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + void testThrows_FailableCallable_Object_Throwable() { + new Functions.FailableCallable() { + + @Override + public Object call() throws Throwable { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + void testThrows_FailableCallable_String_IOException() { + new Functions.FailableCallable() { + + @Override + public String call() throws IOException { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + void testThrows_FailableConsumer_Object_Throwable() { + new Functions.FailableConsumer() { + + @Override + public void accept(Object object) throws Throwable { + throw new IOException("test"); + + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + void testThrows_FailableConsumer_String_IOException() { + new Functions.FailableConsumer() { + + @Override + public void accept(String object) throws IOException { + throw new IOException("test"); + + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + void testThrows_FailableDoubleBinaryOperator_Object_Throwable() { + new Functions.FailableDoubleBinaryOperator() { + + @Override + public double applyAsDouble(double left, double right) throws Throwable { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + void testThrows_FailableDoubleBinaryOperator_String_IOException() { + new Functions.FailableDoubleBinaryOperator() { + + @Override + public double applyAsDouble(double left, double right) throws IOException { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + void testThrows_FailableDoubleConsumer_Object_Throwable() { + new Functions.FailableDoubleConsumer() { + + @Override + public void accept(double value) throws Throwable { + throw new IOException("test"); + + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + void testThrows_FailableDoubleConsumer_String_IOException() { + new Functions.FailableDoubleConsumer() { + + @Override + public void accept(double value) throws IOException { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + void testThrows_FailableDoubleFunction_Object_Throwable() { + new Functions.FailableDoubleFunction() { + + @Override + public Object apply(double input) throws Throwable { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + void testThrows_FailableDoubleFunction_String_IOException() { + new Functions.FailableDoubleFunction() { + + @Override + public String apply(double input) throws IOException { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + void testThrows_FailableDoubleSupplier_Object_Throwable() { + new Functions.FailableDoubleSupplier() { + + @Override + public double getAsDouble() throws Throwable { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + void testThrows_FailableDoubleSupplier_String_IOException() { + new Functions.FailableDoubleSupplier() { + + @Override + public double getAsDouble() throws IOException { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + void testThrows_FailableDoubleToIntFunction_Object_Throwable() { + new Functions.FailableDoubleToIntFunction() { + + @Override + public int applyAsInt(double value) throws Throwable { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + void testThrows_FailableDoubleToIntFunction_String_IOException() { + new Functions.FailableDoubleToIntFunction() { + + @Override + public int applyAsInt(double value) throws IOException { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + void testThrows_FailableDoubleToLongFunction_Object_Throwable() { + new Functions.FailableDoubleToLongFunction() { + + @Override + public int applyAsLong(double value) throws Throwable { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + void testThrows_FailableDoubleToLongFunction_String_IOException() { + new Functions.FailableDoubleToLongFunction() { + + @Override + public int applyAsLong(double value) throws IOException { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + void testThrows_FailableFunction_Object_Throwable() { + new Functions.FailableFunction() { + + @Override + public Object apply(Object input) throws Throwable { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + void testThrows_FailableFunction_String_IOException() { + new Functions.FailableFunction() { + + @Override + public String apply(String input) throws IOException { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + void testThrows_FailableIntBinaryOperator_Object_Throwable() { + new Functions.FailableIntBinaryOperator() { + + @Override + public int applyAsInt(int left, int right) throws Throwable { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + void testThrows_FailableIntBinaryOperator_String_IOException() { + new Functions.FailableIntBinaryOperator() { + + @Override + public int applyAsInt(int left, int right) throws IOException { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + void testThrows_FailableIntConsumer_Object_Throwable() { + new Functions.FailableIntConsumer() { + + @Override + public void accept(int value) throws Throwable { + throw new IOException("test"); + + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + void testThrows_FailableIntConsumer_String_IOException() { + new Functions.FailableIntConsumer() { + + @Override + public void accept(int value) throws IOException { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + void testThrows_FailableIntFunction_Object_Throwable() { + new Functions.FailableIntFunction() { + + @Override + public Object apply(int input) throws Throwable { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + void testThrows_FailableIntFunction_String_IOException() { + new Functions.FailableIntFunction() { + + @Override + public String apply(int input) throws IOException { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + void testThrows_FailableIntSupplier_Object_Throwable() { + new Functions.FailableIntSupplier() { + + @Override + public int getAsInt() throws Throwable { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + void testThrows_FailableIntSupplier_String_IOException() { + new Functions.FailableIntSupplier() { + + @Override + public int getAsInt() throws IOException { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + void testThrows_FailableIntToDoubleFunction_Object_Throwable() { + new Functions.FailableIntToDoubleFunction() { + + @Override + public double applyAsDouble(int value) throws Throwable { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + void testThrows_FailableIntToDoubleFunction_String_IOException() { + new Functions.FailableIntToDoubleFunction() { + + @Override + public double applyAsDouble(int value) throws IOException { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + void testThrows_FailableIntToLongFunction_Object_Throwable() { + new Functions.FailableIntToLongFunction() { + + @Override + public long applyAsLong(int value) throws Throwable { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + void testThrows_FailableIntToLongFunction_String_IOException() { + new Functions.FailableIntToLongFunction() { + + @Override + public long applyAsLong(int value) throws IOException { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + void testThrows_FailableLongBinaryOperator_Object_Throwable() { + new Functions.FailableLongBinaryOperator() { + + @Override + public long applyAsLong(long left, long right) throws Throwable { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + void testThrows_FailableLongBinaryOperator_String_IOException() { + new Functions.FailableLongBinaryOperator() { + + @Override + public long applyAsLong(long left, long right) throws IOException { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + void testThrows_FailableLongConsumer_Object_Throwable() { + new Functions.FailableLongConsumer() { + + @Override + public void accept(long object) throws Throwable { + throw new IOException("test"); + + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + void testThrows_FailableLongConsumer_String_IOException() { + new Functions.FailableLongConsumer() { + + @Override + public void accept(long object) throws IOException { + throw new IOException("test"); + + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + void testThrows_FailableLongFunction_Object_Throwable() { + new Functions.FailableLongFunction() { + + @Override + public Object apply(long input) throws Throwable { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + void testThrows_FailableLongFunction_String_IOException() { + new Functions.FailableLongFunction() { + + @Override + public String apply(long input) throws IOException { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + void testThrows_FailableLongSupplier_Object_Throwable() { + new Functions.FailableLongSupplier() { + + @Override + public long getAsLong() throws Throwable { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + void testThrows_FailableLongSupplier_String_IOException() { + new Functions.FailableLongSupplier() { + + @Override + public long getAsLong() throws IOException { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + void testThrows_FailableLongToDoubleFunction_Object_Throwable() { + new Functions.FailableLongToDoubleFunction() { + + @Override + public double applyAsDouble(long value) throws Throwable { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + void testThrows_FailableLongToDoubleFunction_String_IOException() { + new Functions.FailableLongToDoubleFunction() { + + @Override + public double applyAsDouble(long value) throws IOException { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + void testThrows_FailableLongToIntFunction_Object_Throwable() { + new Functions.FailableLongToIntFunction() { + + @Override + public int applyAsInt(long value) throws Throwable { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + void testThrows_FailableLongToIntFunction_String_IOException() { + new Functions.FailableLongToIntFunction() { + + @Override + public int applyAsInt(long value) throws IOException { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + void testThrows_FailableObjDoubleConsumer_Object_Throwable() { + new Functions.FailableObjDoubleConsumer() { + + @Override + public void accept(Object object, double value) throws Throwable { + throw new IOException("test"); + + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + void testThrows_FailableObjDoubleConsumer_String_IOException() { + new Functions.FailableObjDoubleConsumer() { + + @Override + public void accept(String object, double value) throws IOException { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + void testThrows_FailableObjIntConsumer_Object_Throwable() { + new Functions.FailableObjIntConsumer() { + + @Override + public void accept(Object object, int value) throws Throwable { + throw new IOException("test"); + + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + void testThrows_FailableObjIntConsumer_String_IOException() { + new Functions.FailableObjIntConsumer() { + + @Override + public void accept(String object, int value) throws IOException { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + void testThrows_FailableObjLongConsumer_Object_Throwable() { + new Functions.FailableObjLongConsumer() { + + @Override + public void accept(Object object, long value) throws Throwable { + throw new IOException("test"); + + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + void testThrows_FailableObjLongConsumer_String_IOException() { + new Functions.FailableObjLongConsumer() { + + @Override + public void accept(String object, long value) throws IOException { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + void testThrows_FailablePredicate_Object_Throwable() { + new Functions.FailablePredicate() { + + @Override + public boolean test(Object object) throws Throwable { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + void testThrows_FailablePredicate_String_IOException() { + new Functions.FailablePredicate() { + + @Override + public boolean test(String object) throws IOException { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + void testThrows_FailableRunnable_Object_Throwable() { + new Functions.FailableRunnable() { + + @Override + public void run() throws Throwable { + throw new IOException("test"); + + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + void testThrows_FailableRunnable_String_IOException() { + new Functions.FailableRunnable() { + + @Override + public void run() throws IOException { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + void testThrows_FailableSupplier_Object_Throwable() { + new Functions.FailableSupplier() { + + @Override + public Object get() throws Throwable { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + void testThrows_FailableSupplier_String_IOException() { + new Functions.FailableSupplier() { + + @Override + public String get() throws IOException { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + void testThrows_FailableToDoubleBiFunction_Object_Throwable() { + new Functions.FailableToDoubleBiFunction() { + + @Override + public double applyAsDouble(Object t, Object u) throws Throwable { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + void testThrows_FailableToDoubleBiFunction_String_IOException() { + new Functions.FailableToDoubleBiFunction() { + + @Override + public double applyAsDouble(String t, String u) throws IOException { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + void testThrows_FailableToDoubleFunction_Object_Throwable() { + new Functions.FailableToDoubleFunction() { + + @Override + public double applyAsDouble(Object t) throws Throwable { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + void testThrows_FailableToDoubleFunction_String_IOException() { + new Functions.FailableToDoubleFunction() { + + @Override + public double applyAsDouble(String t) throws IOException { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + void testThrows_FailableToIntBiFunction_Object_Throwable() { + new Functions.FailableToIntBiFunction() { + + @Override + public int applyAsInt(Object t, Object u) throws Throwable { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + void testThrows_FailableToIntBiFunction_String_IOException() { + new Functions.FailableToIntBiFunction() { + + @Override + public int applyAsInt(String t, String u) throws IOException { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + void testThrows_FailableToIntFunction_Object_Throwable() { + new Functions.FailableToIntFunction() { + + @Override + public int applyAsInt(Object t) throws Throwable { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + void testThrows_FailableToIntFunction_String_IOException() { + new Functions.FailableToIntFunction() { + + @Override + public int applyAsInt(String t) throws IOException { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + void testThrows_FailableToLongBiFunction_Object_Throwable() { + new Functions.FailableToLongBiFunction() { + + @Override + public long applyAsLong(Object t, Object u) throws Throwable { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + void testThrows_FailableToLongBiFunction_String_IOException() { + new Functions.FailableToLongBiFunction() { + + @Override + public long applyAsLong(String t, String u) throws IOException { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + void testThrows_FailableToLongFunction_Object_Throwable() { + new Functions.FailableToLongFunction() { + + @Override + public long applyAsLong(Object t) throws Throwable { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + void testThrows_FailableToLongFunction_String_IOException() { + new Functions.FailableToLongFunction() { + + @Override + public long applyAsLong(String t) throws IOException { + throw new IOException("test"); + } + }; + } + @Test public void testTryWithResources() { final CloseableObject co = new CloseableObject(); final FailableConsumer consumer = co::run; final IllegalStateException ise = new IllegalStateException(); - Throwable e = assertThrows(IllegalStateException.class, () -> Functions.tryWithResources(() -> consumer.accept(ise), co::close)); + Throwable e = assertThrows(IllegalStateException.class, + () -> Functions.tryWithResources(() -> consumer.accept(ise), co::close)); assertSame(ise, e); assertTrue(co.isClosed()); co.reset(); final Error error = new OutOfMemoryError(); - e = assertThrows(OutOfMemoryError.class, () -> Functions.tryWithResources(() -> consumer.accept(error), co::close)); + e = assertThrows(OutOfMemoryError.class, + () -> Functions.tryWithResources(() -> consumer.accept(error), co::close)); assertSame(error, e); assertTrue(co.isClosed()); co.reset(); final IOException ioe = new IOException("Unknown I/O error"); - final UncheckedIOException uioe = assertThrows(UncheckedIOException.class, () -> Functions.tryWithResources(() -> consumer.accept(ioe), co::close)); + final UncheckedIOException uioe = assertThrows(UncheckedIOException.class, + () -> Functions.tryWithResources(() -> consumer.accept(ioe), co::close)); final IOException cause = uioe.getCause(); assertSame(ioe, cause); From cf0778a5ad0ad876d4233816b46978679bebac35 Mon Sep 17 00:00:00 2001 From: XenoAmess Date: Mon, 15 Jun 2020 10:08:10 +0800 Subject: [PATCH 0149/3230] Add binary compatibility check to Maven default goal (#555) * add bc detect as discussed in mailing list. * add bc detect as discussed in mailing list. --- pom.xml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pom.xml b/pom.xml index 428266fbfcc..fae2aa0d799 100644 --- a/pom.xml +++ b/pom.xml @@ -615,8 +615,8 @@ 3.0.0-M4 3.1.1 - - false + + true 0.14.3 @@ -630,7 +630,7 @@ - clean verify apache-rat:check clirr:check checkstyle:check spotbugs:check javadoc:javadoc + clean verify apache-rat:check checkstyle:check japicmp:cmp spotbugs:check javadoc:javadoc From 438716a839ff94ef72f7e261e7fb1114e482cb39 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Mon, 15 Jun 2020 09:17:23 -0400 Subject: [PATCH 0150/3230] Add edge case. --- src/test/java/org/apache/commons/lang3/StringUtilsTest.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/test/java/org/apache/commons/lang3/StringUtilsTest.java b/src/test/java/org/apache/commons/lang3/StringUtilsTest.java index a83a34befb4..3230aa0416a 100644 --- a/src/test/java/org/apache/commons/lang3/StringUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/StringUtilsTest.java @@ -1357,6 +1357,7 @@ public void testJoinWith() { assertEquals("a,b,c", StringUtils.joinWith(",", "a", "b", "c")); assertEquals(",a,", StringUtils.joinWith(",", null, "a", "")); + assertEquals(",a,", StringUtils.joinWith(",", "", "a", "")); assertEquals("ab", StringUtils.joinWith(null, "a", "b")); } From 0c42c0c192ed77786bf0e2f9596acb2640ac5401 Mon Sep 17 00:00:00 2001 From: XenoAmess Date: Mon, 3 Jun 2019 01:05:53 +0800 Subject: [PATCH 0151/3230] [LANG-1546]: delete `` and `` in maven-javadoc-plugin --- pom.xml | 2 -- 1 file changed, 2 deletions(-) diff --git a/pom.xml b/pom.xml index fae2aa0d799..07d8cafc474 100644 --- a/pom.xml +++ b/pom.xml @@ -662,8 +662,6 @@ ${maven.compiler.source} true - utf-8 - utf-8 true https://docs.oracle.com/javase/8/docs/api/ From 79adb9f677e8079a2160bfbd096521468bcf8e3a Mon Sep 17 00:00:00 2001 From: "Bruno P. Kinoshita" Date: Tue, 16 Jun 2020 14:15:06 +1200 Subject: [PATCH 0152/3230] [LANG-1546]: add changelog --- src/changes/changes.xml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 69a8b365d7f..f5e3fa5de66 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -46,7 +46,8 @@ The type attribute can be add,update,fix,remove. - Fix Javadoc for StringUtils.appendIfMissingIgnoreCase() #507. + remove encoding and docEncoding and use inherited values from commons-parent + Fix Javadoc for StringUtils.appendIfMissingIgnoreCase() #507. org.junit-pioneer:junit-pioneer 0.5.4 -> 0.6.0. org.junit.jupiter:junit-jupiter 5.6.0 -> 5.6.1. com.github.spotbugs:spotbugs 4.0.0 -> 4.0.4. From 36111ba5829bdd4249c7418c1aec17c149ef86a3 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Wed, 17 Jun 2020 09:30:21 -0400 Subject: [PATCH 0153/3230] [LANG-1568] More failable functional interfaces to match JRE functional interfaces. --- .../org/apache/commons/lang3/Functions.java | 76 +++++++++++++++++-- .../apache/commons/lang3/FunctionsTest.java | 45 ++++++++++- 2 files changed, 112 insertions(+), 9 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/Functions.java b/src/main/java/org/apache/commons/lang3/Functions.java index 0eeef4473ac..16e7a0c10c3 100644 --- a/src/main/java/org/apache/commons/lang3/Functions.java +++ b/src/main/java/org/apache/commons/lang3/Functions.java @@ -30,6 +30,7 @@ import java.util.function.DoubleBinaryOperator; import java.util.function.DoubleConsumer; import java.util.function.DoubleFunction; +import java.util.function.DoublePredicate; import java.util.function.DoubleSupplier; import java.util.function.DoubleToIntFunction; import java.util.function.DoubleToLongFunction; @@ -37,12 +38,14 @@ import java.util.function.IntBinaryOperator; import java.util.function.IntConsumer; import java.util.function.IntFunction; +import java.util.function.IntPredicate; import java.util.function.IntSupplier; import java.util.function.IntToDoubleFunction; import java.util.function.IntToLongFunction; import java.util.function.LongBinaryOperator; import java.util.function.LongConsumer; import java.util.function.LongFunction; +import java.util.function.LongPredicate; import java.util.function.LongSupplier; import java.util.function.LongToDoubleFunction; import java.util.function.LongToIntFunction; @@ -111,7 +114,7 @@ public interface FailableBiConsumer { * * @param object1 the first parameter for the consumable to accept * @param object2 the second parameter for the consumable to accept - * @throws T if the consumer fails + * @throws T Thrown when the consumer fails. */ void accept(O1 object1, O2 object2) throws T; } @@ -208,7 +211,7 @@ public interface FailableConsumer { * Accepts the consumer. * * @param object the parameter for the consumable to accept - * @throws T if the consumer fails + * @throws T Thrown when the consumer fails. */ void accept(O object) throws T; } @@ -246,7 +249,7 @@ public interface FailableDoubleConsumer { * Accepts the consumer. * * @param value the parameter for the consumable to accept - * @throws T if the consumer fails + * @throws T Thrown when the consumer fails. */ void accept(double value) throws T; } @@ -270,6 +273,25 @@ public interface FailableDoubleFunction { R apply(double input) throws T; } + /** + * A functional interface like {@link DoublePredicate} that declares a {@code Throwable}. + * + * @param Thrown exception. + * @since 3.11 + */ + @FunctionalInterface + public interface FailableDoublePredicate { + + /** + * Tests the predicate. + * + * @param value the parameter for the predicate to accept. + * @return {@code true} if the input argument matches the predicate, {@code false} otherwise. + * @throws T Thrown when the consumer fails. + */ + boolean test(double value) throws T; + } + /** * A functional interface like {@link DoubleSupplier} that declares a {@code Throwable}. * @@ -379,7 +401,7 @@ public interface FailableIntConsumer { * Accepts the consumer. * * @param value the parameter for the consumable to accept - * @throws T if the consumer fails + * @throws T Thrown when the consumer fails. */ void accept(int value) throws T; } @@ -403,6 +425,25 @@ public interface FailableIntFunction { R apply(int input) throws T; } + /** + * A functional interface like {@link IntPredicate} that declares a {@code Throwable}. + * + * @param Thrown exception. + * @since 3.11 + */ + @FunctionalInterface + public interface FailableIntPredicate { + + /** + * Tests the predicate. + * + * @param value the parameter for the predicate to accept. + * @return {@code true} if the input argument matches the predicate, {@code false} otherwise. + * @throws T Thrown when the consumer fails. + */ + boolean test(int value) throws T; + } + /** * A functional interface like {@link IntSupplier} that declares a {@code Throwable}. * @@ -492,7 +533,7 @@ public interface FailableLongConsumer { * Accepts the consumer. * * @param object the parameter for the consumable to accept - * @throws T if the consumer fails + * @throws T Thrown when the consumer fails. */ void accept(long object) throws T; } @@ -516,6 +557,25 @@ public interface FailableLongFunction { R apply(long input) throws T; } + /** + * A functional interface like {@link LongPredicate} that declares a {@code Throwable}. + * + * @param Thrown exception. + * @since 3.11 + */ + @FunctionalInterface + public interface FailableLongPredicate { + + /** + * Tests the predicate. + * + * @param value the parameter for the predicate to accept. + * @return {@code true} if the input argument matches the predicate, {@code false} otherwise. + * @throws T Thrown when the consumer fails. + */ + boolean test(long value) throws T; + } + /** * A functional interface like {@link LongSupplier} that declares a {@code Throwable}. * @@ -587,7 +647,7 @@ public interface FailableObjDoubleConsumer { * * @param object the object parameter for the consumable to accept. * @param value the double parameter for the consumable to accept. - * @throws T if the consumer fails + * @throws T Thrown when the consumer fails. */ void accept(O object, double value) throws T; } @@ -607,7 +667,7 @@ public interface FailableObjIntConsumer { * * @param object the object parameter for the consumable to accept. * @param value the int parameter for the consumable to accept. - * @throws T if the consumer fails + * @throws T Thrown when the consumer fails. */ void accept(O object, int value) throws T; } @@ -627,7 +687,7 @@ public interface FailableObjLongConsumer { * * @param object the object parameter for the consumable to accept. * @param value the long parameter for the consumable to accept. - * @throws T if the consumer fails + * @throws T Thrown when the consumer fails. */ void accept(O object, long value) throws T; } diff --git a/src/test/java/org/apache/commons/lang3/FunctionsTest.java b/src/test/java/org/apache/commons/lang3/FunctionsTest.java index d114224f6d8..36ed6ca3513 100644 --- a/src/test/java/org/apache/commons/lang3/FunctionsTest.java +++ b/src/test/java/org/apache/commons/lang3/FunctionsTest.java @@ -77,6 +77,21 @@ static boolean failingBool() throws SomeException { return true; } + static boolean testDouble(double value) throws SomeException { + throwOnOdd(); + return true; + } + + static boolean testInt(int value) throws SomeException { + throwOnOdd(); + return true; + } + + static boolean testLong(long value) throws SomeException { + throwOnOdd(); + return true; + } + private static void throwOnOdd() throws SomeException { final int i = ++invocations; if (i % 2 == 1) { @@ -689,10 +704,20 @@ void testCallable() { @Test public void testConstructor() { - // We allow this, which must be an omission to make the ctor private. + // We allow this, which must have been an omission to make the ctor private. + // We could make the ctor private in 4.0. new Functions(); } + @Test + public void testDoublePredicate() throws Throwable { + FailureOnOddInvocations.invocations = 0; + final Functions.FailableDoublePredicate failablePredicate = t1 -> FailureOnOddInvocations + .testDouble(t1); + assertThrows(SomeException.class, () -> failablePredicate.test(1d)); + failablePredicate.test(1d); + } + @Test public void testFunction() { final IllegalStateException ise = new IllegalStateException(); @@ -855,6 +880,24 @@ public void testGetSupplier() { assertEquals(0, i.intValue()); } + @Test + public void testIntPredicate() throws Throwable { + FailureOnOddInvocations.invocations = 0; + final Functions.FailableIntPredicate failablePredicate = t1 -> FailureOnOddInvocations + .testInt(t1); + assertThrows(SomeException.class, () -> failablePredicate.test(1)); + failablePredicate.test(1); + } + + @Test + public void testLongPredicate() throws Throwable { + FailureOnOddInvocations.invocations = 0; + final Functions.FailableLongPredicate failablePredicate = t1 -> FailureOnOddInvocations + .testLong(t1); + assertThrows(SomeException.class, () -> failablePredicate.test(1l)); + failablePredicate.test(1l); + } + @Test @DisplayName("Test that asPredicate(FailablePredicate) is converted to -> Predicate ") public void testPredicate() { From 9214c65371dded64f0a8068e7b877f97d50a024f Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Wed, 17 Jun 2020 11:05:04 -0400 Subject: [PATCH 0154/3230] Merge conditions using the same blocks. --- .../java/org/apache/commons/lang3/StringUtils.java | 4 +--- .../commons/lang3/event/EventListenerSupport.java | 4 +--- .../apache/commons/lang3/reflect/MethodUtils.java | 14 ++++---------- .../org/apache/commons/lang3/text/WordUtils.java | 5 +---- 4 files changed, 7 insertions(+), 20 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/StringUtils.java b/src/main/java/org/apache/commons/lang3/StringUtils.java index 507cba02e93..ec9f6160cfc 100644 --- a/src/main/java/org/apache/commons/lang3/StringUtils.java +++ b/src/main/java/org/apache/commons/lang3/StringUtils.java @@ -8879,9 +8879,7 @@ public static String swapCase(final String str) { for (int i = 0; i < strLen; ) { final int oldCodepoint = str.codePointAt(i); final int newCodePoint; - if (Character.isUpperCase(oldCodepoint)) { - newCodePoint = Character.toLowerCase(oldCodepoint); - } else if (Character.isTitleCase(oldCodepoint)) { + if (Character.isUpperCase(oldCodepoint) || Character.isTitleCase(oldCodepoint)) { newCodePoint = Character.toLowerCase(oldCodepoint); } else if (Character.isLowerCase(oldCodepoint)) { newCodePoint = Character.toUpperCase(oldCodepoint); diff --git a/src/main/java/org/apache/commons/lang3/event/EventListenerSupport.java b/src/main/java/org/apache/commons/lang3/event/EventListenerSupport.java index 499032d1dbd..bd7951921cf 100644 --- a/src/main/java/org/apache/commons/lang3/event/EventListenerSupport.java +++ b/src/main/java/org/apache/commons/lang3/event/EventListenerSupport.java @@ -195,9 +195,7 @@ public void addListener(final L listener) { */ public void addListener(final L listener, final boolean allowDuplicate) { Validate.notNull(listener, "Listener object cannot be null."); - if (allowDuplicate) { - listeners.add(listener); - } else if (!listeners.contains(listener)) { + if (allowDuplicate || !listeners.contains(listener)) { listeners.add(listener); } } diff --git a/src/main/java/org/apache/commons/lang3/reflect/MethodUtils.java b/src/main/java/org/apache/commons/lang3/reflect/MethodUtils.java index 63260e8dfde..125bba373b8 100644 --- a/src/main/java/org/apache/commons/lang3/reflect/MethodUtils.java +++ b/src/main/java/org/apache/commons/lang3/reflect/MethodUtils.java @@ -757,10 +757,8 @@ public static Method getMatchingMethod(final Class cls, final String methodNa return method; } else if (methodName.equals(method.getName()) && ClassUtils.isAssignable(parameterTypes, method.getParameterTypes(), true)) { - if (inexactMatch == null) { - inexactMatch = method; - } else if (distance(parameterTypes, method.getParameterTypes()) - < distance(parameterTypes, inexactMatch.getParameterTypes())) { + if ((inexactMatch == null) || (distance(parameterTypes, method.getParameterTypes()) + < distance(parameterTypes, inexactMatch.getParameterTypes()))) { inexactMatch = method; } } @@ -1007,14 +1005,10 @@ private static List> getAllSuperclassesAndInterfaces(final Class cls Class acls; if (interfaceIndex >= allInterfaces.size()) { acls = allSuperclasses.get(superClassIndex++); - } else if (superClassIndex >= allSuperclasses.size()) { - acls = allInterfaces.get(interfaceIndex++); - } else if (interfaceIndex < superClassIndex) { + } else if ((superClassIndex >= allSuperclasses.size()) || (interfaceIndex < superClassIndex) || !(superClassIndex < interfaceIndex)) { acls = allInterfaces.get(interfaceIndex++); - } else if (superClassIndex < interfaceIndex) { - acls = allSuperclasses.get(superClassIndex++); } else { - acls = allInterfaces.get(interfaceIndex++); + acls = allSuperclasses.get(superClassIndex++); } allSuperClassesAndInterfaces.add(acls); } diff --git a/src/main/java/org/apache/commons/lang3/text/WordUtils.java b/src/main/java/org/apache/commons/lang3/text/WordUtils.java index ee1249e1e7d..5eb9eadb194 100644 --- a/src/main/java/org/apache/commons/lang3/text/WordUtils.java +++ b/src/main/java/org/apache/commons/lang3/text/WordUtils.java @@ -582,10 +582,7 @@ public static String swapCase(final String str) { for (int i = 0; i < buffer.length; i++) { final char ch = buffer[i]; - if (Character.isUpperCase(ch)) { - buffer[i] = Character.toLowerCase(ch); - whitespace = false; - } else if (Character.isTitleCase(ch)) { + if (Character.isUpperCase(ch) || Character.isTitleCase(ch)) { buffer[i] = Character.toLowerCase(ch); whitespace = false; } else if (Character.isLowerCase(ch)) { From 8b54728564e3e0c75ef915fb17f172326e8be197 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Wed, 17 Jun 2020 15:58:26 -0400 Subject: [PATCH 0155/3230] Create the new package org.apache.commons.function to parallel the JRE's java.util.function to provide home for our "failable" version of the JRE's functional interfaces. --- .../org/apache/commons/lang3/Functions.java | 657 +----- .../function/FailableBooleanSupplier.java | 38 + .../FailableDoubleBinaryOperator.java | 40 + .../function/FailableDoubleConsumer.java | 38 + .../function/FailableDoubleFunction.java | 40 + .../function/FailableDoublePredicate.java | 39 + .../function/FailableDoubleSupplier.java | 38 + .../function/FailableDoubleToIntFunction.java | 39 + .../FailableDoubleToLongFunction.java | 39 + .../function/FailableIntBinaryOperator.java | 40 + .../lang3/function/FailableIntConsumer.java | 38 + .../lang3/function/FailableIntFunction.java | 40 + .../lang3/function/FailableIntPredicate.java | 39 + .../lang3/function/FailableIntSupplier.java | 38 + .../function/FailableIntToDoubleFunction.java | 39 + .../function/FailableIntToLongFunction.java | 39 + .../function/FailableLongBinaryOperator.java | 40 + .../lang3/function/FailableLongConsumer.java | 38 + .../lang3/function/FailableLongFunction.java | 40 + .../lang3/function/FailableLongPredicate.java | 39 + .../lang3/function/FailableLongSupplier.java | 38 + .../FailableLongToDoubleFunction.java | 39 + .../function/FailableLongToIntFunction.java | 39 + .../function/FailableObjDoubleConsumer.java | 40 + .../function/FailableObjIntConsumer.java | 40 + .../function/FailableObjLongConsumer.java | 40 + .../function/FailableToDoubleBiFunction.java | 42 + .../function/FailableToDoubleFunction.java | 40 + .../function/FailableToIntBiFunction.java | 42 + .../lang3/function/FailableToIntFunction.java | 40 + .../function/FailableToLongBiFunction.java | 42 + .../function/FailableToLongFunction.java | 40 + .../apache/commons/lang3/FunctionsTest.java | 908 +-------- .../lang3/function/FailableFunctionsTest.java | 1804 +++++++++++++++++ 34 files changed, 3070 insertions(+), 1522 deletions(-) create mode 100644 src/main/java/org/apache/commons/lang3/function/FailableBooleanSupplier.java create mode 100644 src/main/java/org/apache/commons/lang3/function/FailableDoubleBinaryOperator.java create mode 100644 src/main/java/org/apache/commons/lang3/function/FailableDoubleConsumer.java create mode 100644 src/main/java/org/apache/commons/lang3/function/FailableDoubleFunction.java create mode 100644 src/main/java/org/apache/commons/lang3/function/FailableDoublePredicate.java create mode 100644 src/main/java/org/apache/commons/lang3/function/FailableDoubleSupplier.java create mode 100644 src/main/java/org/apache/commons/lang3/function/FailableDoubleToIntFunction.java create mode 100644 src/main/java/org/apache/commons/lang3/function/FailableDoubleToLongFunction.java create mode 100644 src/main/java/org/apache/commons/lang3/function/FailableIntBinaryOperator.java create mode 100644 src/main/java/org/apache/commons/lang3/function/FailableIntConsumer.java create mode 100644 src/main/java/org/apache/commons/lang3/function/FailableIntFunction.java create mode 100644 src/main/java/org/apache/commons/lang3/function/FailableIntPredicate.java create mode 100644 src/main/java/org/apache/commons/lang3/function/FailableIntSupplier.java create mode 100644 src/main/java/org/apache/commons/lang3/function/FailableIntToDoubleFunction.java create mode 100644 src/main/java/org/apache/commons/lang3/function/FailableIntToLongFunction.java create mode 100644 src/main/java/org/apache/commons/lang3/function/FailableLongBinaryOperator.java create mode 100644 src/main/java/org/apache/commons/lang3/function/FailableLongConsumer.java create mode 100644 src/main/java/org/apache/commons/lang3/function/FailableLongFunction.java create mode 100644 src/main/java/org/apache/commons/lang3/function/FailableLongPredicate.java create mode 100644 src/main/java/org/apache/commons/lang3/function/FailableLongSupplier.java create mode 100644 src/main/java/org/apache/commons/lang3/function/FailableLongToDoubleFunction.java create mode 100644 src/main/java/org/apache/commons/lang3/function/FailableLongToIntFunction.java create mode 100644 src/main/java/org/apache/commons/lang3/function/FailableObjDoubleConsumer.java create mode 100644 src/main/java/org/apache/commons/lang3/function/FailableObjIntConsumer.java create mode 100644 src/main/java/org/apache/commons/lang3/function/FailableObjLongConsumer.java create mode 100644 src/main/java/org/apache/commons/lang3/function/FailableToDoubleBiFunction.java create mode 100644 src/main/java/org/apache/commons/lang3/function/FailableToDoubleFunction.java create mode 100644 src/main/java/org/apache/commons/lang3/function/FailableToIntBiFunction.java create mode 100644 src/main/java/org/apache/commons/lang3/function/FailableToIntFunction.java create mode 100644 src/main/java/org/apache/commons/lang3/function/FailableToLongBiFunction.java create mode 100644 src/main/java/org/apache/commons/lang3/function/FailableToLongFunction.java create mode 100644 src/test/java/org/apache/commons/lang3/function/FailableFunctionsTest.java diff --git a/src/main/java/org/apache/commons/lang3/Functions.java b/src/main/java/org/apache/commons/lang3/Functions.java index 16e7a0c10c3..4aa72094ce2 100644 --- a/src/main/java/org/apache/commons/lang3/Functions.java +++ b/src/main/java/org/apache/commons/lang3/Functions.java @@ -25,44 +25,21 @@ import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.BiPredicate; -import java.util.function.BooleanSupplier; import java.util.function.Consumer; -import java.util.function.DoubleBinaryOperator; -import java.util.function.DoubleConsumer; -import java.util.function.DoubleFunction; -import java.util.function.DoublePredicate; -import java.util.function.DoubleSupplier; -import java.util.function.DoubleToIntFunction; -import java.util.function.DoubleToLongFunction; import java.util.function.Function; -import java.util.function.IntBinaryOperator; -import java.util.function.IntConsumer; -import java.util.function.IntFunction; -import java.util.function.IntPredicate; -import java.util.function.IntSupplier; -import java.util.function.IntToDoubleFunction; -import java.util.function.IntToLongFunction; -import java.util.function.LongBinaryOperator; -import java.util.function.LongConsumer; -import java.util.function.LongFunction; -import java.util.function.LongPredicate; -import java.util.function.LongSupplier; -import java.util.function.LongToDoubleFunction; -import java.util.function.LongToIntFunction; -import java.util.function.ObjDoubleConsumer; -import java.util.function.ObjIntConsumer; -import java.util.function.ObjLongConsumer; import java.util.function.Predicate; import java.util.function.Supplier; -import java.util.function.ToDoubleBiFunction; -import java.util.function.ToDoubleFunction; -import java.util.function.ToIntBiFunction; -import java.util.function.ToIntFunction; -import java.util.function.ToLongBiFunction; -import java.util.function.ToLongFunction; import java.util.stream.Stream; import org.apache.commons.lang3.Streams.FailableStream; +import org.apache.commons.lang3.function.FailableBooleanSupplier; +import org.apache.commons.lang3.function.FailableDoubleBinaryOperator; +import org.apache.commons.lang3.function.FailableDoubleConsumer; +import org.apache.commons.lang3.function.FailableDoubleSupplier; +import org.apache.commons.lang3.function.FailableIntConsumer; +import org.apache.commons.lang3.function.FailableIntSupplier; +import org.apache.commons.lang3.function.FailableLongConsumer; +import org.apache.commons.lang3.function.FailableLongSupplier; /** * This class provides utility functions, and classes for working with the {@code java.util.function} package, or more @@ -101,6 +78,8 @@ public class Functions { /** * A functional interface like {@link BiConsumer} that declares a {@code Throwable}. + * + *

      TODO for 4.0: Move to org.apache.commons.lang3.function.

      * * @param Consumed type 1. * @param Consumed type 2. @@ -122,6 +101,8 @@ public interface FailableBiConsumer { /** * A functional interface like {@link BiFunction} that declares a {@code Throwable}. * + *

      TODO for 4.0: Move to org.apache.commons.lang3.function.

      + * * @param Input type 1. * @param Input type 2. * @param Return type. @@ -144,6 +125,8 @@ public interface FailableBiFunction { /** * A functional interface like {@link BiPredicate} that declares a {@code Throwable}. * + *

      TODO for 4.0: Move to org.apache.commons.lang3.function.

      + * * @param Predicate type 1. * @param Predicate type 2. * @param Thrown exception. @@ -162,27 +145,11 @@ public interface FailableBiPredicate { boolean test(O1 object1, O2 object2) throws T; } - /** - * A functional interface like {@link BooleanSupplier} that declares a {@code Throwable}. - * - * @param Thrown exception. - * @since 3.11 - */ - @FunctionalInterface - public interface FailableBooleanSupplier { - - /** - * Supplies a boolean. - * - * @return a result - * @throws T if the supplier fails - */ - boolean getAsBoolean() throws T; - } - /** * A functional interface like {@link java.util.concurrent.Callable} that declares a {@code Throwable}. * + *

      TODO for 4.0: Move to org.apache.commons.lang3.function.

      + * * @param Return type. * @param Thrown exception. */ @@ -201,6 +168,8 @@ public interface FailableCallable { /** * A functional interface like {@link Consumer} that declares a {@code Throwable}. * + *

      TODO for 4.0: Move to org.apache.commons.lang3.function.

      + * * @param Consumed type 1. * @param Thrown exception. */ @@ -216,141 +185,11 @@ public interface FailableConsumer { void accept(O object) throws T; } - /** - * A functional interface like {@link DoubleBinaryOperator} that declares a {@code Throwable}. - * - * @param Thrown exception. - * @since 3.11 - */ - @FunctionalInterface - public interface FailableDoubleBinaryOperator { - - /** - * Applies this operator to the given operands. - * - * @param left the first operand - * @param right the second operand - * @return the operator result - * @throws T if the operation fails - */ - double applyAsDouble(double left, double right) throws T; - } - - /** - * A functional interface like {@link DoubleConsumer} that declares a {@code Throwable}. - * - * @param Thrown exception. - * @since 3.11 - */ - @FunctionalInterface - public interface FailableDoubleConsumer { - - /** - * Accepts the consumer. - * - * @param value the parameter for the consumable to accept - * @throws T Thrown when the consumer fails. - */ - void accept(double value) throws T; - } - - /** - * A functional interface like {@link DoubleFunction} that declares a {@code Throwable}. - * - * @param Return type. - * @param Thrown exception. - */ - @FunctionalInterface - public interface FailableDoubleFunction { - - /** - * Applies this function. - * - * @param input the input for the function - * @return the result of the function - * @throws T Thrown when the function fails. - */ - R apply(double input) throws T; - } - - /** - * A functional interface like {@link DoublePredicate} that declares a {@code Throwable}. - * - * @param Thrown exception. - * @since 3.11 - */ - @FunctionalInterface - public interface FailableDoublePredicate { - - /** - * Tests the predicate. - * - * @param value the parameter for the predicate to accept. - * @return {@code true} if the input argument matches the predicate, {@code false} otherwise. - * @throws T Thrown when the consumer fails. - */ - boolean test(double value) throws T; - } - - /** - * A functional interface like {@link DoubleSupplier} that declares a {@code Throwable}. - * - * @param Thrown exception. - * @since 3.11 - */ - @FunctionalInterface - public interface FailableDoubleSupplier { - - /** - * Supplies a double. - * - * @return a result - * @throws T if the supplier fails - */ - double getAsDouble() throws T; - } - - /** - * A functional interface like {@link DoubleToIntFunction} that declares a {@code Throwable}. - * - * @param Thrown exception. - * @since 3.11 - */ - @FunctionalInterface - public interface FailableDoubleToIntFunction { - - /** - * Applies this function to the given argument. - * - * @param value the function argument - * @return the function result - * @throws T Thrown when the function fails. - */ - int applyAsInt(double value) throws T; - } - - /** - * A functional interface like {@link DoubleToLongFunction} that declares a {@code Throwable}. - * - * @param Thrown exception. - * @since 3.11 - */ - @FunctionalInterface - public interface FailableDoubleToLongFunction { - - /** - * Applies this function to the given argument. - * - * @param value the function argument - * @return the function result - * @throws T if the operation fails - */ - int applyAsLong(double value) throws T; - } - /** * A functional interface like {@link Function} that declares a {@code Throwable}. * + *

      TODO for 4.0: Move to org.apache.commons.lang3.function.

      + * * @param Input type 1. * @param Return type. * @param Thrown exception. @@ -368,333 +207,11 @@ public interface FailableFunction { R apply(I input) throws T; } - /** - * A functional interface like {@link IntBinaryOperator} that declares a {@code Throwable}. - * - * @param Thrown exception. - * @since 3.11 - */ - @FunctionalInterface - public interface FailableIntBinaryOperator { - - /** - * Applies this operator to the given operands. - * - * @param left the first operand - * @param right the second operand - * @return the operator result - * @throws T if the operation fails - */ - int applyAsInt(int left, int right) throws T; - } - - /** - * A functional interface like {@link IntConsumer} that declares a {@code Throwable}. - * - * @param Thrown exception. - * @since 3.11 - */ - @FunctionalInterface - public interface FailableIntConsumer { - - /** - * Accepts the consumer. - * - * @param value the parameter for the consumable to accept - * @throws T Thrown when the consumer fails. - */ - void accept(int value) throws T; - } - - /** - * A functional interface like {@link IntFunction} that declares a {@code Throwable}. - * - * @param Return type. - * @param Thrown exception. - */ - @FunctionalInterface - public interface FailableIntFunction { - - /** - * Applies this function. - * - * @param input the input for the function - * @return the result of the function - * @throws T Thrown when the function fails. - */ - R apply(int input) throws T; - } - - /** - * A functional interface like {@link IntPredicate} that declares a {@code Throwable}. - * - * @param Thrown exception. - * @since 3.11 - */ - @FunctionalInterface - public interface FailableIntPredicate { - - /** - * Tests the predicate. - * - * @param value the parameter for the predicate to accept. - * @return {@code true} if the input argument matches the predicate, {@code false} otherwise. - * @throws T Thrown when the consumer fails. - */ - boolean test(int value) throws T; - } - - /** - * A functional interface like {@link IntSupplier} that declares a {@code Throwable}. - * - * @param Thrown exception. - * @since 3.11 - */ - @FunctionalInterface - public interface FailableIntSupplier { - - /** - * Supplies an int. - * - * @return a result - * @throws T if the supplier fails - */ - int getAsInt() throws T; - } - - /** - * A functional interface like {@link IntToDoubleFunction} that declares a {@code Throwable}. - * - * @param Thrown exception. - * @since 3.11 - */ - @FunctionalInterface - public interface FailableIntToDoubleFunction { - - /** - * Applies this function to the given argument. - * - * @param value the function argument - * @return the function result - * @throws T Thrown when the function fails. - */ - double applyAsDouble(int value) throws T; - } - - /** - * A functional interface like {@link IntToLongFunction} that declares a {@code Throwable}. - * - * @param Thrown exception. - * @since 3.11 - */ - @FunctionalInterface - public interface FailableIntToLongFunction { - - /** - * Applies this function to the given argument. - * - * @param value the function argument - * @return the function result - * @throws T Thrown when the function fails. - */ - long applyAsLong(int value) throws T; - } - - /** - * A functional interface like {@link LongBinaryOperator} that declares a {@code Throwable}. - * - * @param Thrown exception. - * @since 3.11 - */ - @FunctionalInterface - public interface FailableLongBinaryOperator { - - /** - * Applies this operator to the given operands. - * - * @param left the first operand - * @param right the second operand - * @return the operator result - * @throws T if the operation fails - */ - long applyAsLong(long left, long right) throws T; - } - - /** - * A functional interface like {@link LongConsumer} that declares a {@code Throwable}. - * - * @param Thrown exception. - * @since 3.11 - */ - @FunctionalInterface - public interface FailableLongConsumer { - - /** - * Accepts the consumer. - * - * @param object the parameter for the consumable to accept - * @throws T Thrown when the consumer fails. - */ - void accept(long object) throws T; - } - - /** - * A functional interface like {@link LongFunction} that declares a {@code Throwable}. - * - * @param Return type. - * @param Thrown exception. - */ - @FunctionalInterface - public interface FailableLongFunction { - - /** - * Applies this function. - * - * @param input the input for the function - * @return the result of the function - * @throws T Thrown when the function fails. - */ - R apply(long input) throws T; - } - - /** - * A functional interface like {@link LongPredicate} that declares a {@code Throwable}. - * - * @param Thrown exception. - * @since 3.11 - */ - @FunctionalInterface - public interface FailableLongPredicate { - - /** - * Tests the predicate. - * - * @param value the parameter for the predicate to accept. - * @return {@code true} if the input argument matches the predicate, {@code false} otherwise. - * @throws T Thrown when the consumer fails. - */ - boolean test(long value) throws T; - } - - /** - * A functional interface like {@link LongSupplier} that declares a {@code Throwable}. - * - * @param Thrown exception. - * @since 3.11 - */ - @FunctionalInterface - public interface FailableLongSupplier { - - /** - * Supplies a long. - * - * @return a result - * @throws T if the supplier fails - */ - long getAsLong() throws T; - } - - /** - * A functional interface like {@link LongToDoubleFunction} that declares a {@code Throwable}. - * - * @param Thrown exception. - * @since 3.11 - */ - @FunctionalInterface - public interface FailableLongToDoubleFunction { - - /** - * Applies this function to the given argument. - * - * @param value the function argument - * @return the function result - * @throws T Thrown when the function fails. - */ - double applyAsDouble(long value) throws T; - } - - /** - * A functional interface like {@link LongToIntFunction} that declares a {@code Throwable}. - * - * @param Thrown exception. - * @since 3.11 - */ - @FunctionalInterface - public interface FailableLongToIntFunction { - - /** - * Applies this function to the given argument. - * - * @param value the function argument - * @return the function result - * @throws T Thrown when the function fails. - */ - int applyAsInt(long value) throws T; - } - - /** - * A functional interface like {@link ObjDoubleConsumer} that declares a {@code Throwable}. - * - * @param the type of the object argument to the operation. - * @param Thrown exception. - * @since 3.11 - */ - @FunctionalInterface - public interface FailableObjDoubleConsumer { - - /** - * Accepts the consumer. - * - * @param object the object parameter for the consumable to accept. - * @param value the double parameter for the consumable to accept. - * @throws T Thrown when the consumer fails. - */ - void accept(O object, double value) throws T; - } - - /** - * A functional interface like {@link ObjIntConsumer} that declares a {@code Throwable}. - * - * @param the type of the object argument to the operation. - * @param Thrown exception. - * @since 3.11 - */ - @FunctionalInterface - public interface FailableObjIntConsumer { - - /** - * Accepts the consumer. - * - * @param object the object parameter for the consumable to accept. - * @param value the int parameter for the consumable to accept. - * @throws T Thrown when the consumer fails. - */ - void accept(O object, int value) throws T; - } - - /** - * A functional interface like {@link ObjLongConsumer} that declares a {@code Throwable}. - * - * @param the type of the object argument to the operation. - * @param Thrown exception. - * @since 3.11 - */ - @FunctionalInterface - public interface FailableObjLongConsumer { - - /** - * Accepts the consumer. - * - * @param object the object parameter for the consumable to accept. - * @param value the long parameter for the consumable to accept. - * @throws T Thrown when the consumer fails. - */ - void accept(O object, long value) throws T; - } - /** * A functional interface like {@link Predicate} that declares a {@code Throwable}. * + *

      TODO for 4.0: Move to org.apache.commons.lang3.function.

      + * * @param Predicate type 1. * @param Thrown exception. */ @@ -714,6 +231,8 @@ public interface FailablePredicate { /** * A functional interface like {@link Runnable} that declares a {@code Throwable}. * + *

      TODO for 4.0: Move to org.apache.commons.lang3.function.

      + * * @param Thrown exception. */ @FunctionalInterface @@ -730,6 +249,8 @@ public interface FailableRunnable { /** * A functional interface like {@link Supplier} that declares a {@code Throwable}. * + *

      TODO for 4.0: Move to org.apache.commons.lang3.function.

      + * * @param Return type. * @param Thrown exception. */ @@ -745,132 +266,6 @@ public interface FailableSupplier { R get() throws T; } - /** - * A functional interface like {@link ToDoubleBiFunction} that declares a {@code Throwable}. - * - * @param the type of the first argument to the function - * @param the type of the second argument to the function - * @param Thrown exception. - * @since 3.11 - */ - @FunctionalInterface - public interface FailableToDoubleBiFunction { - - /** - * Applies this function to the given arguments. - * - * @param t the first function argument - * @param u the second function argument - * @return the function result - * @throws T Thrown when the function fails. - */ - double applyAsDouble(O1 t, O2 u) throws T; - } - - /** - * A functional interface like {@link ToDoubleFunction} that declares a {@code Throwable}. - * - * @param the type of the first argument to the function - * @param Thrown exception. - * @since 3.11 - */ - @FunctionalInterface - public interface FailableToDoubleFunction { - - /** - * Applies this function to the given arguments. - * - * @param t the first function argument - * @return the function result - * @throws T Thrown when the function fails. - */ - double applyAsDouble(I t) throws T; - } - - /** - * A functional interface like {@link ToIntBiFunction} that declares a {@code Throwable}. - * - * @param the type of the first argument to the function - * @param the type of the second argument to the function - * @param Thrown exception. - * @since 3.11 - */ - @FunctionalInterface - public interface FailableToIntBiFunction { - - /** - * Applies this function to the given arguments. - * - * @param t the first function argument - * @param u the second function argument - * @return the function result - * @throws T Thrown when the function fails. - */ - int applyAsInt(O1 t, O2 u) throws T; - } - - /** - * A functional interface like {@link ToIntFunction} that declares a {@code Throwable}. - * - * @param the type of the first argument to the function - * @param Thrown exception. - * @since 3.11 - */ - @FunctionalInterface - public interface FailableToIntFunction { - - /** - * Applies this function to the given arguments. - * - * @param t the first function argument - * @return the function result - * @throws T Thrown when the function fails. - */ - int applyAsInt(I t) throws T; - } - - /** - * A functional interface like {@link ToLongBiFunction} that declares a {@code Throwable}. - * - * @param the type of the first argument to the function - * @param the type of the second argument to the function - * @param Thrown exception. - * @since 3.11 - */ - @FunctionalInterface - public interface FailableToLongBiFunction { - - /** - * Applies this function to the given arguments. - * - * @param t the first function argument - * @param u the second function argument - * @return the function result - * @throws T Thrown when the function fails. - */ - long applyAsLong(O1 t, O2 u) throws T; - } - - /** - * A functional interface like {@link ToLongFunction} that declares a {@code Throwable}. - * - * @param the type of the first argument to the function - * @param Thrown exception. - * @since 3.11 - */ - @FunctionalInterface - public interface FailableToLongFunction { - - /** - * Applies this function to the given arguments. - * - * @param t the first function argument - * @return the function result - * @throws T Thrown when the function fails. - */ - long applyAsLong(I t) throws T; - } - /** * Consumes a consumer and rethrows any exception as a {@link RuntimeException}. * diff --git a/src/main/java/org/apache/commons/lang3/function/FailableBooleanSupplier.java b/src/main/java/org/apache/commons/lang3/function/FailableBooleanSupplier.java new file mode 100644 index 00000000000..0deaef5c3d3 --- /dev/null +++ b/src/main/java/org/apache/commons/lang3/function/FailableBooleanSupplier.java @@ -0,0 +1,38 @@ +/* + * 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.function; + +import java.util.function.BooleanSupplier; + +/** + * A functional interface like {@link BooleanSupplier} that declares a {@code Throwable}. + * + * @param Thrown exception. + * @since 3.11 + */ +@FunctionalInterface +public interface FailableBooleanSupplier { + + /** + * Supplies a boolean. + * + * @return a result + * @throws T if the supplier fails + */ + boolean getAsBoolean() throws T; +} \ No newline at end of file diff --git a/src/main/java/org/apache/commons/lang3/function/FailableDoubleBinaryOperator.java b/src/main/java/org/apache/commons/lang3/function/FailableDoubleBinaryOperator.java new file mode 100644 index 00000000000..db58976cda8 --- /dev/null +++ b/src/main/java/org/apache/commons/lang3/function/FailableDoubleBinaryOperator.java @@ -0,0 +1,40 @@ +/* + * 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.function; + +import java.util.function.DoubleBinaryOperator; + +/** + * A functional interface like {@link DoubleBinaryOperator} that declares a {@code Throwable}. + * + * @param Thrown exception. + * @since 3.11 + */ +@FunctionalInterface +public interface FailableDoubleBinaryOperator { + + /** + * Applies this operator to the given operands. + * + * @param left the first operand + * @param right the second operand + * @return the operator result + * @throws T if the operation fails + */ + double applyAsDouble(double left, double right) throws T; +} \ No newline at end of file diff --git a/src/main/java/org/apache/commons/lang3/function/FailableDoubleConsumer.java b/src/main/java/org/apache/commons/lang3/function/FailableDoubleConsumer.java new file mode 100644 index 00000000000..ade6e0c1542 --- /dev/null +++ b/src/main/java/org/apache/commons/lang3/function/FailableDoubleConsumer.java @@ -0,0 +1,38 @@ +/* + * 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.function; + +import java.util.function.DoubleConsumer; + +/** + * A functional interface like {@link DoubleConsumer} that declares a {@code Throwable}. + * + * @param Thrown exception. + * @since 3.11 + */ +@FunctionalInterface +public interface FailableDoubleConsumer { + + /** + * Accepts the consumer. + * + * @param value the parameter for the consumable to accept + * @throws T Thrown when the consumer fails. + */ + void accept(double value) throws T; +} \ No newline at end of file diff --git a/src/main/java/org/apache/commons/lang3/function/FailableDoubleFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableDoubleFunction.java new file mode 100644 index 00000000000..156b204343d --- /dev/null +++ b/src/main/java/org/apache/commons/lang3/function/FailableDoubleFunction.java @@ -0,0 +1,40 @@ +/* + * 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.function; + +import java.util.function.DoubleFunction; + +/** + * A functional interface like {@link DoubleFunction} that declares a {@code Throwable}. + * + * @param Return type. + * @param Thrown exception. + * @since 3.11 + */ +@FunctionalInterface +public interface FailableDoubleFunction { + + /** + * Applies this function. + * + * @param input the input for the function + * @return the result of the function + * @throws T Thrown when the function fails. + */ + R apply(double input) throws T; +} \ No newline at end of file diff --git a/src/main/java/org/apache/commons/lang3/function/FailableDoublePredicate.java b/src/main/java/org/apache/commons/lang3/function/FailableDoublePredicate.java new file mode 100644 index 00000000000..fda8786ac34 --- /dev/null +++ b/src/main/java/org/apache/commons/lang3/function/FailableDoublePredicate.java @@ -0,0 +1,39 @@ +/* + * 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.function; + +import java.util.function.DoublePredicate; + +/** + * A functional interface like {@link DoublePredicate} that declares a {@code Throwable}. + * + * @param Thrown exception. + * @since 3.11 + */ +@FunctionalInterface +public interface FailableDoublePredicate { + + /** + * Tests the predicate. + * + * @param value the parameter for the predicate to accept. + * @return {@code true} if the input argument matches the predicate, {@code false} otherwise. + * @throws T Thrown when the consumer fails. + */ + boolean test(double value) throws T; +} \ No newline at end of file diff --git a/src/main/java/org/apache/commons/lang3/function/FailableDoubleSupplier.java b/src/main/java/org/apache/commons/lang3/function/FailableDoubleSupplier.java new file mode 100644 index 00000000000..9fb751bfed7 --- /dev/null +++ b/src/main/java/org/apache/commons/lang3/function/FailableDoubleSupplier.java @@ -0,0 +1,38 @@ +/* + * 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.function; + +import java.util.function.DoubleSupplier; + +/** + * A functional interface like {@link DoubleSupplier} that declares a {@code Throwable}. + * + * @param Thrown exception. + * @since 3.11 + */ +@FunctionalInterface +public interface FailableDoubleSupplier { + + /** + * Supplies a double. + * + * @return a result + * @throws T if the supplier fails + */ + double getAsDouble() throws T; +} \ No newline at end of file diff --git a/src/main/java/org/apache/commons/lang3/function/FailableDoubleToIntFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableDoubleToIntFunction.java new file mode 100644 index 00000000000..00db9f3eeab --- /dev/null +++ b/src/main/java/org/apache/commons/lang3/function/FailableDoubleToIntFunction.java @@ -0,0 +1,39 @@ +/* + * 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.function; + +import java.util.function.DoubleToIntFunction; + +/** + * A functional interface like {@link DoubleToIntFunction} that declares a {@code Throwable}. + * + * @param Thrown exception. + * @since 3.11 + */ +@FunctionalInterface +public interface FailableDoubleToIntFunction { + + /** + * Applies this function to the given argument. + * + * @param value the function argument + * @return the function result + * @throws T Thrown when the function fails. + */ + int applyAsInt(double value) throws T; +} \ No newline at end of file diff --git a/src/main/java/org/apache/commons/lang3/function/FailableDoubleToLongFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableDoubleToLongFunction.java new file mode 100644 index 00000000000..0eae76c49e7 --- /dev/null +++ b/src/main/java/org/apache/commons/lang3/function/FailableDoubleToLongFunction.java @@ -0,0 +1,39 @@ +/* + * 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.function; + +import java.util.function.DoubleToLongFunction; + +/** + * A functional interface like {@link DoubleToLongFunction} that declares a {@code Throwable}. + * + * @param Thrown exception. + * @since 3.11 + */ +@FunctionalInterface +public interface FailableDoubleToLongFunction { + + /** + * Applies this function to the given argument. + * + * @param value the function argument + * @return the function result + * @throws T if the operation fails + */ + int applyAsLong(double value) throws T; +} \ No newline at end of file diff --git a/src/main/java/org/apache/commons/lang3/function/FailableIntBinaryOperator.java b/src/main/java/org/apache/commons/lang3/function/FailableIntBinaryOperator.java new file mode 100644 index 00000000000..3eaca9dccac --- /dev/null +++ b/src/main/java/org/apache/commons/lang3/function/FailableIntBinaryOperator.java @@ -0,0 +1,40 @@ +/* + * 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.function; + +import java.util.function.IntBinaryOperator; + +/** + * A functional interface like {@link IntBinaryOperator} that declares a {@code Throwable}. + * + * @param Thrown exception. + * @since 3.11 + */ +@FunctionalInterface +public interface FailableIntBinaryOperator { + + /** + * Applies this operator to the given operands. + * + * @param left the first operand + * @param right the second operand + * @return the operator result + * @throws T if the operation fails + */ + int applyAsInt(int left, int right) throws T; +} \ No newline at end of file diff --git a/src/main/java/org/apache/commons/lang3/function/FailableIntConsumer.java b/src/main/java/org/apache/commons/lang3/function/FailableIntConsumer.java new file mode 100644 index 00000000000..54e77104814 --- /dev/null +++ b/src/main/java/org/apache/commons/lang3/function/FailableIntConsumer.java @@ -0,0 +1,38 @@ +/* + * 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.function; + +import java.util.function.IntConsumer; + +/** + * A functional interface like {@link IntConsumer} that declares a {@code Throwable}. + * + * @param Thrown exception. + * @since 3.11 + */ +@FunctionalInterface +public interface FailableIntConsumer { + + /** + * Accepts the consumer. + * + * @param value the parameter for the consumable to accept + * @throws T Thrown when the consumer fails. + */ + void accept(int value) throws T; +} \ No newline at end of file diff --git a/src/main/java/org/apache/commons/lang3/function/FailableIntFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableIntFunction.java new file mode 100644 index 00000000000..07e35c63db7 --- /dev/null +++ b/src/main/java/org/apache/commons/lang3/function/FailableIntFunction.java @@ -0,0 +1,40 @@ +/* + * 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.function; + +import java.util.function.IntFunction; + +/** + * A functional interface like {@link IntFunction} that declares a {@code Throwable}. + * + * @param Return type. + * @param Thrown exception. + * @since 3.11 + */ +@FunctionalInterface +public interface FailableIntFunction { + + /** + * Applies this function. + * + * @param input the input for the function + * @return the result of the function + * @throws T Thrown when the function fails. + */ + R apply(int input) throws T; +} \ No newline at end of file diff --git a/src/main/java/org/apache/commons/lang3/function/FailableIntPredicate.java b/src/main/java/org/apache/commons/lang3/function/FailableIntPredicate.java new file mode 100644 index 00000000000..40e3877f295 --- /dev/null +++ b/src/main/java/org/apache/commons/lang3/function/FailableIntPredicate.java @@ -0,0 +1,39 @@ +/* + * 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.function; + +import java.util.function.IntPredicate; + +/** + * A functional interface like {@link IntPredicate} that declares a {@code Throwable}. + * + * @param Thrown exception. + * @since 3.11 + */ +@FunctionalInterface +public interface FailableIntPredicate { + + /** + * Tests the predicate. + * + * @param value the parameter for the predicate to accept. + * @return {@code true} if the input argument matches the predicate, {@code false} otherwise. + * @throws T Thrown when the consumer fails. + */ + boolean test(int value) throws T; +} \ No newline at end of file diff --git a/src/main/java/org/apache/commons/lang3/function/FailableIntSupplier.java b/src/main/java/org/apache/commons/lang3/function/FailableIntSupplier.java new file mode 100644 index 00000000000..fed9cd23ad0 --- /dev/null +++ b/src/main/java/org/apache/commons/lang3/function/FailableIntSupplier.java @@ -0,0 +1,38 @@ +/* + * 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.function; + +import java.util.function.IntSupplier; + +/** + * A functional interface like {@link IntSupplier} that declares a {@code Throwable}. + * + * @param Thrown exception. + * @since 3.11 + */ +@FunctionalInterface +public interface FailableIntSupplier { + + /** + * Supplies an int. + * + * @return a result + * @throws T if the supplier fails + */ + int getAsInt() throws T; +} \ No newline at end of file diff --git a/src/main/java/org/apache/commons/lang3/function/FailableIntToDoubleFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableIntToDoubleFunction.java new file mode 100644 index 00000000000..f0d916435ce --- /dev/null +++ b/src/main/java/org/apache/commons/lang3/function/FailableIntToDoubleFunction.java @@ -0,0 +1,39 @@ +/* + * 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.function; + +import java.util.function.IntToDoubleFunction; + +/** + * A functional interface like {@link IntToDoubleFunction} that declares a {@code Throwable}. + * + * @param Thrown exception. + * @since 3.11 + */ +@FunctionalInterface +public interface FailableIntToDoubleFunction { + + /** + * Applies this function to the given argument. + * + * @param value the function argument + * @return the function result + * @throws T Thrown when the function fails. + */ + double applyAsDouble(int value) throws T; +} \ No newline at end of file diff --git a/src/main/java/org/apache/commons/lang3/function/FailableIntToLongFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableIntToLongFunction.java new file mode 100644 index 00000000000..f88d5ef51af --- /dev/null +++ b/src/main/java/org/apache/commons/lang3/function/FailableIntToLongFunction.java @@ -0,0 +1,39 @@ +/* + * 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.function; + +import java.util.function.IntToLongFunction; + +/** + * A functional interface like {@link IntToLongFunction} that declares a {@code Throwable}. + * + * @param Thrown exception. + * @since 3.11 + */ +@FunctionalInterface +public interface FailableIntToLongFunction { + + /** + * Applies this function to the given argument. + * + * @param value the function argument + * @return the function result + * @throws T Thrown when the function fails. + */ + long applyAsLong(int value) throws T; +} \ No newline at end of file diff --git a/src/main/java/org/apache/commons/lang3/function/FailableLongBinaryOperator.java b/src/main/java/org/apache/commons/lang3/function/FailableLongBinaryOperator.java new file mode 100644 index 00000000000..e58acf4437d --- /dev/null +++ b/src/main/java/org/apache/commons/lang3/function/FailableLongBinaryOperator.java @@ -0,0 +1,40 @@ +/* + * 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.function; + +import java.util.function.LongBinaryOperator; + +/** + * A functional interface like {@link LongBinaryOperator} that declares a {@code Throwable}. + * + * @param Thrown exception. + * @since 3.11 + */ +@FunctionalInterface +public interface FailableLongBinaryOperator { + + /** + * Applies this operator to the given operands. + * + * @param left the first operand + * @param right the second operand + * @return the operator result + * @throws T if the operation fails + */ + long applyAsLong(long left, long right) throws T; +} \ No newline at end of file diff --git a/src/main/java/org/apache/commons/lang3/function/FailableLongConsumer.java b/src/main/java/org/apache/commons/lang3/function/FailableLongConsumer.java new file mode 100644 index 00000000000..7eb784f7c04 --- /dev/null +++ b/src/main/java/org/apache/commons/lang3/function/FailableLongConsumer.java @@ -0,0 +1,38 @@ +/* + * 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.function; + +import java.util.function.LongConsumer; + +/** + * A functional interface like {@link LongConsumer} that declares a {@code Throwable}. + * + * @param Thrown exception. + * @since 3.11 + */ +@FunctionalInterface +public interface FailableLongConsumer { + + /** + * Accepts the consumer. + * + * @param object the parameter for the consumable to accept + * @throws T Thrown when the consumer fails. + */ + void accept(long object) throws T; +} \ No newline at end of file diff --git a/src/main/java/org/apache/commons/lang3/function/FailableLongFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableLongFunction.java new file mode 100644 index 00000000000..904f9466269 --- /dev/null +++ b/src/main/java/org/apache/commons/lang3/function/FailableLongFunction.java @@ -0,0 +1,40 @@ +/* + * 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.function; + +import java.util.function.LongFunction; + +/** + * A functional interface like {@link LongFunction} that declares a {@code Throwable}. + * + * @param Return type. + * @param Thrown exception. + * @since 3.11 + */ +@FunctionalInterface +public interface FailableLongFunction { + + /** + * Applies this function. + * + * @param input the input for the function + * @return the result of the function + * @throws T Thrown when the function fails. + */ + R apply(long input) throws T; +} \ No newline at end of file diff --git a/src/main/java/org/apache/commons/lang3/function/FailableLongPredicate.java b/src/main/java/org/apache/commons/lang3/function/FailableLongPredicate.java new file mode 100644 index 00000000000..259b82ea6da --- /dev/null +++ b/src/main/java/org/apache/commons/lang3/function/FailableLongPredicate.java @@ -0,0 +1,39 @@ +/* + * 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.function; + +import java.util.function.LongPredicate; + +/** + * A functional interface like {@link LongPredicate} that declares a {@code Throwable}. + * + * @param Thrown exception. + * @since 3.11 + */ +@FunctionalInterface +public interface FailableLongPredicate { + + /** + * Tests the predicate. + * + * @param value the parameter for the predicate to accept. + * @return {@code true} if the input argument matches the predicate, {@code false} otherwise. + * @throws T Thrown when the consumer fails. + */ + boolean test(long value) throws T; +} \ No newline at end of file diff --git a/src/main/java/org/apache/commons/lang3/function/FailableLongSupplier.java b/src/main/java/org/apache/commons/lang3/function/FailableLongSupplier.java new file mode 100644 index 00000000000..67a1aa43078 --- /dev/null +++ b/src/main/java/org/apache/commons/lang3/function/FailableLongSupplier.java @@ -0,0 +1,38 @@ +/* + * 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.function; + +import java.util.function.LongSupplier; + +/** + * A functional interface like {@link LongSupplier} that declares a {@code Throwable}. + * + * @param Thrown exception. + * @since 3.11 + */ +@FunctionalInterface +public interface FailableLongSupplier { + + /** + * Supplies a long. + * + * @return a result + * @throws T if the supplier fails + */ + long getAsLong() throws T; +} \ No newline at end of file diff --git a/src/main/java/org/apache/commons/lang3/function/FailableLongToDoubleFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableLongToDoubleFunction.java new file mode 100644 index 00000000000..dcd64eca45b --- /dev/null +++ b/src/main/java/org/apache/commons/lang3/function/FailableLongToDoubleFunction.java @@ -0,0 +1,39 @@ +/* + * 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.function; + +import java.util.function.LongToDoubleFunction; + +/** + * A functional interface like {@link LongToDoubleFunction} that declares a {@code Throwable}. + * + * @param Thrown exception. + * @since 3.11 + */ +@FunctionalInterface +public interface FailableLongToDoubleFunction { + + /** + * Applies this function to the given argument. + * + * @param value the function argument + * @return the function result + * @throws T Thrown when the function fails. + */ + double applyAsDouble(long value) throws T; +} \ No newline at end of file diff --git a/src/main/java/org/apache/commons/lang3/function/FailableLongToIntFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableLongToIntFunction.java new file mode 100644 index 00000000000..80cb6ae90d7 --- /dev/null +++ b/src/main/java/org/apache/commons/lang3/function/FailableLongToIntFunction.java @@ -0,0 +1,39 @@ +/* + * 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.function; + +import java.util.function.LongToIntFunction; + +/** + * A functional interface like {@link LongToIntFunction} that declares a {@code Throwable}. + * + * @param Thrown exception. + * @since 3.11 + */ +@FunctionalInterface +public interface FailableLongToIntFunction { + + /** + * Applies this function to the given argument. + * + * @param value the function argument + * @return the function result + * @throws T Thrown when the function fails. + */ + int applyAsInt(long value) throws T; +} \ No newline at end of file diff --git a/src/main/java/org/apache/commons/lang3/function/FailableObjDoubleConsumer.java b/src/main/java/org/apache/commons/lang3/function/FailableObjDoubleConsumer.java new file mode 100644 index 00000000000..a18d3f31025 --- /dev/null +++ b/src/main/java/org/apache/commons/lang3/function/FailableObjDoubleConsumer.java @@ -0,0 +1,40 @@ +/* + * 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.function; + +import java.util.function.ObjDoubleConsumer; + +/** + * A functional interface like {@link ObjDoubleConsumer} that declares a {@code Throwable}. + * + * @param the type of the object argument to the operation. + * @param Thrown exception. + * @since 3.11 + */ +@FunctionalInterface +public interface FailableObjDoubleConsumer { + + /** + * Accepts the consumer. + * + * @param object the object parameter for the consumable to accept. + * @param value the double parameter for the consumable to accept. + * @throws T Thrown when the consumer fails. + */ + void accept(O object, double value) throws T; +} \ No newline at end of file diff --git a/src/main/java/org/apache/commons/lang3/function/FailableObjIntConsumer.java b/src/main/java/org/apache/commons/lang3/function/FailableObjIntConsumer.java new file mode 100644 index 00000000000..21bf5cda98f --- /dev/null +++ b/src/main/java/org/apache/commons/lang3/function/FailableObjIntConsumer.java @@ -0,0 +1,40 @@ +/* + * 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.function; + +import java.util.function.ObjIntConsumer; + +/** + * A functional interface like {@link ObjIntConsumer} that declares a {@code Throwable}. + * + * @param the type of the object argument to the operation. + * @param Thrown exception. + * @since 3.11 + */ +@FunctionalInterface +public interface FailableObjIntConsumer { + + /** + * Accepts the consumer. + * + * @param object the object parameter for the consumable to accept. + * @param value the int parameter for the consumable to accept. + * @throws T Thrown when the consumer fails. + */ + void accept(O object, int value) throws T; +} \ No newline at end of file diff --git a/src/main/java/org/apache/commons/lang3/function/FailableObjLongConsumer.java b/src/main/java/org/apache/commons/lang3/function/FailableObjLongConsumer.java new file mode 100644 index 00000000000..32c42563b36 --- /dev/null +++ b/src/main/java/org/apache/commons/lang3/function/FailableObjLongConsumer.java @@ -0,0 +1,40 @@ +/* + * 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.function; + +import java.util.function.ObjLongConsumer; + +/** + * A functional interface like {@link ObjLongConsumer} that declares a {@code Throwable}. + * + * @param the type of the object argument to the operation. + * @param Thrown exception. + * @since 3.11 + */ +@FunctionalInterface +public interface FailableObjLongConsumer { + + /** + * Accepts the consumer. + * + * @param object the object parameter for the consumable to accept. + * @param value the long parameter for the consumable to accept. + * @throws T Thrown when the consumer fails. + */ + void accept(O object, long value) throws T; +} \ No newline at end of file diff --git a/src/main/java/org/apache/commons/lang3/function/FailableToDoubleBiFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableToDoubleBiFunction.java new file mode 100644 index 00000000000..de932f46882 --- /dev/null +++ b/src/main/java/org/apache/commons/lang3/function/FailableToDoubleBiFunction.java @@ -0,0 +1,42 @@ +/* + * 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.function; + +import java.util.function.ToDoubleBiFunction; + +/** + * A functional interface like {@link ToDoubleBiFunction} that declares a {@code Throwable}. + * + * @param the type of the first argument to the function + * @param the type of the second argument to the function + * @param Thrown exception. + * @since 3.11 + */ +@FunctionalInterface +public interface FailableToDoubleBiFunction { + + /** + * Applies this function to the given arguments. + * + * @param t the first function argument + * @param u the second function argument + * @return the function result + * @throws T Thrown when the function fails. + */ + double applyAsDouble(O1 t, O2 u) throws T; +} \ No newline at end of file diff --git a/src/main/java/org/apache/commons/lang3/function/FailableToDoubleFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableToDoubleFunction.java new file mode 100644 index 00000000000..1edc934ba3e --- /dev/null +++ b/src/main/java/org/apache/commons/lang3/function/FailableToDoubleFunction.java @@ -0,0 +1,40 @@ +/* + * 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.function; + +import java.util.function.ToDoubleFunction; + +/** + * A functional interface like {@link ToDoubleFunction} that declares a {@code Throwable}. + * + * @param the type of the first argument to the function + * @param Thrown exception. + * @since 3.11 + */ +@FunctionalInterface +public interface FailableToDoubleFunction { + + /** + * Applies this function to the given arguments. + * + * @param t the first function argument + * @return the function result + * @throws T Thrown when the function fails. + */ + double applyAsDouble(I t) throws T; +} \ No newline at end of file diff --git a/src/main/java/org/apache/commons/lang3/function/FailableToIntBiFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableToIntBiFunction.java new file mode 100644 index 00000000000..126a80c5d4d --- /dev/null +++ b/src/main/java/org/apache/commons/lang3/function/FailableToIntBiFunction.java @@ -0,0 +1,42 @@ +/* + * 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.function; + +import java.util.function.ToIntBiFunction; + +/** + * A functional interface like {@link ToIntBiFunction} that declares a {@code Throwable}. + * + * @param the type of the first argument to the function + * @param the type of the second argument to the function + * @param Thrown exception. + * @since 3.11 + */ +@FunctionalInterface +public interface FailableToIntBiFunction { + + /** + * Applies this function to the given arguments. + * + * @param t the first function argument + * @param u the second function argument + * @return the function result + * @throws T Thrown when the function fails. + */ + int applyAsInt(O1 t, O2 u) throws T; +} \ No newline at end of file diff --git a/src/main/java/org/apache/commons/lang3/function/FailableToIntFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableToIntFunction.java new file mode 100644 index 00000000000..27c2dae09ea --- /dev/null +++ b/src/main/java/org/apache/commons/lang3/function/FailableToIntFunction.java @@ -0,0 +1,40 @@ +/* + * 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.function; + +import java.util.function.ToIntFunction; + +/** + * A functional interface like {@link ToIntFunction} that declares a {@code Throwable}. + * + * @param the type of the first argument to the function + * @param Thrown exception. + * @since 3.11 + */ +@FunctionalInterface +public interface FailableToIntFunction { + + /** + * Applies this function to the given arguments. + * + * @param t the first function argument + * @return the function result + * @throws T Thrown when the function fails. + */ + int applyAsInt(I t) throws T; +} \ No newline at end of file diff --git a/src/main/java/org/apache/commons/lang3/function/FailableToLongBiFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableToLongBiFunction.java new file mode 100644 index 00000000000..dcf2fcae424 --- /dev/null +++ b/src/main/java/org/apache/commons/lang3/function/FailableToLongBiFunction.java @@ -0,0 +1,42 @@ +/* + * 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.function; + +import java.util.function.ToLongBiFunction; + +/** + * A functional interface like {@link ToLongBiFunction} that declares a {@code Throwable}. + * + * @param the type of the first argument to the function + * @param the type of the second argument to the function + * @param Thrown exception. + * @since 3.11 + */ +@FunctionalInterface +public interface FailableToLongBiFunction { + + /** + * Applies this function to the given arguments. + * + * @param t the first function argument + * @param u the second function argument + * @return the function result + * @throws T Thrown when the function fails. + */ + long applyAsLong(O1 t, O2 u) throws T; +} \ No newline at end of file diff --git a/src/main/java/org/apache/commons/lang3/function/FailableToLongFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableToLongFunction.java new file mode 100644 index 00000000000..999541134c6 --- /dev/null +++ b/src/main/java/org/apache/commons/lang3/function/FailableToLongFunction.java @@ -0,0 +1,40 @@ +/* + * 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.function; + +import java.util.function.ToLongFunction; + +/** + * A functional interface like {@link ToLongFunction} that declares a {@code Throwable}. + * + * @param the type of the first argument to the function + * @param Thrown exception. + * @since 3.11 + */ +@FunctionalInterface +public interface FailableToLongFunction { + + /** + * Applies this function to the given arguments. + * + * @param t the first function argument + * @return the function result + * @throws T Thrown when the function fails. + */ + long applyAsLong(I t) throws T; +} \ No newline at end of file diff --git a/src/test/java/org/apache/commons/lang3/FunctionsTest.java b/src/test/java/org/apache/commons/lang3/FunctionsTest.java index 36ed6ca3513..3fec18e0222 100644 --- a/src/test/java/org/apache/commons/lang3/FunctionsTest.java +++ b/src/test/java/org/apache/commons/lang3/FunctionsTest.java @@ -709,15 +709,6 @@ public void testConstructor() { new Functions(); } - @Test - public void testDoublePredicate() throws Throwable { - FailureOnOddInvocations.invocations = 0; - final Functions.FailableDoublePredicate failablePredicate = t1 -> FailureOnOddInvocations - .testDouble(t1); - assertThrows(SomeException.class, () -> failablePredicate.test(1d)); - failablePredicate.test(1d); - } - @Test public void testFunction() { final IllegalStateException ise = new IllegalStateException(); @@ -880,24 +871,6 @@ public void testGetSupplier() { assertEquals(0, i.intValue()); } - @Test - public void testIntPredicate() throws Throwable { - FailureOnOddInvocations.invocations = 0; - final Functions.FailableIntPredicate failablePredicate = t1 -> FailureOnOddInvocations - .testInt(t1); - assertThrows(SomeException.class, () -> failablePredicate.test(1)); - failablePredicate.test(1); - } - - @Test - public void testLongPredicate() throws Throwable { - FailureOnOddInvocations.invocations = 0; - final Functions.FailableLongPredicate failablePredicate = t1 -> FailureOnOddInvocations - .testLong(t1); - assertThrows(SomeException.class, () -> failablePredicate.test(1l)); - failablePredicate.test(1l); - } - @Test @DisplayName("Test that asPredicate(FailablePredicate) is converted to -> Predicate ") public void testPredicate() { @@ -1020,36 +993,6 @@ public boolean test(String object1, String object2) throws IOException { }; } - /** - * Tests that our failable interface is properly defined to throw any exception. using the top level generic types - * Object and Throwable. - */ - @Test - void testThrows_FailableBooleanSupplier_Object_Throwable() { - new Functions.FailableBooleanSupplier() { - - @Override - public boolean getAsBoolean() throws Throwable { - throw new IOException("test"); - } - }; - } - - /** - * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as - * generic test types. - */ - @Test - void testThrows_FailableBooleanSupplier_String_IOException() { - new Functions.FailableBooleanSupplier() { - - @Override - public boolean getAsBoolean() throws IOException { - throw new IOException("test"); - } - }; - } - /** * Tests that our failable interface is properly defined to throw any exception. using the top level generic types * Object and Throwable. @@ -1112,187 +1055,6 @@ public void accept(String object) throws IOException { }; } - /** - * Tests that our failable interface is properly defined to throw any exception. using the top level generic types - * Object and Throwable. - */ - @Test - void testThrows_FailableDoubleBinaryOperator_Object_Throwable() { - new Functions.FailableDoubleBinaryOperator() { - - @Override - public double applyAsDouble(double left, double right) throws Throwable { - throw new IOException("test"); - } - }; - } - - /** - * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as - * generic test types. - */ - @Test - void testThrows_FailableDoubleBinaryOperator_String_IOException() { - new Functions.FailableDoubleBinaryOperator() { - - @Override - public double applyAsDouble(double left, double right) throws IOException { - throw new IOException("test"); - } - }; - } - - /** - * Tests that our failable interface is properly defined to throw any exception. using the top level generic types - * Object and Throwable. - */ - @Test - void testThrows_FailableDoubleConsumer_Object_Throwable() { - new Functions.FailableDoubleConsumer() { - - @Override - public void accept(double value) throws Throwable { - throw new IOException("test"); - - } - }; - } - - /** - * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as - * generic test types. - */ - @Test - void testThrows_FailableDoubleConsumer_String_IOException() { - new Functions.FailableDoubleConsumer() { - - @Override - public void accept(double value) throws IOException { - throw new IOException("test"); - } - }; - } - - /** - * Tests that our failable interface is properly defined to throw any exception. using the top level generic types - * Object and Throwable. - */ - @Test - void testThrows_FailableDoubleFunction_Object_Throwable() { - new Functions.FailableDoubleFunction() { - - @Override - public Object apply(double input) throws Throwable { - throw new IOException("test"); - } - }; - } - - /** - * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as - * generic test types. - */ - @Test - void testThrows_FailableDoubleFunction_String_IOException() { - new Functions.FailableDoubleFunction() { - - @Override - public String apply(double input) throws IOException { - throw new IOException("test"); - } - }; - } - - /** - * Tests that our failable interface is properly defined to throw any exception. using the top level generic types - * Object and Throwable. - */ - @Test - void testThrows_FailableDoubleSupplier_Object_Throwable() { - new Functions.FailableDoubleSupplier() { - - @Override - public double getAsDouble() throws Throwable { - throw new IOException("test"); - } - }; - } - - /** - * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as - * generic test types. - */ - @Test - void testThrows_FailableDoubleSupplier_String_IOException() { - new Functions.FailableDoubleSupplier() { - - @Override - public double getAsDouble() throws IOException { - throw new IOException("test"); - } - }; - } - - /** - * Tests that our failable interface is properly defined to throw any exception. using the top level generic types - * Object and Throwable. - */ - @Test - void testThrows_FailableDoubleToIntFunction_Object_Throwable() { - new Functions.FailableDoubleToIntFunction() { - - @Override - public int applyAsInt(double value) throws Throwable { - throw new IOException("test"); - } - }; - } - - /** - * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as - * generic test types. - */ - @Test - void testThrows_FailableDoubleToIntFunction_String_IOException() { - new Functions.FailableDoubleToIntFunction() { - - @Override - public int applyAsInt(double value) throws IOException { - throw new IOException("test"); - } - }; - } - - /** - * Tests that our failable interface is properly defined to throw any exception. using the top level generic types - * Object and Throwable. - */ - @Test - void testThrows_FailableDoubleToLongFunction_Object_Throwable() { - new Functions.FailableDoubleToLongFunction() { - - @Override - public int applyAsLong(double value) throws Throwable { - throw new IOException("test"); - } - }; - } - - /** - * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as - * generic test types. - */ - @Test - void testThrows_FailableDoubleToLongFunction_String_IOException() { - new Functions.FailableDoubleToLongFunction() { - - @Override - public int applyAsLong(double value) throws IOException { - throw new IOException("test"); - } - }; - } - /** * Tests that our failable interface is properly defined to throw any exception. using the top level generic types * Object and Throwable. @@ -1328,43 +1090,12 @@ public String apply(String input) throws IOException { * Object and Throwable. */ @Test - void testThrows_FailableIntBinaryOperator_Object_Throwable() { - new Functions.FailableIntBinaryOperator() { - - @Override - public int applyAsInt(int left, int right) throws Throwable { - throw new IOException("test"); - } - }; - } - - /** - * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as - * generic test types. - */ - @Test - void testThrows_FailableIntBinaryOperator_String_IOException() { - new Functions.FailableIntBinaryOperator() { - - @Override - public int applyAsInt(int left, int right) throws IOException { - throw new IOException("test"); - } - }; - } - - /** - * Tests that our failable interface is properly defined to throw any exception. using the top level generic types - * Object and Throwable. - */ - @Test - void testThrows_FailableIntConsumer_Object_Throwable() { - new Functions.FailableIntConsumer() { + void testThrows_FailablePredicate_Object_Throwable() { + new Functions.FailablePredicate() { @Override - public void accept(int value) throws Throwable { + public boolean test(Object object) throws Throwable { throw new IOException("test"); - } }; } @@ -1374,11 +1105,11 @@ public void accept(int value) throws Throwable { * generic test types. */ @Test - void testThrows_FailableIntConsumer_String_IOException() { - new Functions.FailableIntConsumer() { + void testThrows_FailablePredicate_String_IOException() { + new Functions.FailablePredicate() { @Override - public void accept(int value) throws IOException { + public boolean test(String object) throws IOException { throw new IOException("test"); } }; @@ -1389,42 +1120,13 @@ public void accept(int value) throws IOException { * Object and Throwable. */ @Test - void testThrows_FailableIntFunction_Object_Throwable() { - new Functions.FailableIntFunction() { - - @Override - public Object apply(int input) throws Throwable { - throw new IOException("test"); - } - }; - } - - /** - * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as - * generic test types. - */ - @Test - void testThrows_FailableIntFunction_String_IOException() { - new Functions.FailableIntFunction() { + void testThrows_FailableRunnable_Object_Throwable() { + new Functions.FailableRunnable() { @Override - public String apply(int input) throws IOException { + public void run() throws Throwable { throw new IOException("test"); - } - }; - } - - /** - * Tests that our failable interface is properly defined to throw any exception. using the top level generic types - * Object and Throwable. - */ - @Test - void testThrows_FailableIntSupplier_Object_Throwable() { - new Functions.FailableIntSupplier() { - @Override - public int getAsInt() throws Throwable { - throw new IOException("test"); } }; } @@ -1434,11 +1136,11 @@ public int getAsInt() throws Throwable { * generic test types. */ @Test - void testThrows_FailableIntSupplier_String_IOException() { - new Functions.FailableIntSupplier() { + void testThrows_FailableRunnable_String_IOException() { + new Functions.FailableRunnable() { @Override - public int getAsInt() throws IOException { + public void run() throws IOException { throw new IOException("test"); } }; @@ -1449,11 +1151,11 @@ public int getAsInt() throws IOException { * Object and Throwable. */ @Test - void testThrows_FailableIntToDoubleFunction_Object_Throwable() { - new Functions.FailableIntToDoubleFunction() { + void testThrows_FailableSupplier_Object_Throwable() { + new Functions.FailableSupplier() { @Override - public double applyAsDouble(int value) throws Throwable { + public Object get() throws Throwable { throw new IOException("test"); } }; @@ -1464,404 +1166,8 @@ public double applyAsDouble(int value) throws Throwable { * generic test types. */ @Test - void testThrows_FailableIntToDoubleFunction_String_IOException() { - new Functions.FailableIntToDoubleFunction() { - - @Override - public double applyAsDouble(int value) throws IOException { - throw new IOException("test"); - } - }; - } - - /** - * Tests that our failable interface is properly defined to throw any exception. using the top level generic types - * Object and Throwable. - */ - @Test - void testThrows_FailableIntToLongFunction_Object_Throwable() { - new Functions.FailableIntToLongFunction() { - - @Override - public long applyAsLong(int value) throws Throwable { - throw new IOException("test"); - } - }; - } - - /** - * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as - * generic test types. - */ - @Test - void testThrows_FailableIntToLongFunction_String_IOException() { - new Functions.FailableIntToLongFunction() { - - @Override - public long applyAsLong(int value) throws IOException { - throw new IOException("test"); - } - }; - } - - /** - * Tests that our failable interface is properly defined to throw any exception. using the top level generic types - * Object and Throwable. - */ - @Test - void testThrows_FailableLongBinaryOperator_Object_Throwable() { - new Functions.FailableLongBinaryOperator() { - - @Override - public long applyAsLong(long left, long right) throws Throwable { - throw new IOException("test"); - } - }; - } - - /** - * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as - * generic test types. - */ - @Test - void testThrows_FailableLongBinaryOperator_String_IOException() { - new Functions.FailableLongBinaryOperator() { - - @Override - public long applyAsLong(long left, long right) throws IOException { - throw new IOException("test"); - } - }; - } - - /** - * Tests that our failable interface is properly defined to throw any exception. using the top level generic types - * Object and Throwable. - */ - @Test - void testThrows_FailableLongConsumer_Object_Throwable() { - new Functions.FailableLongConsumer() { - - @Override - public void accept(long object) throws Throwable { - throw new IOException("test"); - - } - }; - } - - /** - * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as - * generic test types. - */ - @Test - void testThrows_FailableLongConsumer_String_IOException() { - new Functions.FailableLongConsumer() { - - @Override - public void accept(long object) throws IOException { - throw new IOException("test"); - - } - }; - } - - /** - * Tests that our failable interface is properly defined to throw any exception. using the top level generic types - * Object and Throwable. - */ - @Test - void testThrows_FailableLongFunction_Object_Throwable() { - new Functions.FailableLongFunction() { - - @Override - public Object apply(long input) throws Throwable { - throw new IOException("test"); - } - }; - } - - /** - * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as - * generic test types. - */ - @Test - void testThrows_FailableLongFunction_String_IOException() { - new Functions.FailableLongFunction() { - - @Override - public String apply(long input) throws IOException { - throw new IOException("test"); - } - }; - } - - /** - * Tests that our failable interface is properly defined to throw any exception. using the top level generic types - * Object and Throwable. - */ - @Test - void testThrows_FailableLongSupplier_Object_Throwable() { - new Functions.FailableLongSupplier() { - - @Override - public long getAsLong() throws Throwable { - throw new IOException("test"); - } - }; - } - - /** - * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as - * generic test types. - */ - @Test - void testThrows_FailableLongSupplier_String_IOException() { - new Functions.FailableLongSupplier() { - - @Override - public long getAsLong() throws IOException { - throw new IOException("test"); - } - }; - } - - /** - * Tests that our failable interface is properly defined to throw any exception. using the top level generic types - * Object and Throwable. - */ - @Test - void testThrows_FailableLongToDoubleFunction_Object_Throwable() { - new Functions.FailableLongToDoubleFunction() { - - @Override - public double applyAsDouble(long value) throws Throwable { - throw new IOException("test"); - } - }; - } - - /** - * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as - * generic test types. - */ - @Test - void testThrows_FailableLongToDoubleFunction_String_IOException() { - new Functions.FailableLongToDoubleFunction() { - - @Override - public double applyAsDouble(long value) throws IOException { - throw new IOException("test"); - } - }; - } - - /** - * Tests that our failable interface is properly defined to throw any exception. using the top level generic types - * Object and Throwable. - */ - @Test - void testThrows_FailableLongToIntFunction_Object_Throwable() { - new Functions.FailableLongToIntFunction() { - - @Override - public int applyAsInt(long value) throws Throwable { - throw new IOException("test"); - } - }; - } - - /** - * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as - * generic test types. - */ - @Test - void testThrows_FailableLongToIntFunction_String_IOException() { - new Functions.FailableLongToIntFunction() { - - @Override - public int applyAsInt(long value) throws IOException { - throw new IOException("test"); - } - }; - } - - /** - * Tests that our failable interface is properly defined to throw any exception. using the top level generic types - * Object and Throwable. - */ - @Test - void testThrows_FailableObjDoubleConsumer_Object_Throwable() { - new Functions.FailableObjDoubleConsumer() { - - @Override - public void accept(Object object, double value) throws Throwable { - throw new IOException("test"); - - } - }; - } - - /** - * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as - * generic test types. - */ - @Test - void testThrows_FailableObjDoubleConsumer_String_IOException() { - new Functions.FailableObjDoubleConsumer() { - - @Override - public void accept(String object, double value) throws IOException { - throw new IOException("test"); - } - }; - } - - /** - * Tests that our failable interface is properly defined to throw any exception. using the top level generic types - * Object and Throwable. - */ - @Test - void testThrows_FailableObjIntConsumer_Object_Throwable() { - new Functions.FailableObjIntConsumer() { - - @Override - public void accept(Object object, int value) throws Throwable { - throw new IOException("test"); - - } - }; - } - - /** - * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as - * generic test types. - */ - @Test - void testThrows_FailableObjIntConsumer_String_IOException() { - new Functions.FailableObjIntConsumer() { - - @Override - public void accept(String object, int value) throws IOException { - throw new IOException("test"); - } - }; - } - - /** - * Tests that our failable interface is properly defined to throw any exception. using the top level generic types - * Object and Throwable. - */ - @Test - void testThrows_FailableObjLongConsumer_Object_Throwable() { - new Functions.FailableObjLongConsumer() { - - @Override - public void accept(Object object, long value) throws Throwable { - throw new IOException("test"); - - } - }; - } - - /** - * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as - * generic test types. - */ - @Test - void testThrows_FailableObjLongConsumer_String_IOException() { - new Functions.FailableObjLongConsumer() { - - @Override - public void accept(String object, long value) throws IOException { - throw new IOException("test"); - } - }; - } - - /** - * Tests that our failable interface is properly defined to throw any exception. using the top level generic types - * Object and Throwable. - */ - @Test - void testThrows_FailablePredicate_Object_Throwable() { - new Functions.FailablePredicate() { - - @Override - public boolean test(Object object) throws Throwable { - throw new IOException("test"); - } - }; - } - - /** - * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as - * generic test types. - */ - @Test - void testThrows_FailablePredicate_String_IOException() { - new Functions.FailablePredicate() { - - @Override - public boolean test(String object) throws IOException { - throw new IOException("test"); - } - }; - } - - /** - * Tests that our failable interface is properly defined to throw any exception. using the top level generic types - * Object and Throwable. - */ - @Test - void testThrows_FailableRunnable_Object_Throwable() { - new Functions.FailableRunnable() { - - @Override - public void run() throws Throwable { - throw new IOException("test"); - - } - }; - } - - /** - * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as - * generic test types. - */ - @Test - void testThrows_FailableRunnable_String_IOException() { - new Functions.FailableRunnable() { - - @Override - public void run() throws IOException { - throw new IOException("test"); - } - }; - } - - /** - * Tests that our failable interface is properly defined to throw any exception. using the top level generic types - * Object and Throwable. - */ - @Test - void testThrows_FailableSupplier_Object_Throwable() { - new Functions.FailableSupplier() { - - @Override - public Object get() throws Throwable { - throw new IOException("test"); - } - }; - } - - /** - * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as - * generic test types. - */ - @Test - void testThrows_FailableSupplier_String_IOException() { - new Functions.FailableSupplier() { + void testThrows_FailableSupplier_String_IOException() { + new Functions.FailableSupplier() { @Override public String get() throws IOException { @@ -1870,186 +1176,6 @@ public String get() throws IOException { }; } - /** - * Tests that our failable interface is properly defined to throw any exception. using the top level generic types - * Object and Throwable. - */ - @Test - void testThrows_FailableToDoubleBiFunction_Object_Throwable() { - new Functions.FailableToDoubleBiFunction() { - - @Override - public double applyAsDouble(Object t, Object u) throws Throwable { - throw new IOException("test"); - } - }; - } - - /** - * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as - * generic test types. - */ - @Test - void testThrows_FailableToDoubleBiFunction_String_IOException() { - new Functions.FailableToDoubleBiFunction() { - - @Override - public double applyAsDouble(String t, String u) throws IOException { - throw new IOException("test"); - } - }; - } - - /** - * Tests that our failable interface is properly defined to throw any exception. using the top level generic types - * Object and Throwable. - */ - @Test - void testThrows_FailableToDoubleFunction_Object_Throwable() { - new Functions.FailableToDoubleFunction() { - - @Override - public double applyAsDouble(Object t) throws Throwable { - throw new IOException("test"); - } - }; - } - - /** - * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as - * generic test types. - */ - @Test - void testThrows_FailableToDoubleFunction_String_IOException() { - new Functions.FailableToDoubleFunction() { - - @Override - public double applyAsDouble(String t) throws IOException { - throw new IOException("test"); - } - }; - } - - /** - * Tests that our failable interface is properly defined to throw any exception. using the top level generic types - * Object and Throwable. - */ - @Test - void testThrows_FailableToIntBiFunction_Object_Throwable() { - new Functions.FailableToIntBiFunction() { - - @Override - public int applyAsInt(Object t, Object u) throws Throwable { - throw new IOException("test"); - } - }; - } - - /** - * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as - * generic test types. - */ - @Test - void testThrows_FailableToIntBiFunction_String_IOException() { - new Functions.FailableToIntBiFunction() { - - @Override - public int applyAsInt(String t, String u) throws IOException { - throw new IOException("test"); - } - }; - } - - /** - * Tests that our failable interface is properly defined to throw any exception. using the top level generic types - * Object and Throwable. - */ - @Test - void testThrows_FailableToIntFunction_Object_Throwable() { - new Functions.FailableToIntFunction() { - - @Override - public int applyAsInt(Object t) throws Throwable { - throw new IOException("test"); - } - }; - } - - /** - * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as - * generic test types. - */ - @Test - void testThrows_FailableToIntFunction_String_IOException() { - new Functions.FailableToIntFunction() { - - @Override - public int applyAsInt(String t) throws IOException { - throw new IOException("test"); - } - }; - } - - /** - * Tests that our failable interface is properly defined to throw any exception. using the top level generic types - * Object and Throwable. - */ - @Test - void testThrows_FailableToLongBiFunction_Object_Throwable() { - new Functions.FailableToLongBiFunction() { - - @Override - public long applyAsLong(Object t, Object u) throws Throwable { - throw new IOException("test"); - } - }; - } - - /** - * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as - * generic test types. - */ - @Test - void testThrows_FailableToLongBiFunction_String_IOException() { - new Functions.FailableToLongBiFunction() { - - @Override - public long applyAsLong(String t, String u) throws IOException { - throw new IOException("test"); - } - }; - } - - /** - * Tests that our failable interface is properly defined to throw any exception. using the top level generic types - * Object and Throwable. - */ - @Test - void testThrows_FailableToLongFunction_Object_Throwable() { - new Functions.FailableToLongFunction() { - - @Override - public long applyAsLong(Object t) throws Throwable { - throw new IOException("test"); - } - }; - } - - /** - * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as - * generic test types. - */ - @Test - void testThrows_FailableToLongFunction_String_IOException() { - new Functions.FailableToLongFunction() { - - @Override - public long applyAsLong(String t) throws IOException { - throw new IOException("test"); - } - }; - } - @Test public void testTryWithResources() { final CloseableObject co = new CloseableObject(); diff --git a/src/test/java/org/apache/commons/lang3/function/FailableFunctionsTest.java b/src/test/java/org/apache/commons/lang3/function/FailableFunctionsTest.java new file mode 100644 index 00000000000..c0ce3afc1dd --- /dev/null +++ b/src/test/java/org/apache/commons/lang3/function/FailableFunctionsTest.java @@ -0,0 +1,1804 @@ +/* + * 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.function; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.IOException; +import java.io.UncheckedIOException; +import java.lang.reflect.UndeclaredThrowableException; + +import org.apache.commons.lang3.Functions; +import org.junit.jupiter.api.Test; + +/** + * Tests "failable" interfaces defined in this package. + */ +public class FailableFunctionsTest { + + public static class CloseableObject { + private boolean closed; + + public void close() { + closed = true; + } + + public boolean isClosed() { + return closed; + } + + public void reset() { + closed = false; + } + + public void run(final Throwable pTh) throws Throwable { + if (pTh != null) { + throw pTh; + } + } + } + + public static class FailureOnOddInvocations { + private static int invocations; + + static boolean failingBool() throws SomeException { + throwOnOdd(); + return true; + } + + static boolean testDouble(double value) throws SomeException { + throwOnOdd(); + return true; + } + + static boolean testInt(int value) throws SomeException { + throwOnOdd(); + return true; + } + + static boolean testLong(long value) throws SomeException { + throwOnOdd(); + return true; + } + + private static void throwOnOdd() throws SomeException { + final int i = ++invocations; + if (i % 2 == 1) { + throw new SomeException("Odd Invocation: " + i); + } + } + + FailureOnOddInvocations() throws SomeException { + throwOnOdd(); + } + + boolean getAsBoolean() throws SomeException { + throwOnOdd(); + return true; + } + } + + public static class SomeException extends Exception { + + private static final long serialVersionUID = -4965704778119283411L; + + private Throwable t; + + SomeException(final String message) { + super(message); + } + + public void setThrowable(final Throwable throwable) { + t = throwable; + } + + public void test() throws Throwable { + if (t != null) { + throw t; + } + } + } + + public static class Testable { + private T acceptedObject; + private P acceptedPrimitiveObject1; + private P acceptedPrimitiveObject2; + private Throwable throwable; + + Testable(final Throwable throwable) { + this.throwable = throwable; + } + + public T getAcceptedObject() { + return acceptedObject; + } + + public P getAcceptedPrimitiveObject1() { + return acceptedPrimitiveObject1; + } + + public P getAcceptedPrimitiveObject2() { + return acceptedPrimitiveObject2; + } + + public void setThrowable(final Throwable throwable) { + this.throwable = throwable; + } + + public void test() throws Throwable { + test(throwable); + } + + public Object test(Object input1, Object input2) throws Throwable { + test(throwable); + return acceptedObject; + } + + public void test(final Throwable throwable) throws Throwable { + if (throwable != null) { + throw throwable; + } + } + + public boolean testAsBooleanPrimitive() throws Throwable { + return testAsBooleanPrimitive(throwable); + } + + public boolean testAsBooleanPrimitive(final Throwable throwable) throws Throwable { + if (throwable != null) { + throw throwable; + } + return false; + } + + public double testAsDoublePrimitive() throws Throwable { + return testAsDoublePrimitive(throwable); + } + + public double testAsDoublePrimitive(final Throwable throwable) throws Throwable { + if (throwable != null) { + throw throwable; + } + return 0; + } + + public Integer testAsInteger() throws Throwable { + return testAsInteger(throwable); + } + + public Integer testAsInteger(final Throwable throwable) throws Throwable { + if (throwable != null) { + throw throwable; + } + return 0; + } + + public int testAsIntPrimitive() throws Throwable { + return testAsIntPrimitive(throwable); + } + + public int testAsIntPrimitive(final Throwable throwable) throws Throwable { + if (throwable != null) { + throw throwable; + } + return 0; + } + + public long testAsLongPrimitive() throws Throwable { + return testAsLongPrimitive(throwable); + } + + public long testAsLongPrimitive(final Throwable throwable) throws Throwable { + if (throwable != null) { + throw throwable; + } + return 0; + } + + public void testDouble(double i) throws Throwable { + test(throwable); + acceptedPrimitiveObject1 = (P) ((Double) i); + } + + public double testDoubleDouble(double i, double j) throws Throwable { + test(throwable); + acceptedPrimitiveObject1 = (P) ((Double) i); + acceptedPrimitiveObject2 = (P) ((Double) j); + return 3d; + } + + public void testInt(int i) throws Throwable { + test(throwable); + acceptedPrimitiveObject1 = (P) ((Integer) i); + } + + public void testLong(long i) throws Throwable { + test(throwable); + acceptedPrimitiveObject1 = (P) ((Long) i); + } + + public void testObjDouble(T object, double i) throws Throwable { + test(throwable); + acceptedObject = object; + acceptedPrimitiveObject1 = (P) ((Double) i); + } + + public void testObjInt(T object, int i) throws Throwable { + test(throwable); + acceptedObject = object; + acceptedPrimitiveObject1 = (P) ((Integer) i); + } + + public void testObjLong(T object, long i) throws Throwable { + test(throwable); + acceptedObject = object; + acceptedPrimitiveObject1 = (P) ((Long) i); + } + } + + @Test + public void testAcceptDoubleConsumer() { + final IllegalStateException ise = new IllegalStateException(); + final Testable testable = new Testable<>(ise); + Throwable e = assertThrows(IllegalStateException.class, () -> Functions.accept(testable::testDouble, 1d)); + assertSame(ise, e); + assertNull(testable.getAcceptedPrimitiveObject1()); + + final Error error = new OutOfMemoryError(); + testable.setThrowable(error); + e = assertThrows(OutOfMemoryError.class, () -> Functions.accept(testable::testDouble, 1d)); + assertSame(error, e); + assertNull(testable.getAcceptedPrimitiveObject1()); + + final IOException ioe = new IOException("Unknown I/O error"); + testable.setThrowable(ioe); + e = assertThrows(UncheckedIOException.class, () -> Functions.accept(testable::testDouble, 1d)); + final Throwable t = e.getCause(); + assertNotNull(t); + assertSame(ioe, t); + assertNull(testable.getAcceptedPrimitiveObject1()); + + testable.setThrowable(null); + Functions.accept(testable::testDouble, 1d); + assertEquals(1, testable.getAcceptedPrimitiveObject1()); + } + + @Test + public void testAcceptIntConsumer() { + final IllegalStateException ise = new IllegalStateException(); + final Testable testable = new Testable<>(ise); + Throwable e = assertThrows(IllegalStateException.class, () -> Functions.accept(testable::testInt, 1)); + assertSame(ise, e); + assertNull(testable.getAcceptedPrimitiveObject1()); + + final Error error = new OutOfMemoryError(); + testable.setThrowable(error); + e = assertThrows(OutOfMemoryError.class, () -> Functions.accept(testable::testInt, 1)); + assertSame(error, e); + assertNull(testable.getAcceptedPrimitiveObject1()); + + final IOException ioe = new IOException("Unknown I/O error"); + testable.setThrowable(ioe); + e = assertThrows(UncheckedIOException.class, () -> Functions.accept(testable::testInt, 1)); + final Throwable t = e.getCause(); + assertNotNull(t); + assertSame(ioe, t); + assertNull(testable.getAcceptedPrimitiveObject1()); + + testable.setThrowable(null); + Functions.accept(testable::testInt, 1); + assertEquals(1, testable.getAcceptedPrimitiveObject1()); + } + + @Test + public void testAcceptLongConsumer() { + final IllegalStateException ise = new IllegalStateException(); + final Testable testable = new Testable<>(ise); + Throwable e = assertThrows(IllegalStateException.class, () -> Functions.accept(testable::testLong, 1L)); + assertSame(ise, e); + assertNull(testable.getAcceptedPrimitiveObject1()); + + final Error error = new OutOfMemoryError(); + testable.setThrowable(error); + e = assertThrows(OutOfMemoryError.class, () -> Functions.accept(testable::testLong, 1L)); + assertSame(error, e); + assertNull(testable.getAcceptedPrimitiveObject1()); + + final IOException ioe = new IOException("Unknown I/O error"); + testable.setThrowable(ioe); + e = assertThrows(UncheckedIOException.class, () -> Functions.accept(testable::testLong, 1L)); + final Throwable t = e.getCause(); + assertNotNull(t); + assertSame(ioe, t); + assertNull(testable.getAcceptedPrimitiveObject1()); + + testable.setThrowable(null); + Functions.accept(testable::testLong, 1L); + assertEquals(1, testable.getAcceptedPrimitiveObject1()); + } + + @Test + public void testAcceptObjDoubleConsumer() { + final IllegalStateException ise = new IllegalStateException(); + final Testable testable = new Testable<>(ise); + Throwable e = assertThrows(IllegalStateException.class, + () -> Functions.accept(testable::testObjDouble, "X", 1d)); + assertSame(ise, e); + assertNull(testable.getAcceptedObject()); + assertNull(testable.getAcceptedPrimitiveObject1()); + + final Error error = new OutOfMemoryError(); + testable.setThrowable(error); + e = assertThrows(OutOfMemoryError.class, () -> Functions.accept(testable::testObjDouble, "X", 1d)); + assertSame(error, e); + assertNull(testable.getAcceptedObject()); + assertNull(testable.getAcceptedPrimitiveObject1()); + + final IOException ioe = new IOException("Unknown I/O error"); + testable.setThrowable(ioe); + e = assertThrows(UncheckedIOException.class, () -> Functions.accept(testable::testObjDouble, "X", 1d)); + final Throwable t = e.getCause(); + assertNotNull(t); + assertSame(ioe, t); + assertNull(testable.getAcceptedObject()); + assertNull(testable.getAcceptedPrimitiveObject1()); + + testable.setThrowable(null); + Functions.accept(testable::testObjDouble, "X", 1d); + assertEquals("X", testable.getAcceptedObject()); + assertEquals(1d, testable.getAcceptedPrimitiveObject1()); + } + + @Test + public void testAcceptObjIntConsumer() { + final IllegalStateException ise = new IllegalStateException(); + final Testable testable = new Testable<>(ise); + Throwable e = assertThrows(IllegalStateException.class, () -> Functions.accept(testable::testObjInt, "X", 1)); + assertSame(ise, e); + assertNull(testable.getAcceptedObject()); + assertNull(testable.getAcceptedPrimitiveObject1()); + + final Error error = new OutOfMemoryError(); + testable.setThrowable(error); + e = assertThrows(OutOfMemoryError.class, () -> Functions.accept(testable::testObjInt, "X", 1)); + assertSame(error, e); + assertNull(testable.getAcceptedObject()); + assertNull(testable.getAcceptedPrimitiveObject1()); + + final IOException ioe = new IOException("Unknown I/O error"); + testable.setThrowable(ioe); + e = assertThrows(UncheckedIOException.class, () -> Functions.accept(testable::testObjInt, "X", 1)); + final Throwable t = e.getCause(); + assertNotNull(t); + assertSame(ioe, t); + assertNull(testable.getAcceptedObject()); + assertNull(testable.getAcceptedPrimitiveObject1()); + + testable.setThrowable(null); + Functions.accept(testable::testObjInt, "X", 1); + assertEquals("X", testable.getAcceptedObject()); + assertEquals(1, testable.getAcceptedPrimitiveObject1()); + } + + @Test + public void testAcceptObjLongConsumer() { + final IllegalStateException ise = new IllegalStateException(); + final Testable testable = new Testable<>(ise); + Throwable e = assertThrows(IllegalStateException.class, () -> Functions.accept(testable::testObjLong, "X", 1L)); + assertSame(ise, e); + assertNull(testable.getAcceptedObject()); + assertNull(testable.getAcceptedPrimitiveObject1()); + + final Error error = new OutOfMemoryError(); + testable.setThrowable(error); + e = assertThrows(OutOfMemoryError.class, () -> Functions.accept(testable::testObjLong, "X", 1L)); + assertSame(error, e); + assertNull(testable.getAcceptedObject()); + assertNull(testable.getAcceptedPrimitiveObject1()); + + final IOException ioe = new IOException("Unknown I/O error"); + testable.setThrowable(ioe); + e = assertThrows(UncheckedIOException.class, () -> Functions.accept(testable::testObjLong, "X", 1L)); + final Throwable t = e.getCause(); + assertNotNull(t); + assertSame(ioe, t); + assertNull(testable.getAcceptedObject()); + assertNull(testable.getAcceptedPrimitiveObject1()); + + testable.setThrowable(null); + Functions.accept(testable::testObjLong, "X", 1L); + assertEquals("X", testable.getAcceptedObject()); + assertEquals(1L, testable.getAcceptedPrimitiveObject1()); + } + + @Test + public void testApplyBiFunction() { + final IllegalStateException ise = new IllegalStateException(); + final Testable testable = new Testable<>(null); + Throwable e = assertThrows(IllegalStateException.class, + () -> Functions.apply(Testable::testAsInteger, testable, ise)); + assertSame(ise, e); + + final Error error = new OutOfMemoryError(); + e = assertThrows(OutOfMemoryError.class, () -> Functions.apply(Testable::testAsInteger, testable, error)); + assertSame(error, e); + + final IOException ioe = new IOException("Unknown I/O error"); + e = assertThrows(UncheckedIOException.class, () -> Functions.apply(Testable::testAsInteger, testable, ioe)); + final Throwable t = e.getCause(); + assertNotNull(t); + assertSame(ioe, t); + + final Integer i = Functions.apply(Testable::testAsInteger, testable, (Throwable) null); + assertNotNull(i); + assertEquals(0, i.intValue()); + } + + @Test + public void testApplyDoubleBinaryOperator() { + final IllegalStateException ise = new IllegalStateException(); + final Testable testable = new Testable<>(ise); + Throwable e = assertThrows(IllegalStateException.class, + () -> Functions.applyAsDouble(testable::testDoubleDouble, 1d, 2d)); + assertSame(ise, e); + + final Testable testable2 = new Testable<>(null); + final double i = Functions.applyAsDouble(testable2::testDoubleDouble, 1d, 2d); + assertEquals(3d, i); + } + + @Test + public void testApplyFunction() { + final IllegalStateException ise = new IllegalStateException(); + final Testable testable = new Testable<>(ise); + Throwable e = assertThrows(IllegalStateException.class, + () -> Functions.apply(Testable::testAsInteger, testable)); + assertSame(ise, e); + + final Error error = new OutOfMemoryError(); + testable.setThrowable(error); + e = assertThrows(OutOfMemoryError.class, () -> Functions.apply(Testable::testAsInteger, testable)); + assertSame(error, e); + + final IOException ioe = new IOException("Unknown I/O error"); + testable.setThrowable(ioe); + e = assertThrows(UncheckedIOException.class, () -> Functions.apply(Testable::testAsInteger, testable)); + final Throwable t = e.getCause(); + assertNotNull(t); + assertSame(ioe, t); + + testable.setThrowable(null); + final Integer i = Functions.apply(Testable::testAsInteger, testable); + assertNotNull(i); + assertEquals(0, i.intValue()); + } + + @Test + public void testAsRunnable() { + FailureOnOddInvocations.invocations = 0; + final Runnable runnable = Functions.asRunnable(FailureOnOddInvocations::new); + final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, runnable::run); + final Throwable cause = e.getCause(); + assertNotNull(cause); + assertTrue(cause instanceof SomeException); + assertEquals("Odd Invocation: 1", cause.getMessage()); + + // Even invocations, should not throw an exception + runnable.run(); + } + + @Test + public void testDoublePredicate() throws Throwable { + FailureOnOddInvocations.invocations = 0; + final FailableDoublePredicate failablePredicate = t1 -> FailureOnOddInvocations.testDouble(t1); + assertThrows(SomeException.class, () -> failablePredicate.test(1d)); + failablePredicate.test(1d); + } + + @Test + public void testGetAsBooleanSupplier() { + final IllegalStateException ise = new IllegalStateException(); + final Testable testable = new Testable<>(ise); + Throwable e = assertThrows(IllegalStateException.class, + () -> Functions.getAsBoolean(testable::testAsBooleanPrimitive)); + assertSame(ise, e); + + final Error error = new OutOfMemoryError(); + testable.setThrowable(error); + e = assertThrows(OutOfMemoryError.class, () -> Functions.getAsBoolean(testable::testAsBooleanPrimitive)); + assertSame(error, e); + + final IOException ioe = new IOException("Unknown I/O error"); + testable.setThrowable(ioe); + e = assertThrows(UncheckedIOException.class, () -> Functions.getAsBoolean(testable::testAsBooleanPrimitive)); + final Throwable t = e.getCause(); + assertNotNull(t); + assertSame(ioe, t); + + testable.setThrowable(null); + assertFalse(Functions.getAsBoolean(testable::testAsBooleanPrimitive)); + } + + @Test + public void testGetAsDoubleSupplier() { + final IllegalStateException ise = new IllegalStateException(); + final Testable testable = new Testable<>(ise); + Throwable e = assertThrows(IllegalStateException.class, + () -> Functions.getAsDouble(testable::testAsDoublePrimitive)); + assertSame(ise, e); + + final Error error = new OutOfMemoryError(); + testable.setThrowable(error); + e = assertThrows(OutOfMemoryError.class, () -> Functions.getAsDouble(testable::testAsDoublePrimitive)); + assertSame(error, e); + + final IOException ioe = new IOException("Unknown I/O error"); + testable.setThrowable(ioe); + e = assertThrows(UncheckedIOException.class, () -> Functions.getAsDouble(testable::testAsDoublePrimitive)); + final Throwable t = e.getCause(); + assertNotNull(t); + assertSame(ioe, t); + + testable.setThrowable(null); + assertEquals(0, Functions.getAsDouble(testable::testAsDoublePrimitive)); + } + + @Test + public void testGetAsIntSupplier() { + final IllegalStateException ise = new IllegalStateException(); + final Testable testable = new Testable<>(ise); + Throwable e = assertThrows(IllegalStateException.class, () -> Functions.getAsInt(testable::testAsIntPrimitive)); + assertSame(ise, e); + + final Error error = new OutOfMemoryError(); + testable.setThrowable(error); + e = assertThrows(OutOfMemoryError.class, () -> Functions.getAsInt(testable::testAsIntPrimitive)); + assertSame(error, e); + + final IOException ioe = new IOException("Unknown I/O error"); + testable.setThrowable(ioe); + e = assertThrows(UncheckedIOException.class, () -> Functions.getAsInt(testable::testAsIntPrimitive)); + final Throwable t = e.getCause(); + assertNotNull(t); + assertSame(ioe, t); + + testable.setThrowable(null); + final int i = Functions.getAsInt(testable::testAsInteger); + assertEquals(0, i); + } + + @Test + public void testGetAsLongSupplier() { + final IllegalStateException ise = new IllegalStateException(); + final Testable testable = new Testable<>(ise); + Throwable e = assertThrows(IllegalStateException.class, + () -> Functions.getAsLong(testable::testAsLongPrimitive)); + assertSame(ise, e); + + final Error error = new OutOfMemoryError(); + testable.setThrowable(error); + e = assertThrows(OutOfMemoryError.class, () -> Functions.getAsLong(testable::testAsLongPrimitive)); + assertSame(error, e); + + final IOException ioe = new IOException("Unknown I/O error"); + testable.setThrowable(ioe); + e = assertThrows(UncheckedIOException.class, () -> Functions.getAsLong(testable::testAsLongPrimitive)); + final Throwable t = e.getCause(); + assertNotNull(t); + assertSame(ioe, t); + + testable.setThrowable(null); + final long i = Functions.getAsLong(testable::testAsLongPrimitive); + assertEquals(0, i); + } + + @Test + public void testGetFromSupplier() { + FailureOnOddInvocations.invocations = 0; + final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, + () -> Functions.run(FailureOnOddInvocations::new)); + final Throwable cause = e.getCause(); + assertNotNull(cause); + assertTrue(cause instanceof SomeException); + assertEquals("Odd Invocation: 1", cause.getMessage()); + final FailureOnOddInvocations instance = Functions.call(FailureOnOddInvocations::new); + assertNotNull(instance); + } + + @Test + public void testGetSupplier() { + final IllegalStateException ise = new IllegalStateException(); + final Testable testable = new Testable<>(ise); + Throwable e = assertThrows(IllegalStateException.class, () -> Functions.get(testable::testAsInteger)); + assertSame(ise, e); + + final Error error = new OutOfMemoryError(); + testable.setThrowable(error); + e = assertThrows(OutOfMemoryError.class, () -> Functions.get(testable::testAsInteger)); + assertSame(error, e); + + final IOException ioe = new IOException("Unknown I/O error"); + testable.setThrowable(ioe); + e = assertThrows(UncheckedIOException.class, () -> Functions.get(testable::testAsInteger)); + final Throwable t = e.getCause(); + assertNotNull(t); + assertSame(ioe, t); + + testable.setThrowable(null); + final Integer i = Functions.apply(Testable::testAsInteger, testable); + assertNotNull(i); + assertEquals(0, i.intValue()); + } + + @Test + public void testIntPredicate() throws Throwable { + FailureOnOddInvocations.invocations = 0; + final FailableIntPredicate failablePredicate = t1 -> FailureOnOddInvocations.testInt(t1); + assertThrows(SomeException.class, () -> failablePredicate.test(1)); + failablePredicate.test(1); + } + + @Test + public void testLongPredicate() throws Throwable { + FailureOnOddInvocations.invocations = 0; + final FailableLongPredicate failablePredicate = t1 -> FailureOnOddInvocations.testLong(t1); + assertThrows(SomeException.class, () -> failablePredicate.test(1l)); + failablePredicate.test(1l); + } + + @Test + public void testRunnable() { + FailureOnOddInvocations.invocations = 0; + final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, + () -> Functions.run(FailureOnOddInvocations::new)); + final Throwable cause = e.getCause(); + assertNotNull(cause); + assertTrue(cause instanceof SomeException); + assertEquals("Odd Invocation: 1", cause.getMessage()); + + // Even invocations, should not throw an exception + Functions.run(FailureOnOddInvocations::new); + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + public void testThrows_FailableBiConsumer_Object_Throwable() { + new Functions.FailableBiConsumer() { + + @Override + public void accept(Object object1, Object object2) throws Throwable { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + public void testThrows_FailableBiConsumer_String_IOException() { + new Functions.FailableBiConsumer() { + + @Override + public void accept(String object1, String object2) throws IOException { + throw new IOException("test"); + + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + public void testThrows_FailableBiFunction_Object_Throwable() { + new Functions.FailableBiFunction() { + + @Override + public Object apply(Object input1, Object input2) throws Throwable { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + public void testThrows_FailableBiFunction_String_IOException() { + new Functions.FailableBiFunction() { + + @Override + public String apply(String input1, String input2) throws IOException { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + public void testThrows_FailableBiPredicate_Object_Throwable() { + new Functions.FailableBiPredicate() { + + @Override + public boolean test(Object object1, Object object2) throws Throwable { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + public void testThrows_FailableBiPredicate_String_IOException() { + new Functions.FailableBiPredicate() { + + @Override + public boolean test(String object1, String object2) throws IOException { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + public void testThrows_FailableBooleanSupplier_Object_Throwable() { + new FailableBooleanSupplier() { + + @Override + public boolean getAsBoolean() throws Throwable { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + public void testThrows_FailableBooleanSupplier_String_IOException() { + new FailableBooleanSupplier() { + + @Override + public boolean getAsBoolean() throws IOException { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + public void testThrows_FailableCallable_Object_Throwable() { + new Functions.FailableCallable() { + + @Override + public Object call() throws Throwable { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + public void testThrows_FailableCallable_String_IOException() { + new Functions.FailableCallable() { + + @Override + public String call() throws IOException { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + public void testThrows_FailableConsumer_Object_Throwable() { + new Functions.FailableConsumer() { + + @Override + public void accept(Object object) throws Throwable { + throw new IOException("test"); + + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + public void testThrows_FailableConsumer_String_IOException() { + new Functions.FailableConsumer() { + + @Override + public void accept(String object) throws IOException { + throw new IOException("test"); + + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + public void testThrows_FailableDoubleBinaryOperator_Object_Throwable() { + new FailableDoubleBinaryOperator() { + + @Override + public double applyAsDouble(double left, double right) throws Throwable { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + public void testThrows_FailableDoubleBinaryOperator_String_IOException() { + new FailableDoubleBinaryOperator() { + + @Override + public double applyAsDouble(double left, double right) throws IOException { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + public void testThrows_FailableDoubleConsumer_Object_Throwable() { + new FailableDoubleConsumer() { + + @Override + public void accept(double value) throws Throwable { + throw new IOException("test"); + + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + public void testThrows_FailableDoubleConsumer_String_IOException() { + new FailableDoubleConsumer() { + + @Override + public void accept(double value) throws IOException { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + public void testThrows_FailableDoubleFunction_Object_Throwable() { + new FailableDoubleFunction() { + + @Override + public Object apply(double input) throws Throwable { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + public void testThrows_FailableDoubleFunction_String_IOException() { + new FailableDoubleFunction() { + + @Override + public String apply(double input) throws IOException { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + public void testThrows_FailableDoubleSupplier_Object_Throwable() { + new FailableDoubleSupplier() { + + @Override + public double getAsDouble() throws Throwable { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + public void testThrows_FailableDoubleSupplier_String_IOException() { + new FailableDoubleSupplier() { + + @Override + public double getAsDouble() throws IOException { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + public void testThrows_FailableDoubleToIntFunction_Object_Throwable() { + new FailableDoubleToIntFunction() { + + @Override + public int applyAsInt(double value) throws Throwable { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + public void testThrows_FailableDoubleToIntFunction_String_IOException() { + new FailableDoubleToIntFunction() { + + @Override + public int applyAsInt(double value) throws IOException { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + public void testThrows_FailableDoubleToLongFunction_Object_Throwable() { + new FailableDoubleToLongFunction() { + + @Override + public int applyAsLong(double value) throws Throwable { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + public void testThrows_FailableDoubleToLongFunction_String_IOException() { + new FailableDoubleToLongFunction() { + + @Override + public int applyAsLong(double value) throws IOException { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + public void testThrows_FailableFunction_Object_Throwable() { + new Functions.FailableFunction() { + + @Override + public Object apply(Object input) throws Throwable { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + public void testThrows_FailableFunction_String_IOException() { + new Functions.FailableFunction() { + + @Override + public String apply(String input) throws IOException { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + public void testThrows_FailableIntBinaryOperator_Object_Throwable() { + new FailableIntBinaryOperator() { + + @Override + public int applyAsInt(int left, int right) throws Throwable { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + public void testThrows_FailableIntBinaryOperator_String_IOException() { + new FailableIntBinaryOperator() { + + @Override + public int applyAsInt(int left, int right) throws IOException { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + public void testThrows_FailableIntConsumer_Object_Throwable() { + new FailableIntConsumer() { + + @Override + public void accept(int value) throws Throwable { + throw new IOException("test"); + + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + public void testThrows_FailableIntConsumer_String_IOException() { + new FailableIntConsumer() { + + @Override + public void accept(int value) throws IOException { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + public void testThrows_FailableIntFunction_Object_Throwable() { + new FailableIntFunction() { + + @Override + public Object apply(int input) throws Throwable { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + public void testThrows_FailableIntFunction_String_IOException() { + new FailableIntFunction() { + + @Override + public String apply(int input) throws IOException { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + public void testThrows_FailableIntSupplier_Object_Throwable() { + new FailableIntSupplier() { + + @Override + public int getAsInt() throws Throwable { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + public void testThrows_FailableIntSupplier_String_IOException() { + new FailableIntSupplier() { + + @Override + public int getAsInt() throws IOException { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + public void testThrows_FailableIntToDoubleFunction_Object_Throwable() { + new FailableIntToDoubleFunction() { + + @Override + public double applyAsDouble(int value) throws Throwable { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + public void testThrows_FailableIntToDoubleFunction_String_IOException() { + new FailableIntToDoubleFunction() { + + @Override + public double applyAsDouble(int value) throws IOException { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + public void testThrows_FailableIntToLongFunction_Object_Throwable() { + new FailableIntToLongFunction() { + + @Override + public long applyAsLong(int value) throws Throwable { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + public void testThrows_FailableIntToLongFunction_String_IOException() { + new FailableIntToLongFunction() { + + @Override + public long applyAsLong(int value) throws IOException { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + public void testThrows_FailableLongBinaryOperator_Object_Throwable() { + new FailableLongBinaryOperator() { + + @Override + public long applyAsLong(long left, long right) throws Throwable { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + public void testThrows_FailableLongBinaryOperator_String_IOException() { + new FailableLongBinaryOperator() { + + @Override + public long applyAsLong(long left, long right) throws IOException { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + public void testThrows_FailableLongConsumer_Object_Throwable() { + new FailableLongConsumer() { + + @Override + public void accept(long object) throws Throwable { + throw new IOException("test"); + + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + public void testThrows_FailableLongConsumer_String_IOException() { + new FailableLongConsumer() { + + @Override + public void accept(long object) throws IOException { + throw new IOException("test"); + + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + public void testThrows_FailableLongFunction_Object_Throwable() { + new FailableLongFunction() { + + @Override + public Object apply(long input) throws Throwable { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + public void testThrows_FailableLongFunction_String_IOException() { + new FailableLongFunction() { + + @Override + public String apply(long input) throws IOException { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + public void testThrows_FailableLongSupplier_Object_Throwable() { + new FailableLongSupplier() { + + @Override + public long getAsLong() throws Throwable { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + public void testThrows_FailableLongSupplier_String_IOException() { + new FailableLongSupplier() { + + @Override + public long getAsLong() throws IOException { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + public void testThrows_FailableLongToDoubleFunction_Object_Throwable() { + new FailableLongToDoubleFunction() { + + @Override + public double applyAsDouble(long value) throws Throwable { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + public void testThrows_FailableLongToDoubleFunction_String_IOException() { + new FailableLongToDoubleFunction() { + + @Override + public double applyAsDouble(long value) throws IOException { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + public void testThrows_FailableLongToIntFunction_Object_Throwable() { + new FailableLongToIntFunction() { + + @Override + public int applyAsInt(long value) throws Throwable { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + public void testThrows_FailableLongToIntFunction_String_IOException() { + new FailableLongToIntFunction() { + + @Override + public int applyAsInt(long value) throws IOException { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + public void testThrows_FailableObjDoubleConsumer_Object_Throwable() { + new FailableObjDoubleConsumer() { + + @Override + public void accept(Object object, double value) throws Throwable { + throw new IOException("test"); + + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + public void testThrows_FailableObjDoubleConsumer_String_IOException() { + new FailableObjDoubleConsumer() { + + @Override + public void accept(String object, double value) throws IOException { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + public void testThrows_FailableObjIntConsumer_Object_Throwable() { + new FailableObjIntConsumer() { + + @Override + public void accept(Object object, int value) throws Throwable { + throw new IOException("test"); + + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + public void testThrows_FailableObjIntConsumer_String_IOException() { + new FailableObjIntConsumer() { + + @Override + public void accept(String object, int value) throws IOException { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + public void testThrows_FailableObjLongConsumer_Object_Throwable() { + new FailableObjLongConsumer() { + + @Override + public void accept(Object object, long value) throws Throwable { + throw new IOException("test"); + + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + public void testThrows_FailableObjLongConsumer_String_IOException() { + new FailableObjLongConsumer() { + + @Override + public void accept(String object, long value) throws IOException { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + public void testThrows_FailablePredicate_Object_Throwable() { + new Functions.FailablePredicate() { + + @Override + public boolean test(Object object) throws Throwable { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + public void testThrows_FailablePredicate_String_IOException() { + new Functions.FailablePredicate() { + + @Override + public boolean test(String object) throws IOException { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + public void testThrows_FailableRunnable_Object_Throwable() { + new Functions.FailableRunnable() { + + @Override + public void run() throws Throwable { + throw new IOException("test"); + + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + public void testThrows_FailableRunnable_String_IOException() { + new Functions.FailableRunnable() { + + @Override + public void run() throws IOException { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + public void testThrows_FailableSupplier_Object_Throwable() { + new Functions.FailableSupplier() { + + @Override + public Object get() throws Throwable { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + public void testThrows_FailableSupplier_String_IOException() { + new Functions.FailableSupplier() { + + @Override + public String get() throws IOException { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + public void testThrows_FailableToDoubleBiFunction_Object_Throwable() { + new FailableToDoubleBiFunction() { + + @Override + public double applyAsDouble(Object t, Object u) throws Throwable { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + public void testThrows_FailableToDoubleBiFunction_String_IOException() { + new FailableToDoubleBiFunction() { + + @Override + public double applyAsDouble(String t, String u) throws IOException { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + public void testThrows_FailableToDoubleFunction_Object_Throwable() { + new FailableToDoubleFunction() { + + @Override + public double applyAsDouble(Object t) throws Throwable { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + public void testThrows_FailableToDoubleFunction_String_IOException() { + new FailableToDoubleFunction() { + + @Override + public double applyAsDouble(String t) throws IOException { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + public void testThrows_FailableToIntBiFunction_Object_Throwable() { + new FailableToIntBiFunction() { + + @Override + public int applyAsInt(Object t, Object u) throws Throwable { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + public void testThrows_FailableToIntBiFunction_String_IOException() { + new FailableToIntBiFunction() { + + @Override + public int applyAsInt(String t, String u) throws IOException { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + public void testThrows_FailableToIntFunction_Object_Throwable() { + new FailableToIntFunction() { + + @Override + public int applyAsInt(Object t) throws Throwable { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + public void testThrows_FailableToIntFunction_String_IOException() { + new FailableToIntFunction() { + + @Override + public int applyAsInt(String t) throws IOException { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + public void testThrows_FailableToLongBiFunction_Object_Throwable() { + new FailableToLongBiFunction() { + + @Override + public long applyAsLong(Object t, Object u) throws Throwable { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + public void testThrows_FailableToLongBiFunction_String_IOException() { + new FailableToLongBiFunction() { + + @Override + public long applyAsLong(String t, String u) throws IOException { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception. using the top level generic types + * Object and Throwable. + */ + @Test + public void testThrows_FailableToLongFunction_Object_Throwable() { + new FailableToLongFunction() { + + @Override + public long applyAsLong(Object t) throws Throwable { + throw new IOException("test"); + } + }; + } + + /** + * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as + * generic test types. + */ + @Test + public void testThrows_FailableToLongFunction_String_IOException() { + new FailableToLongFunction() { + + @Override + public long applyAsLong(String t) throws IOException { + throw new IOException("test"); + } + }; + } + +} From 74d8ad5c2c490da71082cbb14cea66a0b3a666ed Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Wed, 17 Jun 2020 16:22:05 -0400 Subject: [PATCH 0156/3230] Add missing @Deprecated. --- src/main/java/org/apache/commons/lang3/ArrayUtils.java | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/main/java/org/apache/commons/lang3/ArrayUtils.java b/src/main/java/org/apache/commons/lang3/ArrayUtils.java index ffd250de48f..8b483d2d07b 100644 --- a/src/main/java/org/apache/commons/lang3/ArrayUtils.java +++ b/src/main/java/org/apache/commons/lang3/ArrayUtils.java @@ -5349,6 +5349,7 @@ public static T[] removeAll(final T[] array, final int... indices) { * @since 3.5 * @deprecated Use {@link #removeAllOccurrences(boolean[], boolean)} */ + @Deprecated public static boolean[] removeAllOccurences(final boolean[] array, final boolean element) { return (boolean[]) removeAll((Object) array, indexesOf(array, element)); } @@ -5369,6 +5370,7 @@ public static boolean[] removeAllOccurences(final boolean[] array, final boolean * @since 3.5 * @deprecated Use {@link #removeAllOccurrences(byte[], byte)} */ + @Deprecated public static byte[] removeAllOccurences(final byte[] array, final byte element) { return (byte[]) removeAll((Object) array, indexesOf(array, element)); } @@ -5389,6 +5391,7 @@ public static byte[] removeAllOccurences(final byte[] array, final byte element) * @since 3.5 * @deprecated Use {@link #removeAllOccurrences(char[], char)} */ + @Deprecated public static char[] removeAllOccurences(final char[] array, final char element) { return (char[]) removeAll((Object) array, indexesOf(array, element)); } @@ -5409,6 +5412,7 @@ public static char[] removeAllOccurences(final char[] array, final char element) * @since 3.5 * @deprecated Use {@link #removeAllOccurrences(double[], double)} */ + @Deprecated public static double[] removeAllOccurences(final double[] array, final double element) { return (double[]) removeAll((Object) array, indexesOf(array, element)); } @@ -5429,6 +5433,7 @@ public static double[] removeAllOccurences(final double[] array, final double el * @since 3.5 * @deprecated Use {@link #removeAllOccurrences(float[], float)} */ + @Deprecated public static float[] removeAllOccurences(final float[] array, final float element) { return (float[]) removeAll((Object) array, indexesOf(array, element)); } @@ -5449,6 +5454,7 @@ public static float[] removeAllOccurences(final float[] array, final float eleme * @since 3.5 * @deprecated Use {@link #removeAllOccurrences(int[], int)} */ + @Deprecated public static int[] removeAllOccurences(final int[] array, final int element) { return (int[]) removeAll((Object) array, indexesOf(array, element)); } @@ -5469,6 +5475,7 @@ public static int[] removeAllOccurences(final int[] array, final int element) { * @since 3.5 * @deprecated Use {@link #removeAllOccurrences(long[], long)} */ + @Deprecated public static long[] removeAllOccurences(final long[] array, final long element) { return (long[]) removeAll((Object) array, indexesOf(array, element)); } @@ -5489,6 +5496,7 @@ public static long[] removeAllOccurences(final long[] array, final long element) * @since 3.5 * @deprecated Use {@link #removeAllOccurrences(short[], short)} */ + @Deprecated public static short[] removeAllOccurences(final short[] array, final short element) { return (short[]) removeAll((Object) array, indexesOf(array, element)); } @@ -5510,6 +5518,7 @@ public static short[] removeAllOccurences(final short[] array, final short eleme * @since 3.5 * @deprecated Use {@link #removeAllOccurrences(Object[], Object)} */ + @Deprecated public static T[] removeAllOccurences(final T[] array, final T element) { return (T[]) removeAll((Object) array, indexesOf(array, element)); } From 5d1a5517c99067a49b85891f194d09bf00ec1006 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Wed, 17 Jun 2020 16:38:47 -0400 Subject: [PATCH 0157/3230] Fix checkstyle: End files in a new line. --- .../function/FailableBooleanSupplier.java | 2 +- .../FailableDoubleBinaryOperator.java | 2 +- .../function/FailableDoubleConsumer.java | 2 +- .../function/FailableDoubleFunction.java | 2 +- .../function/FailableDoublePredicate.java | 2 +- .../function/FailableDoubleSupplier.java | 2 +- .../function/FailableDoubleToIntFunction.java | 2 +- .../FailableDoubleToLongFunction.java | 2 +- .../function/FailableIntBinaryOperator.java | 2 +- .../lang3/function/FailableIntConsumer.java | 2 +- .../lang3/function/FailableIntFunction.java | 2 +- .../lang3/function/FailableIntPredicate.java | 2 +- .../lang3/function/FailableIntSupplier.java | 2 +- .../function/FailableIntToDoubleFunction.java | 2 +- .../function/FailableIntToLongFunction.java | 2 +- .../function/FailableLongBinaryOperator.java | 2 +- .../lang3/function/FailableLongConsumer.java | 2 +- .../lang3/function/FailableLongFunction.java | 2 +- .../lang3/function/FailableLongPredicate.java | 2 +- .../lang3/function/FailableLongSupplier.java | 2 +- .../FailableLongToDoubleFunction.java | 2 +- .../function/FailableLongToIntFunction.java | 2 +- .../function/FailableObjDoubleConsumer.java | 2 +- .../function/FailableObjIntConsumer.java | 2 +- .../function/FailableObjLongConsumer.java | 2 +- .../function/FailableToDoubleBiFunction.java | 2 +- .../function/FailableToDoubleFunction.java | 2 +- .../function/FailableToIntBiFunction.java | 2 +- .../lang3/function/FailableToIntFunction.java | 2 +- .../function/FailableToLongBiFunction.java | 2 +- .../function/FailableToLongFunction.java | 2 +- .../lang3/function/FailableFunctionsTest.java | 611 +++++++++++++----- 32 files changed, 475 insertions(+), 198 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/function/FailableBooleanSupplier.java b/src/main/java/org/apache/commons/lang3/function/FailableBooleanSupplier.java index 0deaef5c3d3..25870de42a0 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableBooleanSupplier.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableBooleanSupplier.java @@ -35,4 +35,4 @@ public interface FailableBooleanSupplier { * @throws T if the supplier fails */ boolean getAsBoolean() throws T; -} \ No newline at end of file +} diff --git a/src/main/java/org/apache/commons/lang3/function/FailableDoubleBinaryOperator.java b/src/main/java/org/apache/commons/lang3/function/FailableDoubleBinaryOperator.java index db58976cda8..19680444b56 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableDoubleBinaryOperator.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableDoubleBinaryOperator.java @@ -37,4 +37,4 @@ public interface FailableDoubleBinaryOperator { * @throws T if the operation fails */ double applyAsDouble(double left, double right) throws T; -} \ No newline at end of file +} diff --git a/src/main/java/org/apache/commons/lang3/function/FailableDoubleConsumer.java b/src/main/java/org/apache/commons/lang3/function/FailableDoubleConsumer.java index ade6e0c1542..63bc40e8bb4 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableDoubleConsumer.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableDoubleConsumer.java @@ -35,4 +35,4 @@ public interface FailableDoubleConsumer { * @throws T Thrown when the consumer fails. */ void accept(double value) throws T; -} \ No newline at end of file +} diff --git a/src/main/java/org/apache/commons/lang3/function/FailableDoubleFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableDoubleFunction.java index 156b204343d..48dec105eec 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableDoubleFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableDoubleFunction.java @@ -37,4 +37,4 @@ public interface FailableDoubleFunction { * @throws T Thrown when the function fails. */ R apply(double input) throws T; -} \ No newline at end of file +} diff --git a/src/main/java/org/apache/commons/lang3/function/FailableDoublePredicate.java b/src/main/java/org/apache/commons/lang3/function/FailableDoublePredicate.java index fda8786ac34..e4bf1630169 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableDoublePredicate.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableDoublePredicate.java @@ -36,4 +36,4 @@ public interface FailableDoublePredicate { * @throws T Thrown when the consumer fails. */ boolean test(double value) throws T; -} \ No newline at end of file +} diff --git a/src/main/java/org/apache/commons/lang3/function/FailableDoubleSupplier.java b/src/main/java/org/apache/commons/lang3/function/FailableDoubleSupplier.java index 9fb751bfed7..47ac1290180 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableDoubleSupplier.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableDoubleSupplier.java @@ -35,4 +35,4 @@ public interface FailableDoubleSupplier { * @throws T if the supplier fails */ double getAsDouble() throws T; -} \ No newline at end of file +} diff --git a/src/main/java/org/apache/commons/lang3/function/FailableDoubleToIntFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableDoubleToIntFunction.java index 00db9f3eeab..403400f8a61 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableDoubleToIntFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableDoubleToIntFunction.java @@ -36,4 +36,4 @@ public interface FailableDoubleToIntFunction { * @throws T Thrown when the function fails. */ int applyAsInt(double value) throws T; -} \ No newline at end of file +} diff --git a/src/main/java/org/apache/commons/lang3/function/FailableDoubleToLongFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableDoubleToLongFunction.java index 0eae76c49e7..71cab0e651a 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableDoubleToLongFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableDoubleToLongFunction.java @@ -36,4 +36,4 @@ public interface FailableDoubleToLongFunction { * @throws T if the operation fails */ int applyAsLong(double value) throws T; -} \ No newline at end of file +} diff --git a/src/main/java/org/apache/commons/lang3/function/FailableIntBinaryOperator.java b/src/main/java/org/apache/commons/lang3/function/FailableIntBinaryOperator.java index 3eaca9dccac..7e41e547b80 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableIntBinaryOperator.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableIntBinaryOperator.java @@ -37,4 +37,4 @@ public interface FailableIntBinaryOperator { * @throws T if the operation fails */ int applyAsInt(int left, int right) throws T; -} \ No newline at end of file +} diff --git a/src/main/java/org/apache/commons/lang3/function/FailableIntConsumer.java b/src/main/java/org/apache/commons/lang3/function/FailableIntConsumer.java index 54e77104814..e7ce74c6248 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableIntConsumer.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableIntConsumer.java @@ -35,4 +35,4 @@ public interface FailableIntConsumer { * @throws T Thrown when the consumer fails. */ void accept(int value) throws T; -} \ No newline at end of file +} diff --git a/src/main/java/org/apache/commons/lang3/function/FailableIntFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableIntFunction.java index 07e35c63db7..907f0983810 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableIntFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableIntFunction.java @@ -37,4 +37,4 @@ public interface FailableIntFunction { * @throws T Thrown when the function fails. */ R apply(int input) throws T; -} \ No newline at end of file +} diff --git a/src/main/java/org/apache/commons/lang3/function/FailableIntPredicate.java b/src/main/java/org/apache/commons/lang3/function/FailableIntPredicate.java index 40e3877f295..3687f9c77c7 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableIntPredicate.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableIntPredicate.java @@ -36,4 +36,4 @@ public interface FailableIntPredicate { * @throws T Thrown when the consumer fails. */ boolean test(int value) throws T; -} \ No newline at end of file +} diff --git a/src/main/java/org/apache/commons/lang3/function/FailableIntSupplier.java b/src/main/java/org/apache/commons/lang3/function/FailableIntSupplier.java index fed9cd23ad0..f1f72e47c00 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableIntSupplier.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableIntSupplier.java @@ -35,4 +35,4 @@ public interface FailableIntSupplier { * @throws T if the supplier fails */ int getAsInt() throws T; -} \ No newline at end of file +} diff --git a/src/main/java/org/apache/commons/lang3/function/FailableIntToDoubleFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableIntToDoubleFunction.java index f0d916435ce..51a81ac056d 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableIntToDoubleFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableIntToDoubleFunction.java @@ -36,4 +36,4 @@ public interface FailableIntToDoubleFunction { * @throws T Thrown when the function fails. */ double applyAsDouble(int value) throws T; -} \ No newline at end of file +} diff --git a/src/main/java/org/apache/commons/lang3/function/FailableIntToLongFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableIntToLongFunction.java index f88d5ef51af..aef8c574164 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableIntToLongFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableIntToLongFunction.java @@ -36,4 +36,4 @@ public interface FailableIntToLongFunction { * @throws T Thrown when the function fails. */ long applyAsLong(int value) throws T; -} \ No newline at end of file +} diff --git a/src/main/java/org/apache/commons/lang3/function/FailableLongBinaryOperator.java b/src/main/java/org/apache/commons/lang3/function/FailableLongBinaryOperator.java index e58acf4437d..6ddf2abd4e7 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableLongBinaryOperator.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableLongBinaryOperator.java @@ -37,4 +37,4 @@ public interface FailableLongBinaryOperator { * @throws T if the operation fails */ long applyAsLong(long left, long right) throws T; -} \ No newline at end of file +} diff --git a/src/main/java/org/apache/commons/lang3/function/FailableLongConsumer.java b/src/main/java/org/apache/commons/lang3/function/FailableLongConsumer.java index 7eb784f7c04..465112ecb00 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableLongConsumer.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableLongConsumer.java @@ -35,4 +35,4 @@ public interface FailableLongConsumer { * @throws T Thrown when the consumer fails. */ void accept(long object) throws T; -} \ No newline at end of file +} diff --git a/src/main/java/org/apache/commons/lang3/function/FailableLongFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableLongFunction.java index 904f9466269..b36b2720c25 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableLongFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableLongFunction.java @@ -37,4 +37,4 @@ public interface FailableLongFunction { * @throws T Thrown when the function fails. */ R apply(long input) throws T; -} \ No newline at end of file +} diff --git a/src/main/java/org/apache/commons/lang3/function/FailableLongPredicate.java b/src/main/java/org/apache/commons/lang3/function/FailableLongPredicate.java index 259b82ea6da..32550822dfa 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableLongPredicate.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableLongPredicate.java @@ -36,4 +36,4 @@ public interface FailableLongPredicate { * @throws T Thrown when the consumer fails. */ boolean test(long value) throws T; -} \ No newline at end of file +} diff --git a/src/main/java/org/apache/commons/lang3/function/FailableLongSupplier.java b/src/main/java/org/apache/commons/lang3/function/FailableLongSupplier.java index 67a1aa43078..31d42a24e02 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableLongSupplier.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableLongSupplier.java @@ -35,4 +35,4 @@ public interface FailableLongSupplier { * @throws T if the supplier fails */ long getAsLong() throws T; -} \ No newline at end of file +} diff --git a/src/main/java/org/apache/commons/lang3/function/FailableLongToDoubleFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableLongToDoubleFunction.java index dcd64eca45b..f83d6a29c56 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableLongToDoubleFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableLongToDoubleFunction.java @@ -36,4 +36,4 @@ public interface FailableLongToDoubleFunction { * @throws T Thrown when the function fails. */ double applyAsDouble(long value) throws T; -} \ No newline at end of file +} diff --git a/src/main/java/org/apache/commons/lang3/function/FailableLongToIntFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableLongToIntFunction.java index 80cb6ae90d7..825491e26b4 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableLongToIntFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableLongToIntFunction.java @@ -36,4 +36,4 @@ public interface FailableLongToIntFunction { * @throws T Thrown when the function fails. */ int applyAsInt(long value) throws T; -} \ No newline at end of file +} diff --git a/src/main/java/org/apache/commons/lang3/function/FailableObjDoubleConsumer.java b/src/main/java/org/apache/commons/lang3/function/FailableObjDoubleConsumer.java index a18d3f31025..70555d5b0de 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableObjDoubleConsumer.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableObjDoubleConsumer.java @@ -37,4 +37,4 @@ public interface FailableObjDoubleConsumer { * @throws T Thrown when the consumer fails. */ void accept(O object, double value) throws T; -} \ No newline at end of file +} diff --git a/src/main/java/org/apache/commons/lang3/function/FailableObjIntConsumer.java b/src/main/java/org/apache/commons/lang3/function/FailableObjIntConsumer.java index 21bf5cda98f..68954a4df35 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableObjIntConsumer.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableObjIntConsumer.java @@ -37,4 +37,4 @@ public interface FailableObjIntConsumer { * @throws T Thrown when the consumer fails. */ void accept(O object, int value) throws T; -} \ No newline at end of file +} diff --git a/src/main/java/org/apache/commons/lang3/function/FailableObjLongConsumer.java b/src/main/java/org/apache/commons/lang3/function/FailableObjLongConsumer.java index 32c42563b36..a503f5ee25b 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableObjLongConsumer.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableObjLongConsumer.java @@ -37,4 +37,4 @@ public interface FailableObjLongConsumer { * @throws T Thrown when the consumer fails. */ void accept(O object, long value) throws T; -} \ No newline at end of file +} diff --git a/src/main/java/org/apache/commons/lang3/function/FailableToDoubleBiFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableToDoubleBiFunction.java index de932f46882..766383b9ad8 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableToDoubleBiFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableToDoubleBiFunction.java @@ -39,4 +39,4 @@ public interface FailableToDoubleBiFunction { * @throws T Thrown when the function fails. */ double applyAsDouble(O1 t, O2 u) throws T; -} \ No newline at end of file +} diff --git a/src/main/java/org/apache/commons/lang3/function/FailableToDoubleFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableToDoubleFunction.java index 1edc934ba3e..9e3fedd8a05 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableToDoubleFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableToDoubleFunction.java @@ -37,4 +37,4 @@ public interface FailableToDoubleFunction { * @throws T Thrown when the function fails. */ double applyAsDouble(I t) throws T; -} \ No newline at end of file +} diff --git a/src/main/java/org/apache/commons/lang3/function/FailableToIntBiFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableToIntBiFunction.java index 126a80c5d4d..7430a09c6e4 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableToIntBiFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableToIntBiFunction.java @@ -39,4 +39,4 @@ public interface FailableToIntBiFunction { * @throws T Thrown when the function fails. */ int applyAsInt(O1 t, O2 u) throws T; -} \ No newline at end of file +} diff --git a/src/main/java/org/apache/commons/lang3/function/FailableToIntFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableToIntFunction.java index 27c2dae09ea..0fc91ade3f4 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableToIntFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableToIntFunction.java @@ -37,4 +37,4 @@ public interface FailableToIntFunction { * @throws T Thrown when the function fails. */ int applyAsInt(I t) throws T; -} \ No newline at end of file +} diff --git a/src/main/java/org/apache/commons/lang3/function/FailableToLongBiFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableToLongBiFunction.java index dcf2fcae424..6a34026a8a8 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableToLongBiFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableToLongBiFunction.java @@ -39,4 +39,4 @@ public interface FailableToLongBiFunction { * @throws T Thrown when the function fails. */ long applyAsLong(O1 t, O2 u) throws T; -} \ No newline at end of file +} diff --git a/src/main/java/org/apache/commons/lang3/function/FailableToLongFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableToLongFunction.java index 999541134c6..f46bbcc1532 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableToLongFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableToLongFunction.java @@ -37,4 +37,4 @@ public interface FailableToLongFunction { * @throws T Thrown when the function fails. */ long applyAsLong(I t) throws T; -} \ No newline at end of file +} diff --git a/src/test/java/org/apache/commons/lang3/function/FailableFunctionsTest.java b/src/test/java/org/apache/commons/lang3/function/FailableFunctionsTest.java index c0ce3afc1dd..468c5a48b8d 100644 --- a/src/test/java/org/apache/commons/lang3/function/FailableFunctionsTest.java +++ b/src/test/java/org/apache/commons/lang3/function/FailableFunctionsTest.java @@ -27,8 +27,17 @@ import java.io.IOException; import java.io.UncheckedIOException; import java.lang.reflect.UndeclaredThrowableException; +import java.util.concurrent.Callable; +import java.util.function.BiConsumer; +import java.util.function.BiFunction; +import java.util.function.BiPredicate; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.function.Supplier; import org.apache.commons.lang3.Functions; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; /** @@ -66,17 +75,17 @@ static boolean failingBool() throws SomeException { return true; } - static boolean testDouble(double value) throws SomeException { + static boolean testDouble(final double value) throws SomeException { throwOnOdd(); return true; } - static boolean testInt(int value) throws SomeException { + static boolean testInt(final int value) throws SomeException { throwOnOdd(); return true; } - static boolean testLong(long value) throws SomeException { + static boolean testLong(final long value) throws SomeException { throwOnOdd(); return true; } @@ -149,7 +158,7 @@ public void test() throws Throwable { test(throwable); } - public Object test(Object input1, Object input2) throws Throwable { + public Object test(final Object input1, final Object input2) throws Throwable { test(throwable); return acceptedObject; } @@ -215,41 +224,41 @@ public long testAsLongPrimitive(final Throwable throwable) throws Throwable { return 0; } - public void testDouble(double i) throws Throwable { + public void testDouble(final double i) throws Throwable { test(throwable); acceptedPrimitiveObject1 = (P) ((Double) i); } - public double testDoubleDouble(double i, double j) throws Throwable { + public double testDoubleDouble(final double i, final double j) throws Throwable { test(throwable); acceptedPrimitiveObject1 = (P) ((Double) i); acceptedPrimitiveObject2 = (P) ((Double) j); return 3d; } - public void testInt(int i) throws Throwable { + public void testInt(final int i) throws Throwable { test(throwable); acceptedPrimitiveObject1 = (P) ((Integer) i); } - public void testLong(long i) throws Throwable { + public void testLong(final long i) throws Throwable { test(throwable); acceptedPrimitiveObject1 = (P) ((Long) i); } - public void testObjDouble(T object, double i) throws Throwable { + public void testObjDouble(final T object, final double i) throws Throwable { test(throwable); acceptedObject = object; acceptedPrimitiveObject1 = (P) ((Double) i); } - public void testObjInt(T object, int i) throws Throwable { + public void testObjInt(final T object, final int i) throws Throwable { test(throwable); acceptedObject = object; acceptedPrimitiveObject1 = (P) ((Integer) i); } - public void testObjLong(T object, long i) throws Throwable { + public void testObjLong(final T object, final long i) throws Throwable { test(throwable); acceptedObject = object; acceptedPrimitiveObject1 = (P) ((Long) i); @@ -257,106 +266,151 @@ public void testObjLong(T object, long i) throws Throwable { } @Test - public void testAcceptDoubleConsumer() { + void testAcceptBiConsumer() { + final IllegalStateException ise = new IllegalStateException(); + final Testable testable = new Testable<>(null); + Throwable e = assertThrows(IllegalStateException.class, () -> Failable.accept(Testable::test, testable, ise)); + assertSame(ise, e); + + final Error error = new OutOfMemoryError(); + e = assertThrows(OutOfMemoryError.class, () -> Failable.accept(Testable::test, testable, error)); + assertSame(error, e); + + final IOException ioe = new IOException("Unknown I/O error"); + testable.setThrowable(ioe); + e = assertThrows(UncheckedIOException.class, () -> Failable.accept(Testable::test, testable, ioe)); + final Throwable t = e.getCause(); + assertNotNull(t); + assertSame(ioe, t); + + testable.setThrowable(null); + Failable.accept(Testable::test, testable, (Throwable) null); + } + + @Test + void testAcceptConsumer() { + final IllegalStateException ise = new IllegalStateException(); + final Testable testable = new Testable<>(ise); + Throwable e = assertThrows(IllegalStateException.class, () -> Failable.accept(Testable::test, testable)); + assertSame(ise, e); + + final Error error = new OutOfMemoryError(); + testable.setThrowable(error); + e = assertThrows(OutOfMemoryError.class, () -> Failable.accept(Testable::test, testable)); + assertSame(error, e); + + final IOException ioe = new IOException("Unknown I/O error"); + testable.setThrowable(ioe); + e = assertThrows(UncheckedIOException.class, () -> Failable.accept(Testable::test, testable)); + final Throwable t = e.getCause(); + assertNotNull(t); + assertSame(ioe, t); + + testable.setThrowable(null); + Failable.accept(Testable::test, testable); + } + + @Test + void testAcceptDoubleConsumer() { final IllegalStateException ise = new IllegalStateException(); final Testable testable = new Testable<>(ise); - Throwable e = assertThrows(IllegalStateException.class, () -> Functions.accept(testable::testDouble, 1d)); + Throwable e = assertThrows(IllegalStateException.class, () -> Failable.accept(testable::testDouble, 1d)); assertSame(ise, e); assertNull(testable.getAcceptedPrimitiveObject1()); final Error error = new OutOfMemoryError(); testable.setThrowable(error); - e = assertThrows(OutOfMemoryError.class, () -> Functions.accept(testable::testDouble, 1d)); + e = assertThrows(OutOfMemoryError.class, () -> Failable.accept(testable::testDouble, 1d)); assertSame(error, e); assertNull(testable.getAcceptedPrimitiveObject1()); final IOException ioe = new IOException("Unknown I/O error"); testable.setThrowable(ioe); - e = assertThrows(UncheckedIOException.class, () -> Functions.accept(testable::testDouble, 1d)); + e = assertThrows(UncheckedIOException.class, () -> Failable.accept(testable::testDouble, 1d)); final Throwable t = e.getCause(); assertNotNull(t); assertSame(ioe, t); assertNull(testable.getAcceptedPrimitiveObject1()); testable.setThrowable(null); - Functions.accept(testable::testDouble, 1d); + Failable.accept(testable::testDouble, 1d); assertEquals(1, testable.getAcceptedPrimitiveObject1()); } @Test - public void testAcceptIntConsumer() { + void testAcceptIntConsumer() { final IllegalStateException ise = new IllegalStateException(); final Testable testable = new Testable<>(ise); - Throwable e = assertThrows(IllegalStateException.class, () -> Functions.accept(testable::testInt, 1)); + Throwable e = assertThrows(IllegalStateException.class, () -> Failable.accept(testable::testInt, 1)); assertSame(ise, e); assertNull(testable.getAcceptedPrimitiveObject1()); final Error error = new OutOfMemoryError(); testable.setThrowable(error); - e = assertThrows(OutOfMemoryError.class, () -> Functions.accept(testable::testInt, 1)); + e = assertThrows(OutOfMemoryError.class, () -> Failable.accept(testable::testInt, 1)); assertSame(error, e); assertNull(testable.getAcceptedPrimitiveObject1()); final IOException ioe = new IOException("Unknown I/O error"); testable.setThrowable(ioe); - e = assertThrows(UncheckedIOException.class, () -> Functions.accept(testable::testInt, 1)); + e = assertThrows(UncheckedIOException.class, () -> Failable.accept(testable::testInt, 1)); final Throwable t = e.getCause(); assertNotNull(t); assertSame(ioe, t); assertNull(testable.getAcceptedPrimitiveObject1()); testable.setThrowable(null); - Functions.accept(testable::testInt, 1); + Failable.accept(testable::testInt, 1); assertEquals(1, testable.getAcceptedPrimitiveObject1()); } @Test - public void testAcceptLongConsumer() { + void testAcceptLongConsumer() { final IllegalStateException ise = new IllegalStateException(); final Testable testable = new Testable<>(ise); - Throwable e = assertThrows(IllegalStateException.class, () -> Functions.accept(testable::testLong, 1L)); + Throwable e = assertThrows(IllegalStateException.class, () -> Failable.accept(testable::testLong, 1L)); assertSame(ise, e); assertNull(testable.getAcceptedPrimitiveObject1()); final Error error = new OutOfMemoryError(); testable.setThrowable(error); - e = assertThrows(OutOfMemoryError.class, () -> Functions.accept(testable::testLong, 1L)); + e = assertThrows(OutOfMemoryError.class, () -> Failable.accept(testable::testLong, 1L)); assertSame(error, e); assertNull(testable.getAcceptedPrimitiveObject1()); final IOException ioe = new IOException("Unknown I/O error"); testable.setThrowable(ioe); - e = assertThrows(UncheckedIOException.class, () -> Functions.accept(testable::testLong, 1L)); + e = assertThrows(UncheckedIOException.class, () -> Failable.accept(testable::testLong, 1L)); final Throwable t = e.getCause(); assertNotNull(t); assertSame(ioe, t); assertNull(testable.getAcceptedPrimitiveObject1()); testable.setThrowable(null); - Functions.accept(testable::testLong, 1L); + Failable.accept(testable::testLong, 1L); assertEquals(1, testable.getAcceptedPrimitiveObject1()); } @Test - public void testAcceptObjDoubleConsumer() { + void testAcceptObjDoubleConsumer() { final IllegalStateException ise = new IllegalStateException(); final Testable testable = new Testable<>(ise); Throwable e = assertThrows(IllegalStateException.class, - () -> Functions.accept(testable::testObjDouble, "X", 1d)); + () -> Failable.accept(testable::testObjDouble, "X", 1d)); assertSame(ise, e); assertNull(testable.getAcceptedObject()); assertNull(testable.getAcceptedPrimitiveObject1()); final Error error = new OutOfMemoryError(); testable.setThrowable(error); - e = assertThrows(OutOfMemoryError.class, () -> Functions.accept(testable::testObjDouble, "X", 1d)); + e = assertThrows(OutOfMemoryError.class, () -> Failable.accept(testable::testObjDouble, "X", 1d)); assertSame(error, e); assertNull(testable.getAcceptedObject()); assertNull(testable.getAcceptedPrimitiveObject1()); final IOException ioe = new IOException("Unknown I/O error"); testable.setThrowable(ioe); - e = assertThrows(UncheckedIOException.class, () -> Functions.accept(testable::testObjDouble, "X", 1d)); + e = assertThrows(UncheckedIOException.class, () -> Failable.accept(testable::testObjDouble, "X", 1d)); final Throwable t = e.getCause(); assertNotNull(t); assertSame(ioe, t); @@ -364,30 +418,30 @@ public void testAcceptObjDoubleConsumer() { assertNull(testable.getAcceptedPrimitiveObject1()); testable.setThrowable(null); - Functions.accept(testable::testObjDouble, "X", 1d); + Failable.accept(testable::testObjDouble, "X", 1d); assertEquals("X", testable.getAcceptedObject()); assertEquals(1d, testable.getAcceptedPrimitiveObject1()); } @Test - public void testAcceptObjIntConsumer() { + void testAcceptObjIntConsumer() { final IllegalStateException ise = new IllegalStateException(); final Testable testable = new Testable<>(ise); - Throwable e = assertThrows(IllegalStateException.class, () -> Functions.accept(testable::testObjInt, "X", 1)); + Throwable e = assertThrows(IllegalStateException.class, () -> Failable.accept(testable::testObjInt, "X", 1)); assertSame(ise, e); assertNull(testable.getAcceptedObject()); assertNull(testable.getAcceptedPrimitiveObject1()); final Error error = new OutOfMemoryError(); testable.setThrowable(error); - e = assertThrows(OutOfMemoryError.class, () -> Functions.accept(testable::testObjInt, "X", 1)); + e = assertThrows(OutOfMemoryError.class, () -> Failable.accept(testable::testObjInt, "X", 1)); assertSame(error, e); assertNull(testable.getAcceptedObject()); assertNull(testable.getAcceptedPrimitiveObject1()); final IOException ioe = new IOException("Unknown I/O error"); testable.setThrowable(ioe); - e = assertThrows(UncheckedIOException.class, () -> Functions.accept(testable::testObjInt, "X", 1)); + e = assertThrows(UncheckedIOException.class, () -> Failable.accept(testable::testObjInt, "X", 1)); final Throwable t = e.getCause(); assertNotNull(t); assertSame(ioe, t); @@ -395,30 +449,30 @@ public void testAcceptObjIntConsumer() { assertNull(testable.getAcceptedPrimitiveObject1()); testable.setThrowable(null); - Functions.accept(testable::testObjInt, "X", 1); + Failable.accept(testable::testObjInt, "X", 1); assertEquals("X", testable.getAcceptedObject()); assertEquals(1, testable.getAcceptedPrimitiveObject1()); } @Test - public void testAcceptObjLongConsumer() { + void testAcceptObjLongConsumer() { final IllegalStateException ise = new IllegalStateException(); final Testable testable = new Testable<>(ise); - Throwable e = assertThrows(IllegalStateException.class, () -> Functions.accept(testable::testObjLong, "X", 1L)); + Throwable e = assertThrows(IllegalStateException.class, () -> Failable.accept(testable::testObjLong, "X", 1L)); assertSame(ise, e); assertNull(testable.getAcceptedObject()); assertNull(testable.getAcceptedPrimitiveObject1()); final Error error = new OutOfMemoryError(); testable.setThrowable(error); - e = assertThrows(OutOfMemoryError.class, () -> Functions.accept(testable::testObjLong, "X", 1L)); + e = assertThrows(OutOfMemoryError.class, () -> Failable.accept(testable::testObjLong, "X", 1L)); assertSame(error, e); assertNull(testable.getAcceptedObject()); assertNull(testable.getAcceptedPrimitiveObject1()); final IOException ioe = new IOException("Unknown I/O error"); testable.setThrowable(ioe); - e = assertThrows(UncheckedIOException.class, () -> Functions.accept(testable::testObjLong, "X", 1L)); + e = assertThrows(UncheckedIOException.class, () -> Failable.accept(testable::testObjLong, "X", 1L)); final Throwable t = e.getCause(); assertNotNull(t); assertSame(ioe, t); @@ -426,7 +480,7 @@ public void testAcceptObjLongConsumer() { assertNull(testable.getAcceptedPrimitiveObject1()); testable.setThrowable(null); - Functions.accept(testable::testObjLong, "X", 1L); + Failable.accept(testable::testObjLong, "X", 1L); assertEquals("X", testable.getAcceptedObject()); assertEquals(1L, testable.getAcceptedPrimitiveObject1()); } @@ -436,20 +490,20 @@ public void testApplyBiFunction() { final IllegalStateException ise = new IllegalStateException(); final Testable testable = new Testable<>(null); Throwable e = assertThrows(IllegalStateException.class, - () -> Functions.apply(Testable::testAsInteger, testable, ise)); + () -> Failable.apply(Testable::testAsInteger, testable, ise)); assertSame(ise, e); final Error error = new OutOfMemoryError(); - e = assertThrows(OutOfMemoryError.class, () -> Functions.apply(Testable::testAsInteger, testable, error)); + e = assertThrows(OutOfMemoryError.class, () -> Failable.apply(Testable::testAsInteger, testable, error)); assertSame(error, e); final IOException ioe = new IOException("Unknown I/O error"); - e = assertThrows(UncheckedIOException.class, () -> Functions.apply(Testable::testAsInteger, testable, ioe)); + e = assertThrows(UncheckedIOException.class, () -> Failable.apply(Testable::testAsInteger, testable, ioe)); final Throwable t = e.getCause(); assertNotNull(t); assertSame(ioe, t); - final Integer i = Functions.apply(Testable::testAsInteger, testable, (Throwable) null); + final Integer i = Failable.apply(Testable::testAsInteger, testable, (Throwable) null); assertNotNull(i); assertEquals(0, i.intValue()); } @@ -458,12 +512,12 @@ public void testApplyBiFunction() { public void testApplyDoubleBinaryOperator() { final IllegalStateException ise = new IllegalStateException(); final Testable testable = new Testable<>(ise); - Throwable e = assertThrows(IllegalStateException.class, - () -> Functions.applyAsDouble(testable::testDoubleDouble, 1d, 2d)); + final Throwable e = assertThrows(IllegalStateException.class, + () -> Failable.applyAsDouble(testable::testDoubleDouble, 1d, 2d)); assertSame(ise, e); final Testable testable2 = new Testable<>(null); - final double i = Functions.applyAsDouble(testable2::testDoubleDouble, 1d, 2d); + final double i = Failable.applyAsDouble(testable2::testDoubleDouble, 1d, 2d); assertEquals(3d, i); } @@ -472,31 +526,74 @@ public void testApplyFunction() { final IllegalStateException ise = new IllegalStateException(); final Testable testable = new Testable<>(ise); Throwable e = assertThrows(IllegalStateException.class, - () -> Functions.apply(Testable::testAsInteger, testable)); + () -> Failable.apply(Testable::testAsInteger, testable)); assertSame(ise, e); final Error error = new OutOfMemoryError(); testable.setThrowable(error); - e = assertThrows(OutOfMemoryError.class, () -> Functions.apply(Testable::testAsInteger, testable)); + e = assertThrows(OutOfMemoryError.class, () -> Failable.apply(Testable::testAsInteger, testable)); assertSame(error, e); final IOException ioe = new IOException("Unknown I/O error"); testable.setThrowable(ioe); - e = assertThrows(UncheckedIOException.class, () -> Functions.apply(Testable::testAsInteger, testable)); + e = assertThrows(UncheckedIOException.class, () -> Failable.apply(Testable::testAsInteger, testable)); final Throwable t = e.getCause(); assertNotNull(t); assertSame(ioe, t); testable.setThrowable(null); - final Integer i = Functions.apply(Testable::testAsInteger, testable); + final Integer i = Failable.apply(Testable::testAsInteger, testable); assertNotNull(i); assertEquals(0, i.intValue()); } @Test - public void testAsRunnable() { + void testAsCallable() { + FailureOnOddInvocations.invocations = 0; + final FailableCallable failableCallable = FailureOnOddInvocations::new; + final Callable callable = Failable.asCallable(failableCallable); + final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, callable::call); + final Throwable cause = e.getCause(); + assertNotNull(cause); + assertTrue(cause instanceof SomeException); + assertEquals("Odd Invocation: 1", cause.getMessage()); + final FailureOnOddInvocations instance; + try { + instance = callable.call(); + } catch (final Exception ex) { + throw Failable.rethrow(ex); + } + assertNotNull(instance); + } + + @Test + void testAsConsumer() { + final IllegalStateException ise = new IllegalStateException(); + final Testable testable = new Testable<>(ise); + final Consumer> consumer = Failable.asConsumer(Testable::test); + Throwable e = assertThrows(IllegalStateException.class, () -> consumer.accept(testable)); + assertSame(ise, e); + + final Error error = new OutOfMemoryError(); + testable.setThrowable(error); + e = assertThrows(OutOfMemoryError.class, () -> consumer.accept(testable)); + assertSame(error, e); + + final IOException ioe = new IOException("Unknown I/O error"); + testable.setThrowable(ioe); + e = assertThrows(UncheckedIOException.class, () -> consumer.accept(testable)); + final Throwable t = e.getCause(); + assertNotNull(t); + assertSame(ioe, t); + + testable.setThrowable(null); + Failable.accept(Testable::test, testable); + } + + @Test + void testAsRunnable() { FailureOnOddInvocations.invocations = 0; - final Runnable runnable = Functions.asRunnable(FailureOnOddInvocations::new); + final Runnable runnable = Failable.asRunnable(FailureOnOddInvocations::new); final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, runnable::run); final Throwable cause = e.getCause(); assertNotNull(cause); @@ -507,6 +604,109 @@ public void testAsRunnable() { runnable.run(); } + @Test + public void testAsSupplier() { + FailureOnOddInvocations.invocations = 0; + final FailableSupplier failableSupplier = FailureOnOddInvocations::new; + final Supplier supplier = Failable.asSupplier(failableSupplier); + final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, supplier::get); + final Throwable cause = e.getCause(); + assertNotNull(cause); + assertTrue(cause instanceof SomeException); + assertEquals("Odd Invocation: 1", cause.getMessage()); + assertNotNull(supplier.get()); + } + + @Test + void testBiConsumer() { + final IllegalStateException ise = new IllegalStateException(); + final Testable testable = new Testable<>(null); + final FailableBiConsumer, Throwable, Throwable> failableBiConsumer = (t, th) -> { + t.setThrowable(th); + t.test(); + }; + final BiConsumer, Throwable> consumer = Failable.asBiConsumer(failableBiConsumer); + Throwable e = assertThrows(IllegalStateException.class, () -> consumer.accept(testable, ise)); + assertSame(ise, e); + + final Error error = new OutOfMemoryError(); + e = assertThrows(OutOfMemoryError.class, () -> consumer.accept(testable, error)); + assertSame(error, e); + + final IOException ioe = new IOException("Unknown I/O error"); + testable.setThrowable(ioe); + e = assertThrows(UncheckedIOException.class, () -> consumer.accept(testable, ioe)); + final Throwable t = e.getCause(); + assertNotNull(t); + assertSame(ioe, t); + + consumer.accept(testable, null); + } + + @Test + public void testBiFunction() { + final IllegalStateException ise = new IllegalStateException(); + final Testable testable = new Testable<>(ise); + final FailableBiFunction, Throwable, Integer, Throwable> failableBiFunction = (t, th) -> { + t.setThrowable(th); + return Integer.valueOf(t.testAsInteger()); + }; + final BiFunction, Throwable, Integer> biFunction = Failable.asBiFunction(failableBiFunction); + Throwable e = assertThrows(IllegalStateException.class, () -> biFunction.apply(testable, ise)); + assertSame(ise, e); + + final Error error = new OutOfMemoryError(); + testable.setThrowable(error); + e = assertThrows(OutOfMemoryError.class, () -> biFunction.apply(testable, error)); + assertSame(error, e); + + final IOException ioe = new IOException("Unknown I/O error"); + testable.setThrowable(ioe); + e = assertThrows(UncheckedIOException.class, () -> biFunction.apply(testable, ioe)); + final Throwable t = e.getCause(); + assertNotNull(t); + assertSame(ioe, t); + + assertEquals(0, biFunction.apply(testable, null).intValue()); + } + + @Test + @DisplayName("Test that asPredicate(FailableBiPredicate) is converted to -> BiPredicate ") + public void testBiPredicate() { + FailureOnOddInvocations.invocations = 0; + final FailableBiPredicate failableBiPredicate = (t1, + t2) -> FailureOnOddInvocations.failingBool(); + final BiPredicate predicate = Failable.asBiPredicate(failableBiPredicate); + final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, + () -> predicate.test(null, null)); + final Throwable cause = e.getCause(); + assertNotNull(cause); + assertTrue(cause instanceof SomeException); + assertEquals("Odd Invocation: 1", cause.getMessage()); + final boolean instance = predicate.test(null, null); + assertNotNull(instance); + } + + @Test + void testCallable() { + FailureOnOddInvocations.invocations = 0; + final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, + () -> Failable.run(FailureOnOddInvocations::new)); + final Throwable cause = e.getCause(); + assertNotNull(cause); + assertTrue(cause instanceof SomeException); + assertEquals("Odd Invocation: 1", cause.getMessage()); + final FailureOnOddInvocations instance = Failable.call(FailureOnOddInvocations::new); + assertNotNull(instance); + } + + @Test + public void testConstructor() { + // We allow this, which must have been an omission to make the ctor private. + // We could make the ctor private in 4.0. + new Functions(); + } + @Test public void testDoublePredicate() throws Throwable { FailureOnOddInvocations.invocations = 0; @@ -515,28 +715,55 @@ public void testDoublePredicate() throws Throwable { failablePredicate.test(1d); } + @Test + public void testFunction() { + final IllegalStateException ise = new IllegalStateException(); + final Testable testable = new Testable<>(ise); + final FailableFunction failableFunction = th -> { + testable.setThrowable(th); + return Integer.valueOf(testable.testAsInteger()); + }; + final Function function = Failable.asFunction(failableFunction); + Throwable e = assertThrows(IllegalStateException.class, () -> function.apply(ise)); + assertSame(ise, e); + + final Error error = new OutOfMemoryError(); + testable.setThrowable(error); + e = assertThrows(OutOfMemoryError.class, () -> function.apply(error)); + assertSame(error, e); + + final IOException ioe = new IOException("Unknown I/O error"); + testable.setThrowable(ioe); + e = assertThrows(UncheckedIOException.class, () -> function.apply(ioe)); + final Throwable t = e.getCause(); + assertNotNull(t); + assertSame(ioe, t); + + assertEquals(0, function.apply(null).intValue()); + } + @Test public void testGetAsBooleanSupplier() { final IllegalStateException ise = new IllegalStateException(); final Testable testable = new Testable<>(ise); Throwable e = assertThrows(IllegalStateException.class, - () -> Functions.getAsBoolean(testable::testAsBooleanPrimitive)); + () -> Failable.getAsBoolean(testable::testAsBooleanPrimitive)); assertSame(ise, e); final Error error = new OutOfMemoryError(); testable.setThrowable(error); - e = assertThrows(OutOfMemoryError.class, () -> Functions.getAsBoolean(testable::testAsBooleanPrimitive)); + e = assertThrows(OutOfMemoryError.class, () -> Failable.getAsBoolean(testable::testAsBooleanPrimitive)); assertSame(error, e); final IOException ioe = new IOException("Unknown I/O error"); testable.setThrowable(ioe); - e = assertThrows(UncheckedIOException.class, () -> Functions.getAsBoolean(testable::testAsBooleanPrimitive)); + e = assertThrows(UncheckedIOException.class, () -> Failable.getAsBoolean(testable::testAsBooleanPrimitive)); final Throwable t = e.getCause(); assertNotNull(t); assertSame(ioe, t); testable.setThrowable(null); - assertFalse(Functions.getAsBoolean(testable::testAsBooleanPrimitive)); + assertFalse(Failable.getAsBoolean(testable::testAsBooleanPrimitive)); } @Test @@ -544,46 +771,46 @@ public void testGetAsDoubleSupplier() { final IllegalStateException ise = new IllegalStateException(); final Testable testable = new Testable<>(ise); Throwable e = assertThrows(IllegalStateException.class, - () -> Functions.getAsDouble(testable::testAsDoublePrimitive)); + () -> Failable.getAsDouble(testable::testAsDoublePrimitive)); assertSame(ise, e); final Error error = new OutOfMemoryError(); testable.setThrowable(error); - e = assertThrows(OutOfMemoryError.class, () -> Functions.getAsDouble(testable::testAsDoublePrimitive)); + e = assertThrows(OutOfMemoryError.class, () -> Failable.getAsDouble(testable::testAsDoublePrimitive)); assertSame(error, e); final IOException ioe = new IOException("Unknown I/O error"); testable.setThrowable(ioe); - e = assertThrows(UncheckedIOException.class, () -> Functions.getAsDouble(testable::testAsDoublePrimitive)); + e = assertThrows(UncheckedIOException.class, () -> Failable.getAsDouble(testable::testAsDoublePrimitive)); final Throwable t = e.getCause(); assertNotNull(t); assertSame(ioe, t); testable.setThrowable(null); - assertEquals(0, Functions.getAsDouble(testable::testAsDoublePrimitive)); + assertEquals(0, Failable.getAsDouble(testable::testAsDoublePrimitive)); } @Test public void testGetAsIntSupplier() { final IllegalStateException ise = new IllegalStateException(); final Testable testable = new Testable<>(ise); - Throwable e = assertThrows(IllegalStateException.class, () -> Functions.getAsInt(testable::testAsIntPrimitive)); + Throwable e = assertThrows(IllegalStateException.class, () -> Failable.getAsInt(testable::testAsIntPrimitive)); assertSame(ise, e); final Error error = new OutOfMemoryError(); testable.setThrowable(error); - e = assertThrows(OutOfMemoryError.class, () -> Functions.getAsInt(testable::testAsIntPrimitive)); + e = assertThrows(OutOfMemoryError.class, () -> Failable.getAsInt(testable::testAsIntPrimitive)); assertSame(error, e); final IOException ioe = new IOException("Unknown I/O error"); testable.setThrowable(ioe); - e = assertThrows(UncheckedIOException.class, () -> Functions.getAsInt(testable::testAsIntPrimitive)); + e = assertThrows(UncheckedIOException.class, () -> Failable.getAsInt(testable::testAsIntPrimitive)); final Throwable t = e.getCause(); assertNotNull(t); assertSame(ioe, t); testable.setThrowable(null); - final int i = Functions.getAsInt(testable::testAsInteger); + final int i = Failable.getAsInt(testable::testAsInteger); assertEquals(0, i); } @@ -592,23 +819,23 @@ public void testGetAsLongSupplier() { final IllegalStateException ise = new IllegalStateException(); final Testable testable = new Testable<>(ise); Throwable e = assertThrows(IllegalStateException.class, - () -> Functions.getAsLong(testable::testAsLongPrimitive)); + () -> Failable.getAsLong(testable::testAsLongPrimitive)); assertSame(ise, e); final Error error = new OutOfMemoryError(); testable.setThrowable(error); - e = assertThrows(OutOfMemoryError.class, () -> Functions.getAsLong(testable::testAsLongPrimitive)); + e = assertThrows(OutOfMemoryError.class, () -> Failable.getAsLong(testable::testAsLongPrimitive)); assertSame(error, e); final IOException ioe = new IOException("Unknown I/O error"); testable.setThrowable(ioe); - e = assertThrows(UncheckedIOException.class, () -> Functions.getAsLong(testable::testAsLongPrimitive)); + e = assertThrows(UncheckedIOException.class, () -> Failable.getAsLong(testable::testAsLongPrimitive)); final Throwable t = e.getCause(); assertNotNull(t); assertSame(ioe, t); testable.setThrowable(null); - final long i = Functions.getAsLong(testable::testAsLongPrimitive); + final long i = Failable.getAsLong(testable::testAsLongPrimitive); assertEquals(0, i); } @@ -616,12 +843,12 @@ public void testGetAsLongSupplier() { public void testGetFromSupplier() { FailureOnOddInvocations.invocations = 0; final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, - () -> Functions.run(FailureOnOddInvocations::new)); + () -> Failable.run(FailureOnOddInvocations::new)); final Throwable cause = e.getCause(); assertNotNull(cause); assertTrue(cause instanceof SomeException); assertEquals("Odd Invocation: 1", cause.getMessage()); - final FailureOnOddInvocations instance = Functions.call(FailureOnOddInvocations::new); + final FailureOnOddInvocations instance = Failable.call(FailureOnOddInvocations::new); assertNotNull(instance); } @@ -629,23 +856,23 @@ public void testGetFromSupplier() { public void testGetSupplier() { final IllegalStateException ise = new IllegalStateException(); final Testable testable = new Testable<>(ise); - Throwable e = assertThrows(IllegalStateException.class, () -> Functions.get(testable::testAsInteger)); + Throwable e = assertThrows(IllegalStateException.class, () -> Failable.get(testable::testAsInteger)); assertSame(ise, e); final Error error = new OutOfMemoryError(); testable.setThrowable(error); - e = assertThrows(OutOfMemoryError.class, () -> Functions.get(testable::testAsInteger)); + e = assertThrows(OutOfMemoryError.class, () -> Failable.get(testable::testAsInteger)); assertSame(error, e); final IOException ioe = new IOException("Unknown I/O error"); testable.setThrowable(ioe); - e = assertThrows(UncheckedIOException.class, () -> Functions.get(testable::testAsInteger)); + e = assertThrows(UncheckedIOException.class, () -> Failable.get(testable::testAsInteger)); final Throwable t = e.getCause(); assertNotNull(t); assertSame(ioe, t); testable.setThrowable(null); - final Integer i = Functions.apply(Testable::testAsInteger, testable); + final Integer i = Failable.apply(Testable::testAsInteger, testable); assertNotNull(i); assertEquals(0, i.intValue()); } @@ -667,17 +894,34 @@ public void testLongPredicate() throws Throwable { } @Test - public void testRunnable() { + @DisplayName("Test that asPredicate(FailablePredicate) is converted to -> Predicate ") + public void testPredicate() { + FailureOnOddInvocations.invocations = 0; + final FailablePredicate failablePredicate = t -> FailureOnOddInvocations + .failingBool(); + final Predicate predicate = Failable.asPredicate(failablePredicate); + final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, + () -> predicate.test(null)); + final Throwable cause = e.getCause(); + assertNotNull(cause); + assertTrue(cause instanceof SomeException); + assertEquals("Odd Invocation: 1", cause.getMessage()); + final boolean instance = predicate.test(null); + assertNotNull(instance); + } + + @Test + void testRunnable() { FailureOnOddInvocations.invocations = 0; final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, - () -> Functions.run(FailureOnOddInvocations::new)); + () -> Failable.run(FailureOnOddInvocations::new)); final Throwable cause = e.getCause(); assertNotNull(cause); assertTrue(cause instanceof SomeException); assertEquals("Odd Invocation: 1", cause.getMessage()); // Even invocations, should not throw an exception - Functions.run(FailureOnOddInvocations::new); + Failable.run(FailureOnOddInvocations::new); } /** @@ -685,11 +929,11 @@ public void testRunnable() { * Object and Throwable. */ @Test - public void testThrows_FailableBiConsumer_Object_Throwable() { - new Functions.FailableBiConsumer() { + void testThrows_FailableBiConsumer_Object_Throwable() { + new FailableBiConsumer() { @Override - public void accept(Object object1, Object object2) throws Throwable { + public void accept(final Object object1, final Object object2) throws Throwable { throw new IOException("test"); } }; @@ -700,11 +944,11 @@ public void accept(Object object1, Object object2) throws Throwable { * generic test types. */ @Test - public void testThrows_FailableBiConsumer_String_IOException() { - new Functions.FailableBiConsumer() { + void testThrows_FailableBiConsumer_String_IOException() { + new FailableBiConsumer() { @Override - public void accept(String object1, String object2) throws IOException { + public void accept(final String object1, final String object2) throws IOException { throw new IOException("test"); } @@ -716,11 +960,11 @@ public void accept(String object1, String object2) throws IOException { * Object and Throwable. */ @Test - public void testThrows_FailableBiFunction_Object_Throwable() { - new Functions.FailableBiFunction() { + void testThrows_FailableBiFunction_Object_Throwable() { + new FailableBiFunction() { @Override - public Object apply(Object input1, Object input2) throws Throwable { + public Object apply(final Object input1, final Object input2) throws Throwable { throw new IOException("test"); } }; @@ -731,11 +975,11 @@ public Object apply(Object input1, Object input2) throws Throwable { * generic test types. */ @Test - public void testThrows_FailableBiFunction_String_IOException() { - new Functions.FailableBiFunction() { + void testThrows_FailableBiFunction_String_IOException() { + new FailableBiFunction() { @Override - public String apply(String input1, String input2) throws IOException { + public String apply(final String input1, final String input2) throws IOException { throw new IOException("test"); } }; @@ -746,11 +990,11 @@ public String apply(String input1, String input2) throws IOException { * Object and Throwable. */ @Test - public void testThrows_FailableBiPredicate_Object_Throwable() { - new Functions.FailableBiPredicate() { + void testThrows_FailableBiPredicate_Object_Throwable() { + new FailableBiPredicate() { @Override - public boolean test(Object object1, Object object2) throws Throwable { + public boolean test(final Object object1, final Object object2) throws Throwable { throw new IOException("test"); } }; @@ -761,11 +1005,11 @@ public boolean test(Object object1, Object object2) throws Throwable { * generic test types. */ @Test - public void testThrows_FailableBiPredicate_String_IOException() { - new Functions.FailableBiPredicate() { + void testThrows_FailableBiPredicate_String_IOException() { + new FailableBiPredicate() { @Override - public boolean test(String object1, String object2) throws IOException { + public boolean test(final String object1, final String object2) throws IOException { throw new IOException("test"); } }; @@ -801,13 +1045,16 @@ public boolean getAsBoolean() throws IOException { }; } + /////////////////////////////////////////////// + + /** * Tests that our failable interface is properly defined to throw any exception. using the top level generic types * Object and Throwable. */ @Test - public void testThrows_FailableCallable_Object_Throwable() { - new Functions.FailableCallable() { + void testThrows_FailableCallable_Object_Throwable() { + new FailableCallable() { @Override public Object call() throws Throwable { @@ -821,8 +1068,8 @@ public Object call() throws Throwable { * generic test types. */ @Test - public void testThrows_FailableCallable_String_IOException() { - new Functions.FailableCallable() { + void testThrows_FailableCallable_String_IOException() { + new FailableCallable() { @Override public String call() throws IOException { @@ -836,11 +1083,11 @@ public String call() throws IOException { * Object and Throwable. */ @Test - public void testThrows_FailableConsumer_Object_Throwable() { - new Functions.FailableConsumer() { + void testThrows_FailableConsumer_Object_Throwable() { + new FailableConsumer() { @Override - public void accept(Object object) throws Throwable { + public void accept(final Object object) throws Throwable { throw new IOException("test"); } @@ -852,11 +1099,11 @@ public void accept(Object object) throws Throwable { * generic test types. */ @Test - public void testThrows_FailableConsumer_String_IOException() { - new Functions.FailableConsumer() { + void testThrows_FailableConsumer_String_IOException() { + new FailableConsumer() { @Override - public void accept(String object) throws IOException { + public void accept(final String object) throws IOException { throw new IOException("test"); } @@ -872,7 +1119,7 @@ public void testThrows_FailableDoubleBinaryOperator_Object_Throwable() { new FailableDoubleBinaryOperator() { @Override - public double applyAsDouble(double left, double right) throws Throwable { + public double applyAsDouble(final double left, final double right) throws Throwable { throw new IOException("test"); } }; @@ -887,7 +1134,7 @@ public void testThrows_FailableDoubleBinaryOperator_String_IOException() { new FailableDoubleBinaryOperator() { @Override - public double applyAsDouble(double left, double right) throws IOException { + public double applyAsDouble(final double left, final double right) throws IOException { throw new IOException("test"); } }; @@ -902,7 +1149,7 @@ public void testThrows_FailableDoubleConsumer_Object_Throwable() { new FailableDoubleConsumer() { @Override - public void accept(double value) throws Throwable { + public void accept(final double value) throws Throwable { throw new IOException("test"); } @@ -918,7 +1165,7 @@ public void testThrows_FailableDoubleConsumer_String_IOException() { new FailableDoubleConsumer() { @Override - public void accept(double value) throws IOException { + public void accept(final double value) throws IOException { throw new IOException("test"); } }; @@ -933,7 +1180,7 @@ public void testThrows_FailableDoubleFunction_Object_Throwable() { new FailableDoubleFunction() { @Override - public Object apply(double input) throws Throwable { + public Object apply(final double input) throws Throwable { throw new IOException("test"); } }; @@ -948,7 +1195,7 @@ public void testThrows_FailableDoubleFunction_String_IOException() { new FailableDoubleFunction() { @Override - public String apply(double input) throws IOException { + public String apply(final double input) throws IOException { throw new IOException("test"); } }; @@ -993,7 +1240,7 @@ public void testThrows_FailableDoubleToIntFunction_Object_Throwable() { new FailableDoubleToIntFunction() { @Override - public int applyAsInt(double value) throws Throwable { + public int applyAsInt(final double value) throws Throwable { throw new IOException("test"); } }; @@ -1008,7 +1255,7 @@ public void testThrows_FailableDoubleToIntFunction_String_IOException() { new FailableDoubleToIntFunction() { @Override - public int applyAsInt(double value) throws IOException { + public int applyAsInt(final double value) throws IOException { throw new IOException("test"); } }; @@ -1023,7 +1270,7 @@ public void testThrows_FailableDoubleToLongFunction_Object_Throwable() { new FailableDoubleToLongFunction() { @Override - public int applyAsLong(double value) throws Throwable { + public int applyAsLong(final double value) throws Throwable { throw new IOException("test"); } }; @@ -1038,7 +1285,7 @@ public void testThrows_FailableDoubleToLongFunction_String_IOException() { new FailableDoubleToLongFunction() { @Override - public int applyAsLong(double value) throws IOException { + public int applyAsLong(final double value) throws IOException { throw new IOException("test"); } }; @@ -1050,10 +1297,10 @@ public int applyAsLong(double value) throws IOException { */ @Test public void testThrows_FailableFunction_Object_Throwable() { - new Functions.FailableFunction() { + new FailableFunction() { @Override - public Object apply(Object input) throws Throwable { + public Object apply(final Object input) throws Throwable { throw new IOException("test"); } }; @@ -1065,10 +1312,10 @@ public Object apply(Object input) throws Throwable { */ @Test public void testThrows_FailableFunction_String_IOException() { - new Functions.FailableFunction() { + new FailableFunction() { @Override - public String apply(String input) throws IOException { + public String apply(final String input) throws IOException { throw new IOException("test"); } }; @@ -1083,7 +1330,7 @@ public void testThrows_FailableIntBinaryOperator_Object_Throwable() { new FailableIntBinaryOperator() { @Override - public int applyAsInt(int left, int right) throws Throwable { + public int applyAsInt(final int left, final int right) throws Throwable { throw new IOException("test"); } }; @@ -1098,7 +1345,7 @@ public void testThrows_FailableIntBinaryOperator_String_IOException() { new FailableIntBinaryOperator() { @Override - public int applyAsInt(int left, int right) throws IOException { + public int applyAsInt(final int left, final int right) throws IOException { throw new IOException("test"); } }; @@ -1113,7 +1360,7 @@ public void testThrows_FailableIntConsumer_Object_Throwable() { new FailableIntConsumer() { @Override - public void accept(int value) throws Throwable { + public void accept(final int value) throws Throwable { throw new IOException("test"); } @@ -1129,7 +1376,7 @@ public void testThrows_FailableIntConsumer_String_IOException() { new FailableIntConsumer() { @Override - public void accept(int value) throws IOException { + public void accept(final int value) throws IOException { throw new IOException("test"); } }; @@ -1144,7 +1391,7 @@ public void testThrows_FailableIntFunction_Object_Throwable() { new FailableIntFunction() { @Override - public Object apply(int input) throws Throwable { + public Object apply(final int input) throws Throwable { throw new IOException("test"); } }; @@ -1159,7 +1406,7 @@ public void testThrows_FailableIntFunction_String_IOException() { new FailableIntFunction() { @Override - public String apply(int input) throws IOException { + public String apply(final int input) throws IOException { throw new IOException("test"); } }; @@ -1204,7 +1451,7 @@ public void testThrows_FailableIntToDoubleFunction_Object_Throwable() { new FailableIntToDoubleFunction() { @Override - public double applyAsDouble(int value) throws Throwable { + public double applyAsDouble(final int value) throws Throwable { throw new IOException("test"); } }; @@ -1219,7 +1466,7 @@ public void testThrows_FailableIntToDoubleFunction_String_IOException() { new FailableIntToDoubleFunction() { @Override - public double applyAsDouble(int value) throws IOException { + public double applyAsDouble(final int value) throws IOException { throw new IOException("test"); } }; @@ -1234,7 +1481,7 @@ public void testThrows_FailableIntToLongFunction_Object_Throwable() { new FailableIntToLongFunction() { @Override - public long applyAsLong(int value) throws Throwable { + public long applyAsLong(final int value) throws Throwable { throw new IOException("test"); } }; @@ -1249,7 +1496,7 @@ public void testThrows_FailableIntToLongFunction_String_IOException() { new FailableIntToLongFunction() { @Override - public long applyAsLong(int value) throws IOException { + public long applyAsLong(final int value) throws IOException { throw new IOException("test"); } }; @@ -1264,7 +1511,7 @@ public void testThrows_FailableLongBinaryOperator_Object_Throwable() { new FailableLongBinaryOperator() { @Override - public long applyAsLong(long left, long right) throws Throwable { + public long applyAsLong(final long left, final long right) throws Throwable { throw new IOException("test"); } }; @@ -1279,7 +1526,7 @@ public void testThrows_FailableLongBinaryOperator_String_IOException() { new FailableLongBinaryOperator() { @Override - public long applyAsLong(long left, long right) throws IOException { + public long applyAsLong(final long left, final long right) throws IOException { throw new IOException("test"); } }; @@ -1294,7 +1541,7 @@ public void testThrows_FailableLongConsumer_Object_Throwable() { new FailableLongConsumer() { @Override - public void accept(long object) throws Throwable { + public void accept(final long object) throws Throwable { throw new IOException("test"); } @@ -1310,7 +1557,7 @@ public void testThrows_FailableLongConsumer_String_IOException() { new FailableLongConsumer() { @Override - public void accept(long object) throws IOException { + public void accept(final long object) throws IOException { throw new IOException("test"); } @@ -1326,7 +1573,7 @@ public void testThrows_FailableLongFunction_Object_Throwable() { new FailableLongFunction() { @Override - public Object apply(long input) throws Throwable { + public Object apply(final long input) throws Throwable { throw new IOException("test"); } }; @@ -1341,7 +1588,7 @@ public void testThrows_FailableLongFunction_String_IOException() { new FailableLongFunction() { @Override - public String apply(long input) throws IOException { + public String apply(final long input) throws IOException { throw new IOException("test"); } }; @@ -1386,7 +1633,7 @@ public void testThrows_FailableLongToDoubleFunction_Object_Throwable() { new FailableLongToDoubleFunction() { @Override - public double applyAsDouble(long value) throws Throwable { + public double applyAsDouble(final long value) throws Throwable { throw new IOException("test"); } }; @@ -1401,7 +1648,7 @@ public void testThrows_FailableLongToDoubleFunction_String_IOException() { new FailableLongToDoubleFunction() { @Override - public double applyAsDouble(long value) throws IOException { + public double applyAsDouble(final long value) throws IOException { throw new IOException("test"); } }; @@ -1416,7 +1663,7 @@ public void testThrows_FailableLongToIntFunction_Object_Throwable() { new FailableLongToIntFunction() { @Override - public int applyAsInt(long value) throws Throwable { + public int applyAsInt(final long value) throws Throwable { throw new IOException("test"); } }; @@ -1431,7 +1678,7 @@ public void testThrows_FailableLongToIntFunction_String_IOException() { new FailableLongToIntFunction() { @Override - public int applyAsInt(long value) throws IOException { + public int applyAsInt(final long value) throws IOException { throw new IOException("test"); } }; @@ -1446,7 +1693,7 @@ public void testThrows_FailableObjDoubleConsumer_Object_Throwable() { new FailableObjDoubleConsumer() { @Override - public void accept(Object object, double value) throws Throwable { + public void accept(final Object object, final double value) throws Throwable { throw new IOException("test"); } @@ -1462,7 +1709,7 @@ public void testThrows_FailableObjDoubleConsumer_String_IOException() { new FailableObjDoubleConsumer() { @Override - public void accept(String object, double value) throws IOException { + public void accept(final String object, final double value) throws IOException { throw new IOException("test"); } }; @@ -1477,7 +1724,7 @@ public void testThrows_FailableObjIntConsumer_Object_Throwable() { new FailableObjIntConsumer() { @Override - public void accept(Object object, int value) throws Throwable { + public void accept(final Object object, final int value) throws Throwable { throw new IOException("test"); } @@ -1493,7 +1740,7 @@ public void testThrows_FailableObjIntConsumer_String_IOException() { new FailableObjIntConsumer() { @Override - public void accept(String object, int value) throws IOException { + public void accept(final String object, final int value) throws IOException { throw new IOException("test"); } }; @@ -1508,7 +1755,7 @@ public void testThrows_FailableObjLongConsumer_Object_Throwable() { new FailableObjLongConsumer() { @Override - public void accept(Object object, long value) throws Throwable { + public void accept(final Object object, final long value) throws Throwable { throw new IOException("test"); } @@ -1524,7 +1771,7 @@ public void testThrows_FailableObjLongConsumer_String_IOException() { new FailableObjLongConsumer() { @Override - public void accept(String object, long value) throws IOException { + public void accept(final String object, final long value) throws IOException { throw new IOException("test"); } }; @@ -1536,10 +1783,10 @@ public void accept(String object, long value) throws IOException { */ @Test public void testThrows_FailablePredicate_Object_Throwable() { - new Functions.FailablePredicate() { + new FailablePredicate() { @Override - public boolean test(Object object) throws Throwable { + public boolean test(final Object object) throws Throwable { throw new IOException("test"); } }; @@ -1551,10 +1798,10 @@ public boolean test(Object object) throws Throwable { */ @Test public void testThrows_FailablePredicate_String_IOException() { - new Functions.FailablePredicate() { + new FailablePredicate() { @Override - public boolean test(String object) throws IOException { + public boolean test(final String object) throws IOException { throw new IOException("test"); } }; @@ -1566,7 +1813,7 @@ public boolean test(String object) throws IOException { */ @Test public void testThrows_FailableRunnable_Object_Throwable() { - new Functions.FailableRunnable() { + new FailableRunnable() { @Override public void run() throws Throwable { @@ -1582,7 +1829,7 @@ public void run() throws Throwable { */ @Test public void testThrows_FailableRunnable_String_IOException() { - new Functions.FailableRunnable() { + new FailableRunnable() { @Override public void run() throws IOException { @@ -1597,7 +1844,7 @@ public void run() throws IOException { */ @Test public void testThrows_FailableSupplier_Object_Throwable() { - new Functions.FailableSupplier() { + new FailableSupplier() { @Override public Object get() throws Throwable { @@ -1612,7 +1859,7 @@ public Object get() throws Throwable { */ @Test public void testThrows_FailableSupplier_String_IOException() { - new Functions.FailableSupplier() { + new FailableSupplier() { @Override public String get() throws IOException { @@ -1630,7 +1877,7 @@ public void testThrows_FailableToDoubleBiFunction_Object_Throwable() { new FailableToDoubleBiFunction() { @Override - public double applyAsDouble(Object t, Object u) throws Throwable { + public double applyAsDouble(final Object t, final Object u) throws Throwable { throw new IOException("test"); } }; @@ -1645,7 +1892,7 @@ public void testThrows_FailableToDoubleBiFunction_String_IOException() { new FailableToDoubleBiFunction() { @Override - public double applyAsDouble(String t, String u) throws IOException { + public double applyAsDouble(final String t, final String u) throws IOException { throw new IOException("test"); } }; @@ -1660,7 +1907,7 @@ public void testThrows_FailableToDoubleFunction_Object_Throwable() { new FailableToDoubleFunction() { @Override - public double applyAsDouble(Object t) throws Throwable { + public double applyAsDouble(final Object t) throws Throwable { throw new IOException("test"); } }; @@ -1675,7 +1922,7 @@ public void testThrows_FailableToDoubleFunction_String_IOException() { new FailableToDoubleFunction() { @Override - public double applyAsDouble(String t) throws IOException { + public double applyAsDouble(final String t) throws IOException { throw new IOException("test"); } }; @@ -1690,7 +1937,7 @@ public void testThrows_FailableToIntBiFunction_Object_Throwable() { new FailableToIntBiFunction() { @Override - public int applyAsInt(Object t, Object u) throws Throwable { + public int applyAsInt(final Object t, final Object u) throws Throwable { throw new IOException("test"); } }; @@ -1705,7 +1952,7 @@ public void testThrows_FailableToIntBiFunction_String_IOException() { new FailableToIntBiFunction() { @Override - public int applyAsInt(String t, String u) throws IOException { + public int applyAsInt(final String t, final String u) throws IOException { throw new IOException("test"); } }; @@ -1720,7 +1967,7 @@ public void testThrows_FailableToIntFunction_Object_Throwable() { new FailableToIntFunction() { @Override - public int applyAsInt(Object t) throws Throwable { + public int applyAsInt(final Object t) throws Throwable { throw new IOException("test"); } }; @@ -1735,7 +1982,7 @@ public void testThrows_FailableToIntFunction_String_IOException() { new FailableToIntFunction() { @Override - public int applyAsInt(String t) throws IOException { + public int applyAsInt(final String t) throws IOException { throw new IOException("test"); } }; @@ -1750,7 +1997,7 @@ public void testThrows_FailableToLongBiFunction_Object_Throwable() { new FailableToLongBiFunction() { @Override - public long applyAsLong(Object t, Object u) throws Throwable { + public long applyAsLong(final Object t, final Object u) throws Throwable { throw new IOException("test"); } }; @@ -1765,7 +2012,7 @@ public void testThrows_FailableToLongBiFunction_String_IOException() { new FailableToLongBiFunction() { @Override - public long applyAsLong(String t, String u) throws IOException { + public long applyAsLong(final String t, final String u) throws IOException { throw new IOException("test"); } }; @@ -1780,7 +2027,7 @@ public void testThrows_FailableToLongFunction_Object_Throwable() { new FailableToLongFunction() { @Override - public long applyAsLong(Object t) throws Throwable { + public long applyAsLong(final Object t) throws Throwable { throw new IOException("test"); } }; @@ -1795,10 +2042,40 @@ public void testThrows_FailableToLongFunction_String_IOException() { new FailableToLongFunction() { @Override - public long applyAsLong(String t) throws IOException { + public long applyAsLong(final String t) throws IOException { throw new IOException("test"); } }; } + @Test + public void testTryWithResources() { + final CloseableObject co = new CloseableObject(); + final FailableConsumer consumer = co::run; + final IllegalStateException ise = new IllegalStateException(); + Throwable e = assertThrows(IllegalStateException.class, + () -> Failable.tryWithResources(() -> consumer.accept(ise), co::close)); + assertSame(ise, e); + + assertTrue(co.isClosed()); + co.reset(); + final Error error = new OutOfMemoryError(); + e = assertThrows(OutOfMemoryError.class, + () -> Failable.tryWithResources(() -> consumer.accept(error), co::close)); + assertSame(error, e); + + assertTrue(co.isClosed()); + co.reset(); + final IOException ioe = new IOException("Unknown I/O error"); + final UncheckedIOException uioe = assertThrows(UncheckedIOException.class, + () -> Failable.tryWithResources(() -> consumer.accept(ioe), co::close)); + final IOException cause = uioe.getCause(); + assertSame(ioe, cause); + + assertTrue(co.isClosed()); + co.reset(); + Failable.tryWithResources(() -> consumer.accept(null), co::close); + assertTrue(co.isClosed()); + } + } From 7ba418fc6f0b4e911a33c8e086a75a622a2ae09e Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Wed, 17 Jun 2020 16:46:10 -0400 Subject: [PATCH 0158/3230] Centralize failable functional interfaces in our 'function' package as the parallel to the JRE's java.util.function package. Deprecate old class. --- .../org/apache/commons/lang3/Functions.java | 5 +- .../java/org/apache/commons/lang3/Locks.java | 9 +- .../commons/lang3/function/Failable.java | 573 ++++++++++++++++++ .../lang3/function/FailableBiConsumer.java | 41 ++ .../lang3/function/FailableBiFunction.java | 43 ++ .../lang3/function/FailableBiPredicate.java | 42 ++ .../lang3/function/FailableCallable.java | 37 ++ .../lang3/function/FailableConsumer.java | 39 ++ .../lang3/function/FailableFunction.java | 41 ++ .../lang3/function/FailablePredicate.java | 40 ++ .../lang3/function/FailableRunnable.java | 35 ++ .../lang3/function/FailableSupplier.java | 39 ++ .../org/apache/commons/lang3/LocksTest.java | 2 +- 13 files changed, 940 insertions(+), 6 deletions(-) create mode 100644 src/main/java/org/apache/commons/lang3/function/Failable.java create mode 100644 src/main/java/org/apache/commons/lang3/function/FailableBiConsumer.java create mode 100644 src/main/java/org/apache/commons/lang3/function/FailableBiFunction.java create mode 100644 src/main/java/org/apache/commons/lang3/function/FailableBiPredicate.java create mode 100644 src/main/java/org/apache/commons/lang3/function/FailableCallable.java create mode 100644 src/main/java/org/apache/commons/lang3/function/FailableConsumer.java create mode 100644 src/main/java/org/apache/commons/lang3/function/FailableFunction.java create mode 100644 src/main/java/org/apache/commons/lang3/function/FailablePredicate.java create mode 100644 src/main/java/org/apache/commons/lang3/function/FailableRunnable.java create mode 100644 src/main/java/org/apache/commons/lang3/function/FailableSupplier.java diff --git a/src/main/java/org/apache/commons/lang3/Functions.java b/src/main/java/org/apache/commons/lang3/Functions.java index 4aa72094ce2..626928c76b8 100644 --- a/src/main/java/org/apache/commons/lang3/Functions.java +++ b/src/main/java/org/apache/commons/lang3/Functions.java @@ -32,6 +32,7 @@ import java.util.stream.Stream; import org.apache.commons.lang3.Streams.FailableStream; +import org.apache.commons.lang3.function.Failable; import org.apache.commons.lang3.function.FailableBooleanSupplier; import org.apache.commons.lang3.function.FailableDoubleBinaryOperator; import org.apache.commons.lang3.function.FailableDoubleConsumer; @@ -73,12 +74,14 @@ * version. *

      * @since 3.9 + * @deprecated Use {@link org.apache.commons.lang3.function.Failable}. */ +@Deprecated public class Functions { /** * A functional interface like {@link BiConsumer} that declares a {@code Throwable}. - * + * *

      TODO for 4.0: Move to org.apache.commons.lang3.function.

      * * @param Consumed type 1. diff --git a/src/main/java/org/apache/commons/lang3/Locks.java b/src/main/java/org/apache/commons/lang3/Locks.java index b8fcc45b4aa..1fabaf38e42 100644 --- a/src/main/java/org/apache/commons/lang3/Locks.java +++ b/src/main/java/org/apache/commons/lang3/Locks.java @@ -19,8 +19,9 @@ import java.util.Objects; import java.util.concurrent.locks.StampedLock; -import org.apache.commons.lang3.Functions.FailableConsumer; -import org.apache.commons.lang3.Functions.FailableFunction; +import org.apache.commons.lang3.function.Failable; +import org.apache.commons.lang3.function.FailableConsumer; +import org.apache.commons.lang3.function.FailableFunction; /** Utility class for working with {@link java.util.concurrent.locks.Lock locked objects}. Locked objects are an @@ -93,7 +94,7 @@ protected void runLocked(long stamp, FailableConsumer consumer) { try { consumer.accept(lockedObject); } catch (Throwable t) { - throw Functions.rethrow(t); + throw Failable.rethrow(t); } finally { lock.unlock(stamp); } @@ -103,7 +104,7 @@ protected T callLocked(long stamp, FailableFunction function) { try { return function.apply(lockedObject); } catch (Throwable t) { - throw Functions.rethrow(t); + throw Failable.rethrow(t); } finally { lock.unlock(stamp); } diff --git a/src/main/java/org/apache/commons/lang3/function/Failable.java b/src/main/java/org/apache/commons/lang3/function/Failable.java new file mode 100644 index 00000000000..bcc3e29d561 --- /dev/null +++ b/src/main/java/org/apache/commons/lang3/function/Failable.java @@ -0,0 +1,573 @@ +/* + * 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.function; + +import java.io.IOException; +import java.io.UncheckedIOException; +import java.lang.reflect.UndeclaredThrowableException; +import java.util.Collection; +import java.util.Objects; +import java.util.concurrent.Callable; +import java.util.function.BiConsumer; +import java.util.function.BiFunction; +import java.util.function.BiPredicate; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.function.Supplier; +import java.util.stream.Stream; + +import org.apache.commons.lang3.Streams.FailableStream; + +/** + * This class provides utility functions, and classes for working with the {@code java.util.function} package, or more + * generally, with Java 8 lambdas. More specifically, it attempts to address the fact that lambdas are supposed not to + * throw Exceptions, at least not checked Exceptions, AKA instances of {@link Exception}. This enforces the use of + * constructs like: + * + *
      + * {@code
      + *     Consumer consumer = (m) -> {
      + *         try {
      + *             m.invoke(o, args);
      + *         } catch (Throwable t) {
      + *             throw Functions.rethrow(t);
      + *         }
      + *     };
      + * }
      + * + *

      + * By replacing a {@link java.util.function.Consumer Consumer<O>} with a {@link FailableConsumer + * FailableConsumer<O,? extends Throwable>}, this can be written like follows: + *

      + * + *
      + * {@code
      + *   Functions.accept((m) -> m.invoke(o,args));
      + * }
      + * + *

      + * Obviously, the second version is much more concise and the spirit of Lambda expressions is met better than the second + * version. + *

      + * + * @since 3.11 + */ +public class Failable { + + /** + * Consumes a consumer and rethrows any exception as a {@link RuntimeException}. + * + * @param consumer the consumer to consume + * @param object1 the first object to consume by {@code consumer} + * @param object2 the second object to consume by {@code consumer} + * @param the type of the first argument the consumer accepts + * @param the type of the second argument the consumer accepts + * @param the type of checked exception the consumer may throw + */ + public static void accept(final FailableBiConsumer consumer, + final O1 object1, final O2 object2) { + run(() -> consumer.accept(object1, object2)); + } + + /** + * Consumes a consumer and rethrows any exception as a {@link RuntimeException}. + * + * @param consumer the consumer to consume + * @param object the object to consume by {@code consumer} + * @param the type the consumer accepts + * @param the type of checked exception the consumer may throw + */ + public static void accept(final FailableConsumer consumer, final O object) { + run(() -> consumer.accept(object)); + } + + /** + * Consumes a consumer and rethrows any exception as a {@link RuntimeException}. + * + * @param consumer the consumer to consume + * @param value the value to consume by {@code consumer} + * @param the type of checked exception the consumer may throw + */ + public static void accept(final FailableDoubleConsumer consumer, final double value) { + run(() -> consumer.accept(value)); + } + + /** + * Consumes a consumer and rethrows any exception as a {@link RuntimeException}. + * + * @param consumer the consumer to consume + * @param value the value to consume by {@code consumer} + * @param the type of checked exception the consumer may throw + */ + public static void accept(final FailableIntConsumer consumer, final int value) { + run(() -> consumer.accept(value)); + } + + /** + * Consumes a consumer and rethrows any exception as a {@link RuntimeException}. + * + * @param consumer the consumer to consume + * @param value the value to consume by {@code consumer} + * @param the type of checked exception the consumer may throw + */ + public static void accept(final FailableLongConsumer consumer, final long value) { + run(() -> consumer.accept(value)); + } + + /** + * Applies a function and rethrows any exception as a {@link RuntimeException}. + * + * @param function the function to apply + * @param input1 the first input to apply {@code function} on + * @param input2 the second input to apply {@code function} on + * @param the type of the first argument the function accepts + * @param the type of the second argument the function accepts + * @param the return type of the function + * @param the type of checked exception the function may throw + * @return the value returned from the function + */ + public static O apply(final FailableBiFunction function, + final O1 input1, final O2 input2) { + return get(() -> function.apply(input1, input2)); + } + + /** + * Applies a function and rethrows any exception as a {@link RuntimeException}. + * + * @param function the function to apply + * @param input the input to apply {@code function} on + * @param the type of the argument the function accepts + * @param the return type of the function + * @param the type of checked exception the function may throw + * @return the value returned from the function + */ + public static O apply(final FailableFunction function, final I input) { + return get(() -> function.apply(input)); + } + + /** + * Applies a function and rethrows any exception as a {@link RuntimeException}. + * + * @param function the function to apply + * @param left the first input to apply {@code function} on + * @param right the second input to apply {@code function} on + * @param the type of checked exception the function may throw + * @return the value returned from the function + */ + public static double applyAsDouble(final FailableDoubleBinaryOperator function, + final double left, final double right) { + return getAsDouble(() -> function.applyAsDouble(left, right)); + } + + /** + * Converts the given {@link FailableBiConsumer} into a standard {@link BiConsumer}. + * + * @param the type of the first argument of the consumers + * @param the type of the second argument of the consumers + * @param consumer a failable {@code BiConsumer} + * @return a standard {@code BiConsumer} + */ + public static BiConsumer asBiConsumer(final FailableBiConsumer consumer) { + return (input1, input2) -> accept(consumer, input1, input2); + } + + /** + * Converts the given {@link FailableBiFunction} into a standard {@link BiFunction}. + * + * @param the type of the first argument of the input of the functions + * @param the type of the second argument of the input of the functions + * @param the type of the output of the functions + * @param function a {@code FailableBiFunction} + * @return a standard {@code BiFunction} + */ + public static BiFunction asBiFunction(final FailableBiFunction function) { + return (input1, input2) -> apply(function, input1, input2); + } + + /** + * Converts the given {@link FailableBiPredicate} into a standard {@link BiPredicate}. + * + * @param the type of the first argument used by the predicates + * @param the type of the second argument used by the predicates + * @param predicate a {@code FailableBiPredicate} + * @return a standard {@code BiPredicate} + */ + public static BiPredicate asBiPredicate(final FailableBiPredicate predicate) { + return (input1, input2) -> test(predicate, input1, input2); + } + + /** + * Converts the given {@link FailableCallable} into a standard {@link Callable}. + * + * @param the type used by the callables + * @param callable a {@code FailableCallable} + * @return a standard {@code Callable} + */ + public static Callable asCallable(final FailableCallable callable) { + return () -> call(callable); + } + + /** + * Converts the given {@link FailableConsumer} into a standard {@link Consumer}. + * + * @param the type used by the consumers + * @param consumer a {@code FailableConsumer} + * @return a standard {@code Consumer} + */ + public static Consumer asConsumer(final FailableConsumer consumer) { + return input -> accept(consumer, input); + } + + /** + * Converts the given {@link FailableFunction} into a standard {@link Function}. + * + * @param the type of the input of the functions + * @param the type of the output of the functions + * @param function a {code FailableFunction} + * @return a standard {@code Function} + */ + public static Function asFunction(final FailableFunction function) { + return input -> apply(function, input); + } + + /** + * Converts the given {@link FailablePredicate} into a standard {@link Predicate}. + * + * @param the type used by the predicates + * @param predicate a {@code FailablePredicate} + * @return a standard {@code Predicate} + */ + public static Predicate asPredicate(final FailablePredicate predicate) { + return input -> test(predicate, input); + } + + /** + * Converts the given {@link FailableRunnable} into a standard {@link Runnable}. + * + * @param runnable a {@code FailableRunnable} + * @return a standard {@code Runnable} + */ + public static Runnable asRunnable(final FailableRunnable runnable) { + return () -> run(runnable); + } + + /** + * Converts the given {@link FailableSupplier} into a standard {@link Supplier}. + * + * @param the type supplied by the suppliers + * @param supplier a {@code FailableSupplier} + * @return a standard {@code Supplier} + */ + public static Supplier asSupplier(final FailableSupplier supplier) { + return () -> get(supplier); + } + + /** + * Calls a callable and rethrows any exception as a {@link RuntimeException}. + * + * @param callable the callable to call + * @param the return type of the callable + * @param the type of checked exception the callable may throw + * @return the value returned from the callable + */ + public static O call(final FailableCallable callable) { + return get(callable::call); + } + + /** + * Invokes a supplier, and returns the result. + * + * @param supplier The supplier to invoke. + * @param The suppliers output type. + * @param The type of checked exception, which the supplier can throw. + * @return The object, which has been created by the supplier + */ + public static O get(final FailableSupplier supplier) { + try { + return supplier.get(); + } catch (final Throwable t) { + throw rethrow(t); + } + } + + /** + * Invokes a boolean supplier, and returns the result. + * + * @param supplier The boolean supplier to invoke. + * @param The type of checked exception, which the supplier can throw. + * @return The boolean, which has been created by the supplier + */ + public static boolean getAsBoolean(final FailableBooleanSupplier supplier) { + try { + return supplier.getAsBoolean(); + } catch (final Throwable t) { + throw rethrow(t); + } + } + + /** + * Invokes a double supplier, and returns the result. + * + * @param supplier The double supplier to invoke. + * @param The type of checked exception, which the supplier can throw. + * @return The boolean, which has been created by the supplier + */ + public static double getAsDouble(final FailableDoubleSupplier supplier) { + try { + return supplier.getAsDouble(); + } catch (final Throwable t) { + throw rethrow(t); + } + } + + /** + * Invokes an int supplier, and returns the result. + * + * @param supplier The int supplier to invoke. + * @param The type of checked exception, which the supplier can throw. + * @return The boolean, which has been created by the supplier + */ + public static int getAsInt(final FailableIntSupplier supplier) { + try { + return supplier.getAsInt(); + } catch (final Throwable t) { + throw rethrow(t); + } + } + + /** + * Invokes a long supplier, and returns the result. + * + * @param supplier The long supplier to invoke. + * @param The type of checked exception, which the supplier can throw. + * @return The boolean, which has been created by the supplier + */ + public static long getAsLong(final FailableLongSupplier supplier) { + try { + return supplier.getAsLong(); + } catch (final Throwable t) { + throw rethrow(t); + } + } + + /** + *

      + * Rethrows a {@link Throwable} as an unchecked exception. If the argument is already unchecked, namely a + * {@code RuntimeException} or {@code Error} then the argument will be rethrown without modification. If the + * exception is {@code IOException} then it will be wrapped into a {@code UncheckedIOException}. In every other + * cases the exception will be wrapped into a {@code + * UndeclaredThrowableException} + *

      + * + *

      + * Note that there is a declared return type for this method, even though it never returns. The reason for that is + * to support the usual pattern: + *

      + * + *
      +     * throw rethrow(myUncheckedException);
      +     * 
      + * + *

      + * instead of just calling the method. This pattern may help the Java compiler to recognize that at that point an + * exception will be thrown and the code flow analysis will not demand otherwise mandatory commands that could + * follow the method call, like a {@code return} statement from a value returning method. + *

      + * + * @param throwable The throwable to rethrow ossibly wrapped into an unchecked exception + * @return Never returns anything, this method never terminates normally. + */ + public static RuntimeException rethrow(final Throwable throwable) { + Objects.requireNonNull(throwable, "throwable"); + if (throwable instanceof RuntimeException) { + throw (RuntimeException) throwable; + } else if (throwable instanceof Error) { + throw (Error) throwable; + } else if (throwable instanceof IOException) { + throw new UncheckedIOException((IOException) throwable); + } else { + throw new UndeclaredThrowableException(throwable); + } + } + + /** + * Runs a runnable and rethrows any exception as a {@link RuntimeException}. + * + * @param runnable The runnable to run + * @param the type of checked exception the runnable may throw + */ + public static void run(final FailableRunnable runnable) { + try { + runnable.run(); + } catch (final Throwable t) { + throw rethrow(t); + } + } + + /** + * Converts the given collection into a {@link FailableStream}. The {@link FailableStream} consists of the + * collections elements. Shortcut for + * + *
      +     * Functions.stream(collection.stream());
      +     * 
      + * + * @param collection The collection, which is being converted into a {@link FailableStream}. + * @param The collections element type. (In turn, the result streams element type.) + * @return The created {@link FailableStream}. + */ + public static FailableStream stream(final Collection collection) { + return new FailableStream<>(collection.stream()); + } + + /** + * Converts the given stream into a {@link FailableStream}. The {@link FailableStream} consists of the same + * elements, than the input stream. However, failable lambdas, like {@link FailablePredicate}, + * {@link FailableFunction}, and {@link FailableConsumer} may be applied, rather than {@link Predicate}, + * {@link Function}, {@link Consumer}, etc. + * + * @param stream The stream, which is being converted into a {@link FailableStream}. + * @param The streams element type. + * @return The created {@link FailableStream}. + */ + public static FailableStream stream(final Stream stream) { + return new FailableStream<>(stream); + } + + /** + * Tests a predicate and rethrows any exception as a {@link RuntimeException}. + * + * @param predicate the predicate to test + * @param object1 the first input to test by {@code predicate} + * @param object2 the second input to test by {@code predicate} + * @param the type of the first argument the predicate tests + * @param the type of the second argument the predicate tests + * @param the type of checked exception the predicate may throw + * @return the boolean value returned by the predicate + */ + public static boolean test(final FailableBiPredicate predicate, + final O1 object1, final O2 object2) { + return get(() -> predicate.test(object1, object2)); + } + + /** + * Tests a predicate and rethrows any exception as a {@link RuntimeException}. + * + * @param predicate the predicate to test + * @param object the input to test by {@code predicate} + * @param the type of argument the predicate tests + * @param the type of checked exception the predicate may throw + * @return the boolean value returned by the predicate + */ + public static boolean test(final FailablePredicate predicate, final O object) { + return get(() -> predicate.test(object)); + } + + /** + * A simple try-with-resources implementation, that can be used, if your objects do not implement the + * {@link AutoCloseable} interface. The method executes the {@code action}. The method guarantees, that all + * the {@code resources} are being executed, in the given order, afterwards, and regardless of success, or failure. + * If either the original action, or any of the resource action fails, then the first failure (AKA + * {@link Throwable} is rethrown. Example use: + * + *
      +     *     {@code
      +     *     final FileInputStream fis = new FileInputStream("my.file");
      +     *     Functions.tryWithResources(useInputStream(fis), null, () -> fis.close());
      +     * }
      +     * 
      + * + * @param action The action to execute. This object will always be invoked. + * @param errorHandler An optional error handler, which will be invoked finally, if any error occurred. The error + * handler will receive the first error, AKA {@link Throwable}. + * @param resources The resource actions to execute. All resource actions will be invoked, in the given + * order. A resource action is an instance of {@link FailableRunnable}, which will be executed. + * @see #tryWithResources(FailableRunnable, FailableRunnable...) + */ + @SafeVarargs + public static void tryWithResources(final FailableRunnable action, + final FailableConsumer errorHandler, + final FailableRunnable... resources) { + final FailableConsumer actualErrorHandler; + if (errorHandler == null) { + actualErrorHandler = Failable::rethrow; + } else { + actualErrorHandler = errorHandler; + } + if (resources != null) { + for (final FailableRunnable failableRunnable : resources) { + Objects.requireNonNull(failableRunnable, "runnable"); + } + } + Throwable th = null; + try { + action.run(); + } catch (final Throwable t) { + th = t; + } + if (resources != null) { + for (final FailableRunnable runnable : resources) { + try { + runnable.run(); + } catch (final Throwable t) { + if (th == null) { + th = t; + } + } + } + } + if (th != null) { + try { + actualErrorHandler.accept(th); + } catch (final Throwable t) { + throw rethrow(t); + } + } + } + + /** + * A simple try-with-resources implementation, that can be used, if your objects do not implement the + * {@link AutoCloseable} interface. The method executes the {@code action}. The method guarantees, that all + * the {@code resources} are being executed, in the given order, afterwards, and regardless of success, or failure. + * If either the original action, or any of the resource action fails, then the first failure (AKA + * {@link Throwable} is rethrown. Example use: + * + *
      +     *     {@code
      +     *     final FileInputStream fis = new FileInputStream("my.file");
      +     *     Functions.tryWithResources(useInputStream(fis), () -> fis.close());
      +     * }
      +     * 
      + * + * @param action The action to execute. This object will always be invoked. + * @param resources The resource actions to execute. All resource actions will be invoked, in the given + * order. A resource action is an instance of {@link FailableRunnable}, which will be executed. + * @see #tryWithResources(FailableRunnable, FailableConsumer, FailableRunnable...) + */ + @SafeVarargs + public static void tryWithResources(final FailableRunnable action, + final FailableRunnable... resources) { + tryWithResources(action, null, resources); + } + + private Failable() { + // empty + } + +} diff --git a/src/main/java/org/apache/commons/lang3/function/FailableBiConsumer.java b/src/main/java/org/apache/commons/lang3/function/FailableBiConsumer.java new file mode 100644 index 00000000000..cd9bedebdc1 --- /dev/null +++ b/src/main/java/org/apache/commons/lang3/function/FailableBiConsumer.java @@ -0,0 +1,41 @@ +/* + * 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.function; + +import java.util.function.BiConsumer; + +/** + * A functional interface like {@link BiConsumer} that declares a {@code Throwable}. + * + * @param Consumed type 1. + * @param Consumed type 2. + * @param Thrown exception. + * @since 3.11 + */ +@FunctionalInterface +public interface FailableBiConsumer { + + /** + * Accepts the consumer. + * + * @param object1 the first parameter for the consumable to accept + * @param object2 the second parameter for the consumable to accept + * @throws T Thrown when the consumer fails. + */ + void accept(O1 object1, O2 object2) throws T; +} diff --git a/src/main/java/org/apache/commons/lang3/function/FailableBiFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableBiFunction.java new file mode 100644 index 00000000000..ccb87c1ccf0 --- /dev/null +++ b/src/main/java/org/apache/commons/lang3/function/FailableBiFunction.java @@ -0,0 +1,43 @@ +/* + * 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.function; + +import java.util.function.BiFunction; + +/** + * A functional interface like {@link BiFunction} that declares a {@code Throwable}. + * + * @param Input type 1. + * @param Input type 2. + * @param Return type. + * @param Thrown exception. + * @since 3.11 + */ +@FunctionalInterface +public interface FailableBiFunction { + + /** + * Applies this function. + * + * @param input1 the first input for the function + * @param input2 the second input for the function + * @return the result of the function + * @throws T Thrown when the function fails. + */ + R apply(O1 input1, O2 input2) throws T; +} diff --git a/src/main/java/org/apache/commons/lang3/function/FailableBiPredicate.java b/src/main/java/org/apache/commons/lang3/function/FailableBiPredicate.java new file mode 100644 index 00000000000..725588056e1 --- /dev/null +++ b/src/main/java/org/apache/commons/lang3/function/FailableBiPredicate.java @@ -0,0 +1,42 @@ +/* + * 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.function; + +import java.util.function.BiPredicate; + +/** + * A functional interface like {@link BiPredicate} that declares a {@code Throwable}. + * + * @param Predicate type 1. + * @param Predicate type 2. + * @param Thrown exception. + * @since 3.11 + */ +@FunctionalInterface +public interface FailableBiPredicate { + + /** + * Tests the predicate. + * + * @param object1 the first object to test the predicate on + * @param object2 the second object to test the predicate on + * @return the predicate's evaluation + * @throws T if the predicate fails + */ + boolean test(O1 object1, O2 object2) throws T; +} diff --git a/src/main/java/org/apache/commons/lang3/function/FailableCallable.java b/src/main/java/org/apache/commons/lang3/function/FailableCallable.java new file mode 100644 index 00000000000..5d0d637d445 --- /dev/null +++ b/src/main/java/org/apache/commons/lang3/function/FailableCallable.java @@ -0,0 +1,37 @@ +/* + * 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.function; + +/** + * A functional interface like {@link java.util.concurrent.Callable} that declares a {@code Throwable}. + * + * @param Return type. + * @param Thrown exception. + * @since 3.11 + */ +@FunctionalInterface +public interface FailableCallable { + + /** + * Calls the callable. + * + * @return The value returned from the callable + * @throws T if the callable fails + */ + R call() throws T; +} diff --git a/src/main/java/org/apache/commons/lang3/function/FailableConsumer.java b/src/main/java/org/apache/commons/lang3/function/FailableConsumer.java new file mode 100644 index 00000000000..f969dc167ac --- /dev/null +++ b/src/main/java/org/apache/commons/lang3/function/FailableConsumer.java @@ -0,0 +1,39 @@ +/* + * 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.function; + +import java.util.function.Consumer; + +/** + * A functional interface like {@link Consumer} that declares a {@code Throwable}. + * + * @param Consumed type 1. + * @param Thrown exception. + * @since 3.11 + */ +@FunctionalInterface +public interface FailableConsumer { + + /** + * Accepts the consumer. + * + * @param object the parameter for the consumable to accept + * @throws T Thrown when the consumer fails. + */ + void accept(O object) throws T; +} diff --git a/src/main/java/org/apache/commons/lang3/function/FailableFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableFunction.java new file mode 100644 index 00000000000..9df6f7100a0 --- /dev/null +++ b/src/main/java/org/apache/commons/lang3/function/FailableFunction.java @@ -0,0 +1,41 @@ +/* + * 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.function; + +import java.util.function.Function; + +/** + * A functional interface like {@link Function} that declares a {@code Throwable}. + * + * @param Input type 1. + * @param Return type. + * @param Thrown exception. + * @since 3.11 + */ +@FunctionalInterface +public interface FailableFunction { + + /** + * Applies this function. + * + * @param input the input for the function + * @return the result of the function + * @throws T Thrown when the function fails. + */ + R apply(I input) throws T; +} \ No newline at end of file diff --git a/src/main/java/org/apache/commons/lang3/function/FailablePredicate.java b/src/main/java/org/apache/commons/lang3/function/FailablePredicate.java new file mode 100644 index 00000000000..64389e8e46b --- /dev/null +++ b/src/main/java/org/apache/commons/lang3/function/FailablePredicate.java @@ -0,0 +1,40 @@ +/* + * 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.function; + +import java.util.function.Predicate; + +/** + * A functional interface like {@link Predicate} that declares a {@code Throwable}. + * + * @param Predicate type 1. + * @param Thrown exception. + * @since 3.11 + */ +@FunctionalInterface +public interface FailablePredicate { + + /** + * Tests the predicate. + * + * @param object the object to test the predicate on + * @return the predicate's evaluation + * @throws T if the predicate fails + */ + boolean test(I object) throws T; +} \ No newline at end of file diff --git a/src/main/java/org/apache/commons/lang3/function/FailableRunnable.java b/src/main/java/org/apache/commons/lang3/function/FailableRunnable.java new file mode 100644 index 00000000000..2cce9e8e6b2 --- /dev/null +++ b/src/main/java/org/apache/commons/lang3/function/FailableRunnable.java @@ -0,0 +1,35 @@ +/* + * 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.function; + +/** + * A functional interface like {@link Runnable} that declares a {@code Throwable}. + * + * @param Thrown exception. + * @since 3.11 + */ +@FunctionalInterface +public interface FailableRunnable { + + /** + * Runs the function. + * + * @throws T Thrown when the function fails. + */ + void run() throws T; +} \ No newline at end of file diff --git a/src/main/java/org/apache/commons/lang3/function/FailableSupplier.java b/src/main/java/org/apache/commons/lang3/function/FailableSupplier.java new file mode 100644 index 00000000000..a07bd6a16f7 --- /dev/null +++ b/src/main/java/org/apache/commons/lang3/function/FailableSupplier.java @@ -0,0 +1,39 @@ +/* + * 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.function; + +import java.util.function.Supplier; + +/** + * A functional interface like {@link Supplier} that declares a {@code Throwable}. + * + * @param Return type. + * @param Thrown exception. + * @since 3.11 + */ +@FunctionalInterface +public interface FailableSupplier { + + /** + * Supplies an object + * + * @return a result + * @throws T if the supplier fails + */ + R get() throws T; +} \ No newline at end of file diff --git a/src/test/java/org/apache/commons/lang3/LocksTest.java b/src/test/java/org/apache/commons/lang3/LocksTest.java index 18a81d9dbff..b3c805e3ebe 100644 --- a/src/test/java/org/apache/commons/lang3/LocksTest.java +++ b/src/test/java/org/apache/commons/lang3/LocksTest.java @@ -20,8 +20,8 @@ import java.util.function.LongConsumer; -import org.apache.commons.lang3.Functions.FailableConsumer; import org.apache.commons.lang3.Locks.Lock; +import org.apache.commons.lang3.function.FailableConsumer; import org.junit.jupiter.api.Test; class LocksTest { From fc686a48ef60a2282214a7102830f94cdcf16e2f Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Wed, 17 Jun 2020 16:53:15 -0400 Subject: [PATCH 0159/3230] We have a concurrent package, and JRE locks live in a similar package, so let's put our new code in there. --- .../org/apache/commons/lang3/{ => concurrent}/Locks.java | 7 +++++-- .../apache/commons/lang3/{ => concurrent}/LocksTest.java | 5 +++-- 2 files changed, 8 insertions(+), 4 deletions(-) rename src/main/java/org/apache/commons/lang3/{ => concurrent}/Locks.java (96%) rename src/test/java/org/apache/commons/lang3/{ => concurrent}/LocksTest.java (95%) diff --git a/src/main/java/org/apache/commons/lang3/Locks.java b/src/main/java/org/apache/commons/lang3/concurrent/Locks.java similarity index 96% rename from src/main/java/org/apache/commons/lang3/Locks.java rename to src/main/java/org/apache/commons/lang3/concurrent/Locks.java index 1fabaf38e42..99cea4dfbb4 100644 --- a/src/main/java/org/apache/commons/lang3/Locks.java +++ b/src/main/java/org/apache/commons/lang3/concurrent/Locks.java @@ -14,7 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.commons.lang3; +package org.apache.commons.lang3.concurrent; import java.util.Objects; import java.util.concurrent.locks.StampedLock; @@ -24,7 +24,8 @@ import org.apache.commons.lang3.function.FailableFunction; -/** Utility class for working with {@link java.util.concurrent.locks.Lock locked objects}. Locked objects are an +/** + * Utility class for working with {@link java.util.concurrent.locks.Lock locked objects}. Locked objects are an * alternative to synchronization. * * Locking is preferable, if there is a distinction between read access (multiple threads may have read @@ -64,8 +65,10 @@ * lock.runWriteLocked((ps) -> { ps.write(buffer); ps.println(); }); * } * + * @since 3.11 */ public class Locks { + public static class Lock { private final O lockedObject; private final StampedLock lock = new StampedLock(); diff --git a/src/test/java/org/apache/commons/lang3/LocksTest.java b/src/test/java/org/apache/commons/lang3/concurrent/LocksTest.java similarity index 95% rename from src/test/java/org/apache/commons/lang3/LocksTest.java rename to src/test/java/org/apache/commons/lang3/concurrent/LocksTest.java index b3c805e3ebe..eaba4e93f1d 100644 --- a/src/test/java/org/apache/commons/lang3/LocksTest.java +++ b/src/test/java/org/apache/commons/lang3/concurrent/LocksTest.java @@ -14,13 +14,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.commons.lang3; +package org.apache.commons.lang3.concurrent; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.function.LongConsumer; -import org.apache.commons.lang3.Locks.Lock; +import org.apache.commons.lang3.concurrent.Locks; +import org.apache.commons.lang3.concurrent.Locks.Lock; import org.apache.commons.lang3.function.FailableConsumer; import org.junit.jupiter.api.Test; From e22a5ea87addb8d786925a46d74d8dfb2a6c41d2 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Wed, 17 Jun 2020 17:13:40 -0400 Subject: [PATCH 0160/3230] Javadoc. --- .../org/apache/commons/lang3/Functions.java | 21 +++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/Functions.java b/src/main/java/org/apache/commons/lang3/Functions.java index 626928c76b8..7c9ec3d45d5 100644 --- a/src/main/java/org/apache/commons/lang3/Functions.java +++ b/src/main/java/org/apache/commons/lang3/Functions.java @@ -31,8 +31,6 @@ import java.util.function.Supplier; import java.util.stream.Stream; -import org.apache.commons.lang3.Streams.FailableStream; -import org.apache.commons.lang3.function.Failable; import org.apache.commons.lang3.function.FailableBooleanSupplier; import org.apache.commons.lang3.function.FailableDoubleBinaryOperator; import org.apache.commons.lang3.function.FailableDoubleConsumer; @@ -41,6 +39,7 @@ import org.apache.commons.lang3.function.FailableIntSupplier; import org.apache.commons.lang3.function.FailableLongConsumer; import org.apache.commons.lang3.function.FailableLongSupplier; +import org.apache.commons.lang3.stream.Streams.FailableStream; /** * This class provides utility functions, and classes for working with the {@code java.util.function} package, or more @@ -87,7 +86,9 @@ public class Functions { * @param Consumed type 1. * @param Consumed type 2. * @param Thrown exception. + * @deprecated Use {@link org.apache.commons.lang3.function.FailableBiConsumer}. */ + @Deprecated @FunctionalInterface public interface FailableBiConsumer { @@ -110,7 +111,9 @@ public interface FailableBiConsumer { * @param Input type 2. * @param Return type. * @param Thrown exception. + * @deprecated Use {@link org.apache.commons.lang3.function.FailableBiFunction}. */ + @Deprecated @FunctionalInterface public interface FailableBiFunction { @@ -133,7 +136,9 @@ public interface FailableBiFunction { * @param Predicate type 1. * @param Predicate type 2. * @param Thrown exception. + * @deprecated Use {@link org.apache.commons.lang3.function.FailableBiPredicate}. */ + @Deprecated @FunctionalInterface public interface FailableBiPredicate { @@ -155,7 +160,9 @@ public interface FailableBiPredicate { * * @param Return type. * @param Thrown exception. + * @deprecated Use {@link org.apache.commons.lang3.function.FailableCallable}. */ + @Deprecated @FunctionalInterface public interface FailableCallable { @@ -175,7 +182,9 @@ public interface FailableCallable { * * @param Consumed type 1. * @param Thrown exception. + * @deprecated Use {@link org.apache.commons.lang3.function.FailableConsumer}. */ + @Deprecated @FunctionalInterface public interface FailableConsumer { @@ -196,7 +205,9 @@ public interface FailableConsumer { * @param Input type 1. * @param Return type. * @param Thrown exception. + * @deprecated Use {@link org.apache.commons.lang3.function.FailableFunction}. */ + @Deprecated @FunctionalInterface public interface FailableFunction { @@ -217,7 +228,9 @@ public interface FailableFunction { * * @param Predicate type 1. * @param Thrown exception. + * @deprecated Use {@link org.apache.commons.lang3.function.FailablePredicate}. */ + @Deprecated @FunctionalInterface public interface FailablePredicate { @@ -237,7 +250,9 @@ public interface FailablePredicate { *

      TODO for 4.0: Move to org.apache.commons.lang3.function.

      * * @param Thrown exception. + * @deprecated Use {@link org.apache.commons.lang3.function.FailableRunnable}. */ + @Deprecated @FunctionalInterface public interface FailableRunnable { @@ -256,7 +271,9 @@ public interface FailableRunnable { * * @param Return type. * @param Thrown exception. + * @deprecated Use {@link org.apache.commons.lang3.function.FailableSupplier}. */ + @Deprecated @FunctionalInterface public interface FailableSupplier { From 724c00f0e86926e758b56bea03cdc517c475ad6a Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Wed, 17 Jun 2020 17:16:19 -0400 Subject: [PATCH 0161/3230] Follow current style: @Test methods are public. --- .../apache/commons/lang3/FunctionsTest.java | 66 +++++++++---------- 1 file changed, 33 insertions(+), 33 deletions(-) diff --git a/src/test/java/org/apache/commons/lang3/FunctionsTest.java b/src/test/java/org/apache/commons/lang3/FunctionsTest.java index 3fec18e0222..3b2aa0e2625 100644 --- a/src/test/java/org/apache/commons/lang3/FunctionsTest.java +++ b/src/test/java/org/apache/commons/lang3/FunctionsTest.java @@ -45,7 +45,7 @@ import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -class FunctionsTest { +public class FunctionsTest { public static class CloseableObject { private boolean closed; @@ -268,7 +268,7 @@ public void testObjLong(T object, long i) throws Throwable { } @Test - void testAcceptBiConsumer() { + public void testAcceptBiConsumer() { final IllegalStateException ise = new IllegalStateException(); final Testable testable = new Testable<>(null); Throwable e = assertThrows(IllegalStateException.class, () -> Functions.accept(Testable::test, testable, ise)); @@ -290,7 +290,7 @@ void testAcceptBiConsumer() { } @Test - void testAcceptConsumer() { + public void testAcceptConsumer() { final IllegalStateException ise = new IllegalStateException(); final Testable testable = new Testable<>(ise); Throwable e = assertThrows(IllegalStateException.class, () -> Functions.accept(Testable::test, testable)); @@ -313,7 +313,7 @@ void testAcceptConsumer() { } @Test - void testAcceptDoubleConsumer() { + public void testAcceptDoubleConsumer() { final IllegalStateException ise = new IllegalStateException(); final Testable testable = new Testable<>(ise); Throwable e = assertThrows(IllegalStateException.class, () -> Functions.accept(testable::testDouble, 1d)); @@ -340,7 +340,7 @@ void testAcceptDoubleConsumer() { } @Test - void testAcceptIntConsumer() { + public void testAcceptIntConsumer() { final IllegalStateException ise = new IllegalStateException(); final Testable testable = new Testable<>(ise); Throwable e = assertThrows(IllegalStateException.class, () -> Functions.accept(testable::testInt, 1)); @@ -367,7 +367,7 @@ void testAcceptIntConsumer() { } @Test - void testAcceptLongConsumer() { + public void testAcceptLongConsumer() { final IllegalStateException ise = new IllegalStateException(); final Testable testable = new Testable<>(ise); Throwable e = assertThrows(IllegalStateException.class, () -> Functions.accept(testable::testLong, 1L)); @@ -394,7 +394,7 @@ void testAcceptLongConsumer() { } @Test - void testAcceptObjDoubleConsumer() { + public void testAcceptObjDoubleConsumer() { final IllegalStateException ise = new IllegalStateException(); final Testable testable = new Testable<>(ise); Throwable e = assertThrows(IllegalStateException.class, @@ -426,7 +426,7 @@ void testAcceptObjDoubleConsumer() { } @Test - void testAcceptObjIntConsumer() { + public void testAcceptObjIntConsumer() { final IllegalStateException ise = new IllegalStateException(); final Testable testable = new Testable<>(ise); Throwable e = assertThrows(IllegalStateException.class, () -> Functions.accept(testable::testObjInt, "X", 1)); @@ -457,7 +457,7 @@ void testAcceptObjIntConsumer() { } @Test - void testAcceptObjLongConsumer() { + public void testAcceptObjLongConsumer() { final IllegalStateException ise = new IllegalStateException(); final Testable testable = new Testable<>(ise); Throwable e = assertThrows(IllegalStateException.class, () -> Functions.accept(testable::testObjLong, "X", 1L)); @@ -550,7 +550,7 @@ public void testApplyFunction() { } @Test - void testAsCallable() { + public void testAsCallable() { FailureOnOddInvocations.invocations = 0; final FailableCallable failableCallable = FailureOnOddInvocations::new; final Callable callable = Functions.asCallable(failableCallable); @@ -569,7 +569,7 @@ void testAsCallable() { } @Test - void testAsConsumer() { + public void testAsConsumer() { final IllegalStateException ise = new IllegalStateException(); final Testable testable = new Testable<>(ise); final Consumer> consumer = Functions.asConsumer(Testable::test); @@ -593,7 +593,7 @@ void testAsConsumer() { } @Test - void testAsRunnable() { + public void testAsRunnable() { FailureOnOddInvocations.invocations = 0; final Runnable runnable = Functions.asRunnable(FailureOnOddInvocations::new); final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, runnable::run); @@ -620,7 +620,7 @@ public void testAsSupplier() { } @Test - void testBiConsumer() { + public void testBiConsumer() { final IllegalStateException ise = new IllegalStateException(); final Testable testable = new Testable<>(null); final FailableBiConsumer, Throwable, Throwable> failableBiConsumer = (t, th) -> { @@ -690,7 +690,7 @@ public void testBiPredicate() { } @Test - void testCallable() { + public void testCallable() { FailureOnOddInvocations.invocations = 0; final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, () -> Functions.run(FailureOnOddInvocations::new)); @@ -889,7 +889,7 @@ public void testPredicate() { } @Test - void testRunnable() { + public void testRunnable() { FailureOnOddInvocations.invocations = 0; final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, () -> Functions.run(FailureOnOddInvocations::new)); @@ -907,7 +907,7 @@ void testRunnable() { * Object and Throwable. */ @Test - void testThrows_FailableBiConsumer_Object_Throwable() { + public void testThrows_FailableBiConsumer_Object_Throwable() { new Functions.FailableBiConsumer() { @Override @@ -922,7 +922,7 @@ public void accept(Object object1, Object object2) throws Throwable { * generic test types. */ @Test - void testThrows_FailableBiConsumer_String_IOException() { + public void testThrows_FailableBiConsumer_String_IOException() { new Functions.FailableBiConsumer() { @Override @@ -938,7 +938,7 @@ public void accept(String object1, String object2) throws IOException { * Object and Throwable. */ @Test - void testThrows_FailableBiFunction_Object_Throwable() { + public void testThrows_FailableBiFunction_Object_Throwable() { new Functions.FailableBiFunction() { @Override @@ -953,7 +953,7 @@ public Object apply(Object input1, Object input2) throws Throwable { * generic test types. */ @Test - void testThrows_FailableBiFunction_String_IOException() { + public void testThrows_FailableBiFunction_String_IOException() { new Functions.FailableBiFunction() { @Override @@ -968,7 +968,7 @@ public String apply(String input1, String input2) throws IOException { * Object and Throwable. */ @Test - void testThrows_FailableBiPredicate_Object_Throwable() { + public void testThrows_FailableBiPredicate_Object_Throwable() { new Functions.FailableBiPredicate() { @Override @@ -983,7 +983,7 @@ public boolean test(Object object1, Object object2) throws Throwable { * generic test types. */ @Test - void testThrows_FailableBiPredicate_String_IOException() { + public void testThrows_FailableBiPredicate_String_IOException() { new Functions.FailableBiPredicate() { @Override @@ -998,7 +998,7 @@ public boolean test(String object1, String object2) throws IOException { * Object and Throwable. */ @Test - void testThrows_FailableCallable_Object_Throwable() { + public void testThrows_FailableCallable_Object_Throwable() { new Functions.FailableCallable() { @Override @@ -1013,7 +1013,7 @@ public Object call() throws Throwable { * generic test types. */ @Test - void testThrows_FailableCallable_String_IOException() { + public void testThrows_FailableCallable_String_IOException() { new Functions.FailableCallable() { @Override @@ -1028,7 +1028,7 @@ public String call() throws IOException { * Object and Throwable. */ @Test - void testThrows_FailableConsumer_Object_Throwable() { + public void testThrows_FailableConsumer_Object_Throwable() { new Functions.FailableConsumer() { @Override @@ -1044,7 +1044,7 @@ public void accept(Object object) throws Throwable { * generic test types. */ @Test - void testThrows_FailableConsumer_String_IOException() { + public void testThrows_FailableConsumer_String_IOException() { new Functions.FailableConsumer() { @Override @@ -1060,7 +1060,7 @@ public void accept(String object) throws IOException { * Object and Throwable. */ @Test - void testThrows_FailableFunction_Object_Throwable() { + public void testThrows_FailableFunction_Object_Throwable() { new Functions.FailableFunction() { @Override @@ -1075,7 +1075,7 @@ public Object apply(Object input) throws Throwable { * generic test types. */ @Test - void testThrows_FailableFunction_String_IOException() { + public void testThrows_FailableFunction_String_IOException() { new Functions.FailableFunction() { @Override @@ -1090,7 +1090,7 @@ public String apply(String input) throws IOException { * Object and Throwable. */ @Test - void testThrows_FailablePredicate_Object_Throwable() { + public void testThrows_FailablePredicate_Object_Throwable() { new Functions.FailablePredicate() { @Override @@ -1105,7 +1105,7 @@ public boolean test(Object object) throws Throwable { * generic test types. */ @Test - void testThrows_FailablePredicate_String_IOException() { + public void testThrows_FailablePredicate_String_IOException() { new Functions.FailablePredicate() { @Override @@ -1120,7 +1120,7 @@ public boolean test(String object) throws IOException { * Object and Throwable. */ @Test - void testThrows_FailableRunnable_Object_Throwable() { + public void testThrows_FailableRunnable_Object_Throwable() { new Functions.FailableRunnable() { @Override @@ -1136,7 +1136,7 @@ public void run() throws Throwable { * generic test types. */ @Test - void testThrows_FailableRunnable_String_IOException() { + public void testThrows_FailableRunnable_String_IOException() { new Functions.FailableRunnable() { @Override @@ -1151,7 +1151,7 @@ public void run() throws IOException { * Object and Throwable. */ @Test - void testThrows_FailableSupplier_Object_Throwable() { + public void testThrows_FailableSupplier_Object_Throwable() { new Functions.FailableSupplier() { @Override @@ -1166,7 +1166,7 @@ public Object get() throws Throwable { * generic test types. */ @Test - void testThrows_FailableSupplier_String_IOException() { + public void testThrows_FailableSupplier_String_IOException() { new Functions.FailableSupplier() { @Override From 8fcefb4f98856998d857e90f73bb88af043ef3b8 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Wed, 17 Jun 2020 17:37:14 -0400 Subject: [PATCH 0162/3230] Centralize stream code in our own 'stream' package as a parallel to the JRE's java.util.stream package. - Re-implement use of failable function interfaces based on our function package. - Deprecate old class. - Remove trainling whitespace. --- .../org/apache/commons/lang3/Functions.java | 2 +- .../org/apache/commons/lang3/Streams.java | 8 + .../commons/lang3/concurrent/Locks.java | 2 +- .../commons/lang3/function/Failable.java | 2 +- .../apache/commons/lang3/stream/Streams.java | 492 ++++++++++++++++++ .../org/apache/commons/lang3/StreamsTest.java | 16 +- .../commons/lang3/stream/StreamsTest.java | 187 +++++++ 7 files changed, 698 insertions(+), 11 deletions(-) create mode 100644 src/main/java/org/apache/commons/lang3/stream/Streams.java create mode 100644 src/test/java/org/apache/commons/lang3/stream/StreamsTest.java diff --git a/src/main/java/org/apache/commons/lang3/Functions.java b/src/main/java/org/apache/commons/lang3/Functions.java index 7c9ec3d45d5..4cf9d5589b2 100644 --- a/src/main/java/org/apache/commons/lang3/Functions.java +++ b/src/main/java/org/apache/commons/lang3/Functions.java @@ -31,6 +31,7 @@ import java.util.function.Supplier; import java.util.stream.Stream; +import org.apache.commons.lang3.Streams.FailableStream; import org.apache.commons.lang3.function.FailableBooleanSupplier; import org.apache.commons.lang3.function.FailableDoubleBinaryOperator; import org.apache.commons.lang3.function.FailableDoubleConsumer; @@ -39,7 +40,6 @@ import org.apache.commons.lang3.function.FailableIntSupplier; import org.apache.commons.lang3.function.FailableLongConsumer; import org.apache.commons.lang3.function.FailableLongSupplier; -import org.apache.commons.lang3.stream.Streams.FailableStream; /** * This class provides utility functions, and classes for working with the {@code java.util.function} package, or more diff --git a/src/main/java/org/apache/commons/lang3/Streams.java b/src/main/java/org/apache/commons/lang3/Streams.java index 125aefec9fd..c6afd0a27b1 100644 --- a/src/main/java/org/apache/commons/lang3/Streams.java +++ b/src/main/java/org/apache/commons/lang3/Streams.java @@ -62,14 +62,18 @@ * @see Stream * @see Functions * @since 3.10 + * @deprecated Use {@link org.apache.commons.lang3.stream.Streams}. */ +@Deprecated public class Streams { /** * A reduced, and simplified version of a {@link Stream} with * failable method signatures. * @param The streams element type. + * @deprecated Use {@link org.apache.commons.lang3.stream.Streams.FailableStream}. */ + @Deprecated public static class FailableStream { private Stream stream; @@ -435,6 +439,10 @@ public static FailableStream stream(final Collection stream) { return stream(stream.stream()); } + /** + * @deprecated Use {@link org.apache.commons.lang3.stream.Streams.ArrayCollector}. + */ + @Deprecated public static class ArrayCollector implements Collector, O[]> { private static final Set characteristics = Collections.emptySet(); private final Class elementType; diff --git a/src/main/java/org/apache/commons/lang3/concurrent/Locks.java b/src/main/java/org/apache/commons/lang3/concurrent/Locks.java index 99cea4dfbb4..e96f36bc165 100644 --- a/src/main/java/org/apache/commons/lang3/concurrent/Locks.java +++ b/src/main/java/org/apache/commons/lang3/concurrent/Locks.java @@ -24,7 +24,7 @@ import org.apache.commons.lang3.function.FailableFunction; -/** +/** * Utility class for working with {@link java.util.concurrent.locks.Lock locked objects}. Locked objects are an * alternative to synchronization. * diff --git a/src/main/java/org/apache/commons/lang3/function/Failable.java b/src/main/java/org/apache/commons/lang3/function/Failable.java index bcc3e29d561..9ecc2838876 100644 --- a/src/main/java/org/apache/commons/lang3/function/Failable.java +++ b/src/main/java/org/apache/commons/lang3/function/Failable.java @@ -32,7 +32,7 @@ import java.util.function.Supplier; import java.util.stream.Stream; -import org.apache.commons.lang3.Streams.FailableStream; +import org.apache.commons.lang3.stream.Streams.FailableStream; /** * This class provides utility functions, and classes for working with the {@code java.util.function} package, or more diff --git a/src/main/java/org/apache/commons/lang3/stream/Streams.java b/src/main/java/org/apache/commons/lang3/stream/Streams.java new file mode 100644 index 00000000000..1954432c7c0 --- /dev/null +++ b/src/main/java/org/apache/commons/lang3/stream/Streams.java @@ -0,0 +1,492 @@ +/* + * 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.stream; + +import java.lang.reflect.Array; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Set; +import java.util.function.BiConsumer; +import java.util.function.BinaryOperator; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.function.Supplier; +import java.util.stream.Collector; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.apache.commons.lang3.function.Failable; +import org.apache.commons.lang3.function.FailableConsumer; +import org.apache.commons.lang3.function.FailableFunction; +import org.apache.commons.lang3.function.FailablePredicate; + +/** + * Provides utility functions, and classes for working with the + * {@code java.util.stream} package, or more generally, with Java 8 lambdas. More + * specifically, it attempts to address the fact that lambdas are supposed + * not to throw Exceptions, at least not checked Exceptions, AKA instances + * of {@link Exception}. This enforces the use of constructs like + *
      + *     Consumer<java.lang.reflect.Method> consumer = (m) -> {
      + *         try {
      + *             m.invoke(o, args);
      + *         } catch (Throwable t) {
      + *             throw Failable.rethrow(t);
      + *         }
      + *    };
      + *    stream.forEach(consumer);
      + * 
      + * Using a {@link FailableStream}, this can be rewritten as follows: + *
      + *     Streams.failable(stream).forEach((m) -> m.invoke(o, args));
      + * 
      + * Obviously, the second version is much more concise and the spirit of + * Lambda expressions is met better than in the first version. + * + * @see Stream + * @see Failable + * @since 3.10 + */ +public class Streams { + + public static class ArrayCollector implements Collector, O[]> { + private static final Set characteristics = Collections.emptySet(); + private final Class elementType; + + public ArrayCollector(final Class elementType) { + this.elementType = elementType; + } + + @Override + public BiConsumer, O> accumulator() { + return List::add; + } + + @Override + public Set characteristics() { + return characteristics; + } + + @Override + public BinaryOperator> combiner() { + return (left, right) -> { + left.addAll(right); + return left; + }; + } + + @Override + public Function, O[]> finisher() { + return list -> { + @SuppressWarnings("unchecked") + final O[] array = (O[]) Array.newInstance(elementType, list.size()); + return list.toArray(array); + }; + } + + @Override + public Supplier> supplier() { + return ArrayList::new; + } +} + + /** + * A reduced, and simplified version of a {@link Stream} with + * failable method signatures. + * @param The streams element type. + */ + public static class FailableStream { + + private Stream stream; + private boolean terminated; + + /** + * Constructs a new instance with the given {@code stream}. + * @param stream The stream. + */ + public FailableStream(final Stream stream) { + this.stream = stream; + } + + /** + * Returns whether all elements of this stream match the provided predicate. + * May not evaluate the predicate on all elements if not necessary for + * determining the result. If the stream is empty then {@code true} is + * returned and the predicate is not evaluated. + * + *

      This is a short-circuiting terminal operation. + * + * \@apiNote + * This method evaluates the universal quantification of the + * predicate over the elements of the stream (for all x P(x)). If the + * stream is empty, the quantification is said to be vacuously + * satisfied and is always {@code true} (regardless of P(x)). + * + * @param predicate A non-interfering, stateless predicate to apply to + * elements of this stream + * @return {@code true} If either all elements of the stream match the + * provided predicate or the stream is empty, otherwise {@code false}. + */ + public boolean allMatch(final FailablePredicate predicate) { + assertNotTerminated(); + return stream().allMatch(Failable.asPredicate(predicate)); + } + + /** + * Returns whether any elements of this stream match the provided + * predicate. May not evaluate the predicate on all elements if not + * necessary for determining the result. If the stream is empty then + * {@code false} is returned and the predicate is not evaluated. + * + *

      This is a short-circuiting terminal operation. + * + * \@apiNote + * This method evaluates the existential quantification of the + * predicate over the elements of the stream (for some x P(x)). + * + * @param predicate A non-interfering, stateless predicate to apply to + * elements of this stream + * @return {@code true} if any elements of the stream match the provided + * predicate, otherwise {@code false} + */ + public boolean anyMatch(final FailablePredicate predicate) { + assertNotTerminated(); + return stream().anyMatch(Failable.asPredicate(predicate)); + } + + protected void assertNotTerminated() { + if (terminated) { + throw new IllegalStateException("This stream is already terminated."); + } + } + + /** + * Performs a mutable reduction operation on the elements of this stream using a + * {@code Collector}. A {@code Collector} + * encapsulates the functions used as arguments to + * {@link #collect(Supplier, BiConsumer, BiConsumer)}, allowing for reuse of + * collection strategies and composition of collect operations such as + * multiple-level grouping or partitioning. + * + *

      If the underlying stream is parallel, and the {@code Collector} + * is concurrent, and either the stream is unordered or the collector is + * unordered, then a concurrent reduction will be performed + * (see {@link Collector} for details on concurrent reduction.) + * + *

      This is a terminal operation. + * + *

      When executed in parallel, multiple intermediate results may be + * instantiated, populated, and merged so as to maintain isolation of + * mutable data structures. Therefore, even when executed in parallel + * with non-thread-safe data structures (such as {@code ArrayList}), no + * additional synchronization is needed for a parallel reduction. + * + * \@apiNote + * The following will accumulate strings into an ArrayList: + *

      {@code
      +             *     List asList = stringStream.collect(Collectors.toList());
      +             * }
      + * + *

      The following will classify {@code Person} objects by city: + *

      {@code
      +             *     Map> peopleByCity
      +             *         = personStream.collect(Collectors.groupingBy(Person::getCity));
      +             * }
      + * + *

      The following will classify {@code Person} objects by state and city, + * cascading two {@code Collector}s together: + *

      {@code
      +             *     Map>> peopleByStateAndCity
      +             *         = personStream.collect(Collectors.groupingBy(Person::getState,
      +             *                                                      Collectors.groupingBy(Person::getCity)));
      +             * }
      + * + * @param the type of the result + * @param
      the intermediate accumulation type of the {@code Collector} + * @param collector the {@code Collector} describing the reduction + * @return the result of the reduction + * @see #collect(Supplier, BiConsumer, BiConsumer) + * @see Collectors + */ + public R collect(final Collector collector) { + makeTerminated(); + return stream().collect(collector); + } + + /** + * Performs a mutable reduction operation on the elements of this FailableStream. + * A mutable reduction is one in which the reduced value is a mutable result + * container, such as an {@code ArrayList}, and elements are incorporated by updating + * the state of the result rather than by replacing the result. This produces a result equivalent to: + *
      {@code
      +             *     R result = supplier.get();
      +             *     for (T element : this stream)
      +             *         accumulator.accept(result, element);
      +             *     return result;
      +             * }
      + * + *

      Like {@link #reduce(Object, BinaryOperator)}, {@code collect} operations + * can be parallelized without requiring additional synchronization. + * + *

      This is a terminal operation. + * + * \@apiNote There are many existing classes in the JDK whose signatures are + * well-suited for use with method references as arguments to {@code collect()}. + * For example, the following will accumulate strings into an {@code ArrayList}: + *

      {@code
      +             *     List asList = stringStream.collect(ArrayList::new, ArrayList::add,
      +             *                                                ArrayList::addAll);
      +             * }
      + * + *

      The following will take a stream of strings and concatenates them into a + * single string: + *

      {@code
      +             *     String concat = stringStream.collect(StringBuilder::new, StringBuilder::append,
      +             *                                          StringBuilder::append)
      +             *                                 .toString();
      +             * }
      + * + * @param type of the result + * @param
      Type of the accumulator. + * @param pupplier a function that creates a new result container. For a + * parallel execution, this function may be called + * multiple times and must return a fresh value each time. + * @param accumulator An associative, non-interfering, stateless function for + * incorporating an additional element into a result + * @param combiner An associative, non-interfering, stateless + * function for combining two values, which must be compatible with the + * accumulator function + * @return The result of the reduction + */ + public R collect(final Supplier pupplier, final BiConsumer accumulator, final BiConsumer combiner) { + makeTerminated(); + return stream().collect(pupplier, accumulator, combiner); + } + + /** + * Returns a FailableStream consisting of the elements of this stream that match + * the given FailablePredicate. + * + *

      This is an intermediate operation. + * + * @param predicate a non-interfering, stateless predicate to apply to each + * element to determine if it should be included. + * @return the new stream + */ + public FailableStream filter(final FailablePredicate predicate){ + assertNotTerminated(); + stream = stream.filter(Failable.asPredicate(predicate)); + return this; + } + + /** + * Performs an action for each element of this stream. + * + *

      This is a terminal operation. + * + *

      The behavior of this operation is explicitly nondeterministic. + * For parallel stream pipelines, this operation does not + * guarantee to respect the encounter order of the stream, as doing so + * would sacrifice the benefit of parallelism. For any given element, the + * action may be performed at whatever time and in whatever thread the + * library chooses. If the action accesses shared state, it is + * responsible for providing the required synchronization. + * + * @param action a non-interfering action to perform on the elements + */ + public void forEach(final FailableConsumer action) { + makeTerminated(); + stream().forEach(Failable.asConsumer(action)); + } + + protected void makeTerminated() { + assertNotTerminated(); + terminated = true; + } + + /** + * Returns a stream consisting of the results of applying the given + * function to the elements of this stream. + * + *

      This is an intermediate operation. + * + * @param The element type of the new stream + * @param mapper A non-interfering, stateless function to apply to each element + * @return the new stream + */ + public FailableStream map(final FailableFunction mapper) { + assertNotTerminated(); + return new FailableStream<>(stream.map(Failable.asFunction(mapper))); + } + + /** + * Performs a reduction on the elements of this stream, using the provided + * identity value and an associative accumulation function, and returns + * the reduced value. This is equivalent to: + *

      {@code
      +             *     T result = identity;
      +             *     for (T element : this stream)
      +             *         result = accumulator.apply(result, element)
      +             *     return result;
      +             * }
      + * + * but is not constrained to execute sequentially. + * + *

      The {@code identity} value must be an identity for the accumulator + * function. This means that for all {@code t}, + * {@code accumulator.apply(identity, t)} is equal to {@code t}. + * The {@code accumulator} function must be an associative function. + * + *

      This is a terminal operation. + * + * \@apiNote Sum, min, max, average, and string concatenation are all special + * cases of reduction. Summing a stream of numbers can be expressed as: + * + *

      {@code
      +             *     Integer sum = integers.reduce(0, (a, b) -> a+b);
      +             * }
      + * + * or: + * + *
      {@code
      +             *     Integer sum = integers.reduce(0, Integer::sum);
      +             * }
      + * + *

      While this may seem a more roundabout way to perform an aggregation + * compared to simply mutating a running total in a loop, reduction + * operations parallelize more gracefully, without needing additional + * synchronization and with greatly reduced risk of data races. + * + * @param identity the identity value for the accumulating function + * @param accumulator an associative, non-interfering, stateless + * function for combining two values + * @return the result of the reduction + */ + public O reduce(final O identity, final BinaryOperator accumulator) { + makeTerminated(); + return stream().reduce(identity, accumulator); + } + + /** + * Converts the FailableStream into an equivalent stream. + * @return A stream, which will return the same elements, which this FailableStream would return. + */ + public Stream stream() { + return stream; + } + } + + /** + * Converts the given {@link Collection} into a {@link FailableStream}. + * This is basically a simplified, reduced version of the {@link Stream} + * class, with the same underlying element stream, except that failable + * objects, like {@link FailablePredicate}, {@link FailableFunction}, or + * {@link FailableConsumer} may be applied, instead of + * {@link Predicate}, {@link Function}, or {@link Consumer}. The idea is + * to rewrite a code snippet like this: + *

      +     *     final List<O> list;
      +     *     final Method m;
      +     *     final Function<O,String> mapper = (o) -> {
      +     *         try {
      +     *             return (String) m.invoke(o);
      +     *         } catch (Throwable t) {
      +     *             throw Failable.rethrow(t);
      +     *         }
      +     *     };
      +     *     final List<String> strList = list.stream()
      +     *         .map(mapper).collect(Collectors.toList());
      +     *  
      + * as follows: + *
      +     *     final List<O> list;
      +     *     final Method m;
      +     *     final List<String> strList = Failable.stream(list.stream())
      +     *         .map((o) -> (String) m.invoke(o)).collect(Collectors.toList());
      +     *  
      + * While the second version may not be quite as + * efficient (because it depends on the creation of additional, + * intermediate objects, of type FailableStream), it is much more + * concise, and readable, and meets the spirit of Lambdas better + * than the first version. + * @param The streams element type. + * @param stream The stream, which is being converted. + * @return The {@link FailableStream}, which has been created by + * converting the stream. + */ + public static FailableStream stream(final Collection stream) { + return stream(stream.stream()); + } + + /** + * Converts the given {@link Stream stream} into a {@link FailableStream}. + * This is basically a simplified, reduced version of the {@link Stream} + * class, with the same underlying element stream, except that failable + * objects, like {@link FailablePredicate}, {@link FailableFunction}, or + * {@link FailableConsumer} may be applied, instead of + * {@link Predicate}, {@link Function}, or {@link Consumer}. The idea is + * to rewrite a code snippet like this: + *
      +     *     final List<O> list;
      +     *     final Method m;
      +     *     final Function<O,String> mapper = (o) -> {
      +     *         try {
      +     *             return (String) m.invoke(o);
      +     *         } catch (Throwable t) {
      +     *             throw Failable.rethrow(t);
      +     *         }
      +     *     };
      +     *     final List<String> strList = list.stream()
      +     *         .map(mapper).collect(Collectors.toList());
      +     *  
      + * as follows: + *
      +     *     final List<O> list;
      +     *     final Method m;
      +     *     final List<String> strList = Failable.stream(list.stream())
      +     *         .map((o) -> (String) m.invoke(o)).collect(Collectors.toList());
      +     *  
      + * While the second version may not be quite as + * efficient (because it depends on the creation of additional, + * intermediate objects, of type FailableStream), it is much more + * concise, and readable, and meets the spirit of Lambdas better + * than the first version. + * @param The streams element type. + * @param stream The stream, which is being converted. + * @return The {@link FailableStream}, which has been created by + * converting the stream. + */ + public static FailableStream stream(final Stream stream) { + return new FailableStream<>(stream); + } + + /** + * Returns a {@code Collector} that accumulates the input elements into a + * new array. + * + * @param pElementType Type of an element in the array. + * @param the type of the input elements + * @return a {@code Collector} which collects all the input elements into an + * array, in encounter order + */ + public static Collector toArray(final Class pElementType) { + return new ArrayCollector<>(pElementType); + } +} diff --git a/src/test/java/org/apache/commons/lang3/StreamsTest.java b/src/test/java/org/apache/commons/lang3/StreamsTest.java index a0b79f60c13..df1316036bb 100644 --- a/src/test/java/org/apache/commons/lang3/StreamsTest.java +++ b/src/test/java/org/apache/commons/lang3/StreamsTest.java @@ -41,10 +41,10 @@ import org.junit.jupiter.api.function.Executable; import org.xml.sax.SAXException; -class StreamsTest { +public class StreamsTest { @Test - void testSimpleStreamMap() { + public void testSimpleStreamMap() { final List input = Arrays.asList("1", "2", "3", "4", "5", "6"); final List output = Functions.stream(input).map(Integer::valueOf).collect(Collectors.toList()); assertEquals(6, output.size()); @@ -54,7 +54,7 @@ void testSimpleStreamMap() { } @Test - void testSimpleStreamMapFailing() { + public void testSimpleStreamMapFailing() { final List input = Arrays.asList("1", "2", "3", "4 ", "5", "6"); final Executable testMethod = () -> Functions.stream(input).map(Integer::valueOf).collect(Collectors.toList()); final NumberFormatException thrown = assertThrows(NumberFormatException.class, testMethod); @@ -62,7 +62,7 @@ void testSimpleStreamMapFailing() { } @Test - void testSimpleStreamForEach() { + public void testSimpleStreamForEach() { final List input = Arrays.asList("1", "2", "3", "4", "5", "6"); final List output = new ArrayList<>(); Functions.stream(input).forEach(s -> output.add(Integer.valueOf(s))); @@ -73,7 +73,7 @@ void testSimpleStreamForEach() { } @Test - void testToArray() { + public void testToArray() { final String[] array = Arrays.asList("2", "3", "1").stream().collect(Streams.toArray(String.class)); assertNotNull(array); assertEquals(3, array.length); @@ -92,7 +92,7 @@ protected FailableConsumer asIntConsumer(final } @TestFactory - Stream simpleStreamForEachFailing() { + public Stream simpleStreamForEachFailing() { final List input = Arrays.asList("1", "2", "3", "4", "5", "6"); return Stream.of( @@ -127,7 +127,7 @@ Stream simpleStreamForEachFailing() { } @Test - void testSimpleStreamFilter() { + public void testSimpleStreamFilter() { final List input = Arrays.asList("1", "2", "3", "4", "5", "6"); final List output = Functions.stream(input) .map(Integer::valueOf) @@ -155,7 +155,7 @@ protected FailablePredicate asIntPredicate(fin } @TestFactory - Stream simpleStreamFilterFailing() { + public Stream simpleStreamFilterFailing() { final List input = Arrays.asList("1", "2", "3", "4", "5", "6"); final List output = Functions.stream(input) .map(Integer::valueOf) diff --git a/src/test/java/org/apache/commons/lang3/stream/StreamsTest.java b/src/test/java/org/apache/commons/lang3/stream/StreamsTest.java new file mode 100644 index 00000000000..218fa334a3a --- /dev/null +++ b/src/test/java/org/apache/commons/lang3/stream/StreamsTest.java @@ -0,0 +1,187 @@ +/* + * 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.stream; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.Is.is; +import static org.hamcrest.core.IsEqual.equalTo; +import static org.hamcrest.core.IsNull.nullValue; +import static org.junit.jupiter.api.Assertions.assertAll; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.DynamicTest.dynamicTest; + +import java.lang.reflect.UndeclaredThrowableException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.apache.commons.lang3.function.Failable; +import org.apache.commons.lang3.function.FailableConsumer; +import org.apache.commons.lang3.function.FailablePredicate; +import org.junit.jupiter.api.DynamicTest; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestFactory; +import org.junit.jupiter.api.function.Executable; +import org.xml.sax.SAXException; + +public class StreamsTest { + + protected FailableConsumer asIntConsumer(final T pThrowable) { + return s -> { + final Integer i = Integer.valueOf(s); + if (i.intValue() == 4) { + throw pThrowable; + } + }; + } + + protected FailablePredicate asIntPredicate(final T pThrowable) { + return i -> { + if (i.intValue() == 5) { + if (pThrowable != null) { + throw pThrowable; + } + } + return i % 2 == 0; + }; + } + + private void assertEvenNumbers(final List output) { + assertEquals(3, output.size()); + for (int i = 0; i < 3; i++) { + assertEquals((i + 1) * 2, output.get(i).intValue()); + } + } + + @TestFactory + public Stream simpleStreamFilterFailing() { + final List input = Arrays.asList("1", "2", "3", "4", "5", "6"); + final List output = Failable.stream(input).map(Integer::valueOf).filter(asIntPredicate(null)) + .collect(Collectors.toList()); + assertEvenNumbers(output); + + return Stream.of( + + dynamicTest("IllegalArgumentException", () -> { + final IllegalArgumentException iae = new IllegalArgumentException("Invalid argument: " + 5); + final Executable testMethod = () -> Failable.stream(input).map(Integer::valueOf) + .filter(asIntPredicate(iae)).collect(Collectors.toList()); + final IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, testMethod); + assertThat(thrown.getMessage(), is(equalTo("Invalid argument: " + 5))); + }), + + dynamicTest("OutOfMemoryError", () -> { + final OutOfMemoryError oome = new OutOfMemoryError(); + final Executable testMethod = () -> Failable.stream(input).map(Integer::valueOf) + .filter(asIntPredicate(oome)).collect(Collectors.toList()); + final OutOfMemoryError thrown = assertThrows(OutOfMemoryError.class, testMethod); + assertThat(thrown.getMessage(), is(nullValue())); + }), + + dynamicTest("SAXException", () -> { + final SAXException se = new SAXException(); + final Executable testMethod = () -> Failable.stream(input).map(Integer::valueOf) + .filter(asIntPredicate(se)).collect(Collectors.toList()); + final UndeclaredThrowableException thrown = assertThrows(UndeclaredThrowableException.class, + testMethod); + assertAll(() -> assertThat(thrown.getMessage(), is(nullValue())), + () -> assertThat(thrown.getCause(), is(equalTo(se)))); + })); + } + + @TestFactory + public Stream simpleStreamForEachFailing() { + final List input = Arrays.asList("1", "2", "3", "4", "5", "6"); + + return Stream.of( + + dynamicTest("IllegalArgumentException", () -> { + final IllegalArgumentException ise = new IllegalArgumentException(); + final Executable testMethod = () -> Failable.stream(input).forEach(asIntConsumer(ise)); + final IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, testMethod); + assertThat(thrown.getMessage(), is(nullValue())); + }), + + dynamicTest("OutOfMemoryError", () -> { + final OutOfMemoryError oome = new OutOfMemoryError(); + final Executable oomeTestMethod = () -> Failable.stream(input).forEach(asIntConsumer(oome)); + final OutOfMemoryError oomeThrown = assertThrows(OutOfMemoryError.class, oomeTestMethod); + assertThat(oomeThrown.getMessage(), is(nullValue())); + }), + + dynamicTest("SAXException", () -> { + final SAXException se = new SAXException(); + final Executable seTestMethod = () -> Failable.stream(input).forEach(asIntConsumer(se)); + final UndeclaredThrowableException seThrown = assertThrows(UndeclaredThrowableException.class, + seTestMethod); + assertAll(() -> assertThat(seThrown.getMessage(), is(nullValue())), + () -> assertThat(seThrown.getCause(), is(equalTo(se)))); + })); + } + + @Test + public void testSimpleStreamFilter() { + final List input = Arrays.asList("1", "2", "3", "4", "5", "6"); + final List output = Failable.stream(input).map(Integer::valueOf).filter(i -> (i.intValue() % 2 == 0)) + .collect(Collectors.toList()); + assertEvenNumbers(output); + } + + @Test + public void testSimpleStreamForEach() { + final List input = Arrays.asList("1", "2", "3", "4", "5", "6"); + final List output = new ArrayList<>(); + Failable.stream(input).forEach(s -> output.add(Integer.valueOf(s))); + assertEquals(6, output.size()); + for (int i = 0; i < 6; i++) { + assertEquals(i + 1, output.get(i).intValue()); + } + } + + @Test + public void testSimpleStreamMap() { + final List input = Arrays.asList("1", "2", "3", "4", "5", "6"); + final List output = Failable.stream(input).map(Integer::valueOf).collect(Collectors.toList()); + assertEquals(6, output.size()); + for (int i = 0; i < 6; i++) { + assertEquals(i + 1, output.get(i).intValue()); + } + } + + @Test + public void testSimpleStreamMapFailing() { + final List input = Arrays.asList("1", "2", "3", "4 ", "5", "6"); + final Executable testMethod = () -> Failable.stream(input).map(Integer::valueOf).collect(Collectors.toList()); + final NumberFormatException thrown = assertThrows(NumberFormatException.class, testMethod); + assertEquals("For input string: \"4 \"", thrown.getMessage()); + } + + @Test + public void testToArray() { + final String[] array = Arrays.asList("2", "3", "1").stream().collect(Streams.toArray(String.class)); + assertNotNull(array); + assertEquals(3, array.length); + assertEquals("2", array[0]); + assertEquals("3", array[1]); + assertEquals("1", array[2]); + } + +} From 46acdde8bde91f8f266ffeaefc8d526309c24998 Mon Sep 17 00:00:00 2001 From: aherbert Date: Thu, 18 Jun 2020 09:25:25 +0100 Subject: [PATCH 0163/3230] Fix comment typos --- src/main/java/org/apache/commons/lang3/ArrayUtils.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/ArrayUtils.java b/src/main/java/org/apache/commons/lang3/ArrayUtils.java index 8b483d2d07b..1fe9dd47c26 100644 --- a/src/main/java/org/apache/commons/lang3/ArrayUtils.java +++ b/src/main/java/org/apache/commons/lang3/ArrayUtils.java @@ -5190,7 +5190,7 @@ static Object removeAll(final Object array, final BitSet indices) { final int srcLength = getLength(array); // No need to check maxIndex here, because method only currently called from removeElements() - // which guarantee to generate on;y valid bit entries. + // which guarantee to generate only valid bit entries. // final int maxIndex = indices.length(); // if (maxIndex > srcLength) { // throw new IndexOutOfBoundsException("Index: " + (maxIndex-1) + ", Length: " + srcLength); @@ -5258,7 +5258,7 @@ static Object removeAll(final Object array, final int... indices) { final int cp = end - index - 1; dest -= cp; System.arraycopy(array, index + 1, result, dest, cp); - // Afer this copy, we still have room for dest items. + // After this copy, we still have room for dest items. } end = index; } From abf6899e0701e9b00f4f761082308255481dc5a8 Mon Sep 17 00:00:00 2001 From: aherbert Date: Thu, 18 Jun 2020 11:46:51 +0100 Subject: [PATCH 0164/3230] Use upper case L on long declarations --- .../apache/commons/lang3/function/FailableFunctionsTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/test/java/org/apache/commons/lang3/function/FailableFunctionsTest.java b/src/test/java/org/apache/commons/lang3/function/FailableFunctionsTest.java index 468c5a48b8d..7390ab683ea 100644 --- a/src/test/java/org/apache/commons/lang3/function/FailableFunctionsTest.java +++ b/src/test/java/org/apache/commons/lang3/function/FailableFunctionsTest.java @@ -889,8 +889,8 @@ public void testIntPredicate() throws Throwable { public void testLongPredicate() throws Throwable { FailureOnOddInvocations.invocations = 0; final FailableLongPredicate failablePredicate = t1 -> FailureOnOddInvocations.testLong(t1); - assertThrows(SomeException.class, () -> failablePredicate.test(1l)); - failablePredicate.test(1l); + assertThrows(SomeException.class, () -> failablePredicate.test(1L)); + failablePredicate.test(1L); } @Test From f53ff8cc209b77ea63b79b9ee0f1f1f0cfb83713 Mon Sep 17 00:00:00 2001 From: aherbert Date: Thu, 18 Jun 2020 11:48:12 +0100 Subject: [PATCH 0165/3230] Checkstyle: new line at end of file --- .../org/apache/commons/lang3/function/FailableFunction.java | 2 +- .../org/apache/commons/lang3/function/FailablePredicate.java | 2 +- .../org/apache/commons/lang3/function/FailableRunnable.java | 2 +- .../org/apache/commons/lang3/function/FailableSupplier.java | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/function/FailableFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableFunction.java index 9df6f7100a0..3aad2108964 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableFunction.java @@ -38,4 +38,4 @@ public interface FailableFunction { * @throws T Thrown when the function fails. */ R apply(I input) throws T; -} \ No newline at end of file +} diff --git a/src/main/java/org/apache/commons/lang3/function/FailablePredicate.java b/src/main/java/org/apache/commons/lang3/function/FailablePredicate.java index 64389e8e46b..6e461ce0a22 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailablePredicate.java +++ b/src/main/java/org/apache/commons/lang3/function/FailablePredicate.java @@ -37,4 +37,4 @@ public interface FailablePredicate { * @throws T if the predicate fails */ boolean test(I object) throws T; -} \ No newline at end of file +} diff --git a/src/main/java/org/apache/commons/lang3/function/FailableRunnable.java b/src/main/java/org/apache/commons/lang3/function/FailableRunnable.java index 2cce9e8e6b2..f783b338ce6 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableRunnable.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableRunnable.java @@ -32,4 +32,4 @@ public interface FailableRunnable { * @throws T Thrown when the function fails. */ void run() throws T; -} \ No newline at end of file +} diff --git a/src/main/java/org/apache/commons/lang3/function/FailableSupplier.java b/src/main/java/org/apache/commons/lang3/function/FailableSupplier.java index a07bd6a16f7..a8ff7680131 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableSupplier.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableSupplier.java @@ -36,4 +36,4 @@ public interface FailableSupplier { * @throws T if the supplier fails */ R get() throws T; -} \ No newline at end of file +} From 093dd682d29cde9a994728536473af06d0e81fef Mon Sep 17 00:00:00 2001 From: aherbert Date: Thu, 18 Jun 2020 11:49:20 +0100 Subject: [PATCH 0166/3230] Remove redundant import --- src/test/java/org/apache/commons/lang3/concurrent/LocksTest.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/test/java/org/apache/commons/lang3/concurrent/LocksTest.java b/src/test/java/org/apache/commons/lang3/concurrent/LocksTest.java index eaba4e93f1d..88164893504 100644 --- a/src/test/java/org/apache/commons/lang3/concurrent/LocksTest.java +++ b/src/test/java/org/apache/commons/lang3/concurrent/LocksTest.java @@ -20,7 +20,6 @@ import java.util.function.LongConsumer; -import org.apache.commons.lang3.concurrent.Locks; import org.apache.commons.lang3.concurrent.Locks.Lock; import org.apache.commons.lang3.function.FailableConsumer; import org.junit.jupiter.api.Test; From 5d675a0e294ca83b5739ef57be7e9bcfb04c35af Mon Sep 17 00:00:00 2001 From: aherbert Date: Thu, 18 Jun 2020 12:09:50 +0100 Subject: [PATCH 0167/3230] Add skeleton package-info --- .../commons/lang3/function/package-info.java | 28 +++++++++++++++++++ .../commons/lang3/stream/package-info.java | 26 +++++++++++++++++ 2 files changed, 54 insertions(+) create mode 100644 src/main/java/org/apache/commons/lang3/function/package-info.java create mode 100644 src/main/java/org/apache/commons/lang3/stream/package-info.java diff --git a/src/main/java/org/apache/commons/lang3/function/package-info.java b/src/main/java/org/apache/commons/lang3/function/package-info.java new file mode 100644 index 00000000000..aae4c7dd31c --- /dev/null +++ b/src/main/java/org/apache/commons/lang3/function/package-info.java @@ -0,0 +1,28 @@ +/* + * 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. + */ +/** + * Provides functional interfaces to complement those in {@code java.lang.function} and utilities + * for working with Java 8 lambdas. + * + *

      Contains failable functional interfaces that address the fact that lambdas are supposed not to + * throw Exceptions, at least not checked Exceptions, AKA instances of {@link java.lang.Exception}. + * A failable functional interface declares a type of Exception that may be raised if the function + * fails. + * + * @since 3.11 + */ +package org.apache.commons.lang3.function; diff --git a/src/main/java/org/apache/commons/lang3/stream/package-info.java b/src/main/java/org/apache/commons/lang3/stream/package-info.java new file mode 100644 index 00000000000..b2deefcfb56 --- /dev/null +++ b/src/main/java/org/apache/commons/lang3/stream/package-info.java @@ -0,0 +1,26 @@ +/* + * 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. + */ +/** + * Provides utility classes to complement those in {@code java.util.stream}. + * + *

      Contains utilities to allow streaming of failable functional interfaces from the + * {@code org.apache.commons.lang3.functions} package allowing streaming of functional expressions + * that may raise an Exception. + * + * @since 3.11 + */ +package org.apache.commons.lang3.stream; From 3302d5040bece8f2bf2e236bd99c5bbc160b1d93 Mon Sep 17 00:00:00 2001 From: aherbert Date: Thu, 18 Jun 2020 12:10:20 +0100 Subject: [PATCH 0168/3230] Correct code example in javadoc header --- src/main/java/org/apache/commons/lang3/function/Failable.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/apache/commons/lang3/function/Failable.java b/src/main/java/org/apache/commons/lang3/function/Failable.java index 9ecc2838876..1017146b090 100644 --- a/src/main/java/org/apache/commons/lang3/function/Failable.java +++ b/src/main/java/org/apache/commons/lang3/function/Failable.java @@ -46,7 +46,7 @@ * try { * m.invoke(o, args); * } catch (Throwable t) { - * throw Functions.rethrow(t); + * throw Failable.rethrow(t); * } * }; * } From 4453bb3ede27278e414cb634c2db1ad268116622 Mon Sep 17 00:00:00 2001 From: aherbert Date: Thu, 18 Jun 2020 12:13:15 +0100 Subject: [PATCH 0169/3230] Fix @since for new o.a.c.lang3.stream.Streams class. This replaces o.a.c.lang3.Streams. --- src/main/java/org/apache/commons/lang3/stream/Streams.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/apache/commons/lang3/stream/Streams.java b/src/main/java/org/apache/commons/lang3/stream/Streams.java index 1954432c7c0..f9759652344 100644 --- a/src/main/java/org/apache/commons/lang3/stream/Streams.java +++ b/src/main/java/org/apache/commons/lang3/stream/Streams.java @@ -62,7 +62,7 @@ * * @see Stream * @see Failable - * @since 3.10 + * @since 3.11 */ public class Streams { From d22f4e1e613ab35c7a7e07a0b69bf6bca92cb6c4 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Thu, 18 Jun 2020 08:16:51 -0400 Subject: [PATCH 0170/3230] Clean up generics. --- src/main/java/org/apache/commons/lang3/concurrent/Locks.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/apache/commons/lang3/concurrent/Locks.java b/src/main/java/org/apache/commons/lang3/concurrent/Locks.java index e96f36bc165..2a6e52f5da1 100644 --- a/src/main/java/org/apache/commons/lang3/concurrent/Locks.java +++ b/src/main/java/org/apache/commons/lang3/concurrent/Locks.java @@ -115,6 +115,6 @@ protected T callLocked(long stamp, FailableFunction function) { } public static Locks.Lock lock(O object) { - return new Locks.Lock(object); + return new Locks.Lock<>(object); } } From f05c39b6e4d0c9d0f939a13bed916c442b098be6 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Thu, 18 Jun 2020 12:36:00 -0400 Subject: [PATCH 0171/3230] Use names that reflect the functional interface in use. --- .../org/apache/commons/lang3/concurrent/Locks.java | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/concurrent/Locks.java b/src/main/java/org/apache/commons/lang3/concurrent/Locks.java index 2a6e52f5da1..f78a9dd6daa 100644 --- a/src/main/java/org/apache/commons/lang3/concurrent/Locks.java +++ b/src/main/java/org/apache/commons/lang3/concurrent/Locks.java @@ -78,22 +78,22 @@ public Lock(O lockedObject) { } public void runReadLocked(FailableConsumer consumer) { - runLocked(lock.readLock(), consumer); + acceptLocked(lock.readLock(), consumer); } public void runWriteLocked(FailableConsumer consumer) { - runLocked(lock.writeLock(), consumer); + acceptLocked(lock.writeLock(), consumer); } public T callReadLocked(FailableFunction function) { - return callLocked(lock.readLock(), function); + return applyLocked(lock.readLock(), function); } public T callWriteLocked(FailableFunction function) { - return callLocked(lock.writeLock(), function); + return applyLocked(lock.writeLock(), function); } - protected void runLocked(long stamp, FailableConsumer consumer) { + protected void acceptLocked(long stamp, FailableConsumer consumer) { try { consumer.accept(lockedObject); } catch (Throwable t) { @@ -103,7 +103,7 @@ protected void runLocked(long stamp, FailableConsumer consumer) { } } - protected T callLocked(long stamp, FailableFunction function) { + protected T applyLocked(long stamp, FailableFunction function) { try { return function.apply(lockedObject); } catch (Throwable t) { From ed0f5bea111c449fa17478d7e0c7c37c3ede3863 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Thu, 18 Jun 2020 12:48:46 -0400 Subject: [PATCH 0172/3230] Reimplement such that locking and unlocking take place in the same method. --- .../commons/lang3/concurrent/Locks.java | 61 ++++++++++--------- 1 file changed, 32 insertions(+), 29 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/concurrent/Locks.java b/src/main/java/org/apache/commons/lang3/concurrent/Locks.java index f78a9dd6daa..f8ecae965bd 100644 --- a/src/main/java/org/apache/commons/lang3/concurrent/Locks.java +++ b/src/main/java/org/apache/commons/lang3/concurrent/Locks.java @@ -18,36 +18,36 @@ import java.util.Objects; import java.util.concurrent.locks.StampedLock; +import java.util.function.LongSupplier; import org.apache.commons.lang3.function.Failable; import org.apache.commons.lang3.function.FailableConsumer; import org.apache.commons.lang3.function.FailableFunction; - /** * Utility class for working with {@link java.util.concurrent.locks.Lock locked objects}. Locked objects are an * alternative to synchronization. * - * Locking is preferable, if there is a distinction between read access (multiple threads may have read - * access concurrently), and write access (only one thread may have write access at any given time. - * In comparison, synchronization doesn't support read access, because synchronized access is exclusive. + * Locking is preferable, if there is a distinction between read access (multiple threads may have read access + * concurrently), and write access (only one thread may have write access at any given time. In comparison, + * synchronization doesn't support read access, because synchronized access is exclusive. * * Using this class is fairly straightforward: *

        - *
      1. While still in single thread mode, create an instance of {@link Locks.Lock} by calling - * {@link #lock(Object)}, passing the object, which needs to be locked. Discard all - * references to the locked object. Instead, use references to the lock.
      2. - *
      3. If you want to access the locked object, create a {@link FailableConsumer}. The consumer - * will receive the locked object as a parameter. For convenience, the consumer may be - * implemented as a Lambda. Then invoke {@link Locks.Lock#runReadLocked(FailableConsumer)}, - * or {@link Locks.Lock#runWriteLocked(FailableConsumer)}, passing the consumer.
      4. - *
      5. As an alternative, if you need to produce a result object, you may use a - * {@link FailableFunction}. This function may also be implemented as a Lambda. To - * have the function executed, invoke {@link Locks.Lock#callReadLocked(FailableFunction)}, or - * {@link Locks.Lock#callWriteLocked(FailableFunction)}.
      6. + *
      7. While still in single thread mode, create an instance of {@link Locks.Lock} by calling {@link #lock(Object)}, + * passing the object, which needs to be locked. Discard all references to the locked object. Instead, use references to + * the lock.
      8. + *
      9. If you want to access the locked object, create a {@link FailableConsumer}. The consumer will receive the locked + * object as a parameter. For convenience, the consumer may be implemented as a Lambda. Then invoke + * {@link Locks.Lock#runReadLocked(FailableConsumer)}, or {@link Locks.Lock#runWriteLocked(FailableConsumer)}, passing + * the consumer.
      10. + *
      11. As an alternative, if you need to produce a result object, you may use a {@link FailableFunction}. This function + * may also be implemented as a Lambda. To have the function executed, invoke + * {@link Locks.Lock#callReadLocked(FailableFunction)}, or {@link Locks.Lock#callWriteLocked(FailableFunction)}.
      12. *
      * * Example: A thread safe logger class. + * *
        *   public class SimpleLogger {
        *     private final Lock<PrintStream> lock;
      @@ -65,6 +65,7 @@
        *         lock.runWriteLocked((ps) -> { ps.write(buffer); ps.println(); });
        *     }
        * 
      + * * @since 3.11 */ public class Locks { @@ -73,40 +74,42 @@ public static class Lock { private final O lockedObject; private final StampedLock lock = new StampedLock(); - public Lock(O lockedObject) { + public Lock(final O lockedObject) { this.lockedObject = Objects.requireNonNull(lockedObject, "Locked Object"); } - public void runReadLocked(FailableConsumer consumer) { - acceptLocked(lock.readLock(), consumer); + public void runReadLocked(final FailableConsumer consumer) { + acceptLocked(() -> lock.readLock(), consumer); } - public void runWriteLocked(FailableConsumer consumer) { - acceptLocked(lock.writeLock(), consumer); + public void runWriteLocked(final FailableConsumer consumer) { + acceptLocked(() -> lock.writeLock(), consumer); } - public T callReadLocked(FailableFunction function) { - return applyLocked(lock.readLock(), function); + public T callReadLocked(final FailableFunction function) { + return applyLocked(() -> lock.readLock(), function); } - public T callWriteLocked(FailableFunction function) { - return applyLocked(lock.writeLock(), function); + public T callWriteLocked(final FailableFunction function) { + return applyLocked(() -> lock.writeLock(), function); } - protected void acceptLocked(long stamp, FailableConsumer consumer) { + protected void acceptLocked(final LongSupplier stampSupplier, final FailableConsumer consumer) { + final long stamp = stampSupplier.getAsLong(); try { consumer.accept(lockedObject); - } catch (Throwable t) { + } catch (final Throwable t) { throw Failable.rethrow(t); } finally { lock.unlock(stamp); } } - protected T applyLocked(long stamp, FailableFunction function) { + protected T applyLocked(final LongSupplier stampSupplier, final FailableFunction function) { + final long stamp = stampSupplier.getAsLong(); try { return function.apply(lockedObject); - } catch (Throwable t) { + } catch (final Throwable t) { throw Failable.rethrow(t); } finally { lock.unlock(stamp); @@ -114,7 +117,7 @@ protected T applyLocked(long stamp, FailableFunction function) { } } - public static Locks.Lock lock(O object) { + public static Locks.Lock lock(final O object) { return new Locks.Lock<>(object); } } From bb270696fd83de10172b2483941e52711d78d860 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Thu, 18 Jun 2020 12:49:40 -0400 Subject: [PATCH 0173/3230] Tests are public by convention on Commons Lang. --- .../org/apache/commons/lang3/concurrent/LocksTest.java | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/test/java/org/apache/commons/lang3/concurrent/LocksTest.java b/src/test/java/org/apache/commons/lang3/concurrent/LocksTest.java index 88164893504..ee8fc09f42f 100644 --- a/src/test/java/org/apache/commons/lang3/concurrent/LocksTest.java +++ b/src/test/java/org/apache/commons/lang3/concurrent/LocksTest.java @@ -24,11 +24,11 @@ import org.apache.commons.lang3.function.FailableConsumer; import org.junit.jupiter.api.Test; -class LocksTest { +public class LocksTest { private static final int NUMBER_OF_THREADS = 10; @Test - void testReadLock() throws Exception { + public void testReadLock() throws Exception { final long DELAY=3000; /** If our threads are running concurrently, then we expect to be faster * than running one after the other. @@ -36,7 +36,7 @@ void testReadLock() throws Exception { runTest(DELAY, false, l -> assertTrue(l < NUMBER_OF_THREADS*DELAY)); } - void testWriteLock() throws Exception { + public void testWriteLock() throws Exception { final long DELAY = 100; /** If our threads are running concurrently, then we expect to be no faster * than running one after the other. @@ -83,6 +83,7 @@ protected void modify(boolean[] booleanArray, int offset, boolean value) { booleanArray[offset] = value; } } + protected boolean someValueIsTrue(boolean[] booleanArray) { synchronized(booleanArray) { for (int i = 0; i < booleanArray.length; i++) { From 45e38e91f902461a91dfbad36c681435aa95fac6 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Fri, 19 Jun 2020 11:02:54 -0400 Subject: [PATCH 0174/3230] Better method names. --- .../org/apache/commons/lang3/concurrent/Locks.java | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/concurrent/Locks.java b/src/main/java/org/apache/commons/lang3/concurrent/Locks.java index f8ecae965bd..c4856866dbb 100644 --- a/src/main/java/org/apache/commons/lang3/concurrent/Locks.java +++ b/src/main/java/org/apache/commons/lang3/concurrent/Locks.java @@ -79,22 +79,22 @@ public Lock(final O lockedObject) { } public void runReadLocked(final FailableConsumer consumer) { - acceptLocked(() -> lock.readLock(), consumer); + lockAcceptUnlock(() -> lock.readLock(), consumer); } public void runWriteLocked(final FailableConsumer consumer) { - acceptLocked(() -> lock.writeLock(), consumer); + lockAcceptUnlock(() -> lock.writeLock(), consumer); } public T callReadLocked(final FailableFunction function) { - return applyLocked(() -> lock.readLock(), function); + return lockApplyUnock(() -> lock.readLock(), function); } public T callWriteLocked(final FailableFunction function) { - return applyLocked(() -> lock.writeLock(), function); + return lockApplyUnock(() -> lock.writeLock(), function); } - protected void acceptLocked(final LongSupplier stampSupplier, final FailableConsumer consumer) { + protected void lockAcceptUnlock(final LongSupplier stampSupplier, final FailableConsumer consumer) { final long stamp = stampSupplier.getAsLong(); try { consumer.accept(lockedObject); @@ -105,7 +105,7 @@ protected void acceptLocked(final LongSupplier stampSupplier, final FailableCons } } - protected T applyLocked(final LongSupplier stampSupplier, final FailableFunction function) { + protected T lockApplyUnock(final LongSupplier stampSupplier, final FailableFunction function) { final long stamp = stampSupplier.getAsLong(); try { return function.apply(lockedObject); From a33b86e61f23170f6f63fd484dee477dc78bfa6c Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Fri, 19 Jun 2020 11:03:14 -0400 Subject: [PATCH 0175/3230] Better method names. --- .../java/org/apache/commons/lang3/concurrent/Locks.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/concurrent/Locks.java b/src/main/java/org/apache/commons/lang3/concurrent/Locks.java index c4856866dbb..d2cdfdb9363 100644 --- a/src/main/java/org/apache/commons/lang3/concurrent/Locks.java +++ b/src/main/java/org/apache/commons/lang3/concurrent/Locks.java @@ -87,11 +87,11 @@ public void runWriteLocked(final FailableConsumer consumer) { } public T callReadLocked(final FailableFunction function) { - return lockApplyUnock(() -> lock.readLock(), function); + return lockApplyUnlock(() -> lock.readLock(), function); } public T callWriteLocked(final FailableFunction function) { - return lockApplyUnock(() -> lock.writeLock(), function); + return lockApplyUnlock(() -> lock.writeLock(), function); } protected void lockAcceptUnlock(final LongSupplier stampSupplier, final FailableConsumer consumer) { @@ -105,7 +105,7 @@ protected void lockAcceptUnlock(final LongSupplier stampSupplier, final Failable } } - protected T lockApplyUnock(final LongSupplier stampSupplier, final FailableFunction function) { + protected T lockApplyUnlock(final LongSupplier stampSupplier, final FailableFunction function) { final long stamp = stampSupplier.getAsLong(); try { return function.apply(lockedObject); From 6363fced4b3837afb8a36ed109264b016097d8d8 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Fri, 19 Jun 2020 11:06:52 -0400 Subject: [PATCH 0176/3230] Better method names. --- .../commons/lang3/concurrent/Locks.java | 23 ++++++++++--------- .../commons/lang3/concurrent/LocksTest.java | 4 ++-- 2 files changed, 14 insertions(+), 13 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/concurrent/Locks.java b/src/main/java/org/apache/commons/lang3/concurrent/Locks.java index d2cdfdb9363..28df9c0953a 100644 --- a/src/main/java/org/apache/commons/lang3/concurrent/Locks.java +++ b/src/main/java/org/apache/commons/lang3/concurrent/Locks.java @@ -39,30 +39,30 @@ * the lock.
    5. *
    6. If you want to access the locked object, create a {@link FailableConsumer}. The consumer will receive the locked * object as a parameter. For convenience, the consumer may be implemented as a Lambda. Then invoke - * {@link Locks.Lock#runReadLocked(FailableConsumer)}, or {@link Locks.Lock#runWriteLocked(FailableConsumer)}, passing + * {@link Locks.Lock#acceptReadLocked(FailableConsumer)}, or {@link Locks.Lock#acceptWriteLocked(FailableConsumer)}, passing * the consumer.
    7. *
    8. As an alternative, if you need to produce a result object, you may use a {@link FailableFunction}. This function * may also be implemented as a Lambda. To have the function executed, invoke - * {@link Locks.Lock#callReadLocked(FailableFunction)}, or {@link Locks.Lock#callWriteLocked(FailableFunction)}.
    9. + * {@link Locks.Lock#applyReadLocked(FailableFunction)}, or {@link Locks.Lock#applyWriteLocked(FailableFunction)}. * * * Example: A thread safe logger class. * *
        *   public class SimpleLogger {
      + *
        *     private final Lock<PrintStream> lock;
        *
        *     public SimpleLogger(OutputStream out) {
      - *         PrintStream ps = new PrintStream(out);
      - *         lock = Locks.lock(ps);
      + *         lock = Locks.lock(new PrintStream(out));
        *     }
        *
        *     public void log(String message) {
      - *         lock.runWriteLocked((ps) -> ps.println(message));
      + *         lock.acceptWriteLocked((ps) -> ps.println(message));
        *     }
        *
        *     public void log(byte[] buffer) {
      - *         lock.runWriteLocked((ps) -> { ps.write(buffer); ps.println(); });
      + *         lock.acceptWriteLocked((ps) -> { ps.write(buffer); ps.println(); });
        *     }
        * 
      * @@ -71,26 +71,27 @@ public class Locks { public static class Lock { - private final O lockedObject; + private final StampedLock lock = new StampedLock(); + private final O lockedObject; public Lock(final O lockedObject) { this.lockedObject = Objects.requireNonNull(lockedObject, "Locked Object"); } - public void runReadLocked(final FailableConsumer consumer) { + public void acceptReadLocked(final FailableConsumer consumer) { lockAcceptUnlock(() -> lock.readLock(), consumer); } - public void runWriteLocked(final FailableConsumer consumer) { + public void acceptWriteLocked(final FailableConsumer consumer) { lockAcceptUnlock(() -> lock.writeLock(), consumer); } - public T callReadLocked(final FailableFunction function) { + public T applyReadLocked(final FailableFunction function) { return lockApplyUnlock(() -> lock.readLock(), function); } - public T callWriteLocked(final FailableFunction function) { + public T applyWriteLocked(final FailableFunction function) { return lockApplyUnlock(() -> lock.writeLock(), function); } diff --git a/src/test/java/org/apache/commons/lang3/concurrent/LocksTest.java b/src/test/java/org/apache/commons/lang3/concurrent/LocksTest.java index ee8fc09f42f..461bb539ea1 100644 --- a/src/test/java/org/apache/commons/lang3/concurrent/LocksTest.java +++ b/src/test/java/org/apache/commons/lang3/concurrent/LocksTest.java @@ -60,9 +60,9 @@ private void runTest(long delay, boolean exclusiveLock, LongConsumer runTimeChec }; final Thread t = new Thread(() -> { if (exclusiveLock) { - lock.runWriteLocked(consumer); + lock.acceptWriteLocked(consumer); } else { - lock.runReadLocked(consumer); + lock.acceptReadLocked(consumer); } }); modify(runningValues, i, true); From 5b350aa33b1ec01d65c54b765d6f2ebe2dc61728 Mon Sep 17 00:00:00 2001 From: XenoAmess Date: Sat, 20 Jun 2020 00:01:55 +0800 Subject: [PATCH 0177/3230] refine test output for FastDateParserTest --- .../apache/commons/lang3/time/FastDateParserTest.java | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/src/test/java/org/apache/commons/lang3/time/FastDateParserTest.java b/src/test/java/org/apache/commons/lang3/time/FastDateParserTest.java index 529d662336f..aec8ef89ea3 100644 --- a/src/test/java/org/apache/commons/lang3/time/FastDateParserTest.java +++ b/src/test/java/org/apache/commons/lang3/time/FastDateParserTest.java @@ -21,6 +21,7 @@ import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.io.Serializable; import java.text.ParseException; @@ -366,9 +367,13 @@ private void checkParse(final Locale locale, final Calendar cal, final SimpleDat } private void checkParse(final Locale locale, final SimpleDateFormat sdf, final DateParser fdf, final String formattedDate) throws ParseException { - final Date expectedTime = sdf.parse(formattedDate); - final Date actualTime = fdf.parse(formattedDate); - assertEquals(expectedTime, actualTime, locale.toString()+" "+formattedDate +"\n"); + try { + final Date expectedTime = sdf.parse(formattedDate); + final Date actualTime = fdf.parse(formattedDate); + assertEquals(expectedTime, actualTime, "locale : " + locale + " formattedDate : " + formattedDate + "\n"); + } catch (Exception e) { + fail("locale : " + locale + " formattedDate : " + formattedDate + " error : " + e + "\n", e); + } } @Test From acb237c52dbc6b9c2976c05fcd610ca0433ce654 Mon Sep 17 00:00:00 2001 From: XenoAmess Date: Sat, 20 Jun 2020 01:41:01 +0800 Subject: [PATCH 0178/3230] add a single test for showing up the problem --- .../lang3/time/FastDateParserTest.java | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/src/test/java/org/apache/commons/lang3/time/FastDateParserTest.java b/src/test/java/org/apache/commons/lang3/time/FastDateParserTest.java index aec8ef89ea3..6ede003eec8 100644 --- a/src/test/java/org/apache/commons/lang3/time/FastDateParserTest.java +++ b/src/test/java/org/apache/commons/lang3/time/FastDateParserTest.java @@ -707,4 +707,30 @@ public void testLang1380() throws ParseException { assertEquals(expected.getTime(), fdp.parse("14 avr. 2014")); assertEquals(expected.getTime(), fdp.parse("14 avr 2014")); } + + @Test + public void java15BuggyLocaleTest() throws ParseException { + final String buggyLocaleName = "ff_LR_#Adlm"; + Locale buggyLocale = null; + + for (final Locale locale : Locale.getAvailableLocales()) { + if (buggyLocaleName.equals(locale.toString())) { + buggyLocale = locale; + break; + } + } + + if (buggyLocale == null) { + return; + } + + final Calendar cal = Calendar.getInstance(GMT); + cal.clear(); + cal.set(2003, Calendar.FEBRUARY, 10); + final SimpleDateFormat sdf = new SimpleDateFormat(LONG_FORMAT, buggyLocale); + final String formattedDate = sdf.format(cal.getTime()); + sdf.parse(formattedDate); + sdf.parse(formattedDate.toUpperCase(buggyLocale)); + sdf.parse(formattedDate.toLowerCase(buggyLocale)); + } } From e291a601db76e73b7644440543918183f4b9c700 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Mon, 22 Jun 2020 08:52:25 -0400 Subject: [PATCH 0179/3230] Formatting. --- src/test/java/org/apache/commons/lang3/ThreadUtilsTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/org/apache/commons/lang3/ThreadUtilsTest.java b/src/test/java/org/apache/commons/lang3/ThreadUtilsTest.java index 3942ff8e7d9..a0539b1456e 100644 --- a/src/test/java/org/apache/commons/lang3/ThreadUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/ThreadUtilsTest.java @@ -323,7 +323,7 @@ public void testComplexThreadGroups() throws Exception { assertEquals(1, ThreadUtils.findThreadsByName(t4.getName(), threadGroup3.getName()).size()); assertEquals(0, ThreadUtils.findThreadsByName(t4.getName(), threadGroup2.getName()).size()); assertEquals(2, ThreadUtils.findThreadsByName(t11.getName(), threadGroup7.getName()).size()); - }finally { + } finally { for (final Thread thread : threads) { thread.interrupt(); thread.join(); From 4d403b4ff374eb7d3569a3e56cf135666ee9691d Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Mon, 22 Jun 2020 09:14:34 -0400 Subject: [PATCH 0180/3230] Formatting. --- src/main/java/org/apache/commons/lang3/time/DateUtils.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/apache/commons/lang3/time/DateUtils.java b/src/main/java/org/apache/commons/lang3/time/DateUtils.java index 078c21e6af9..1df4e834b4f 100644 --- a/src/main/java/org/apache/commons/lang3/time/DateUtils.java +++ b/src/main/java/org/apache/commons/lang3/time/DateUtils.java @@ -368,7 +368,7 @@ private static Date parseDateWithLeniency( } final TimeZone tz = TimeZone.getDefault(); - final Locale lcl = locale==null ?Locale.getDefault() : locale; + final Locale lcl = locale==null ? Locale.getDefault() : locale; final ParsePosition pos = new ParsePosition(0); final Calendar calendar = Calendar.getInstance(tz, lcl); calendar.setLenient(lenient); From b7b4ae33dc1f275297a5125ca7ed323756130dff Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Mon, 22 Jun 2020 09:15:29 -0400 Subject: [PATCH 0181/3230] Formatting. --- .../java/org/apache/commons/lang3/time/DateUtils.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/time/DateUtils.java b/src/main/java/org/apache/commons/lang3/time/DateUtils.java index 1df4e834b4f..fd340492c93 100644 --- a/src/main/java/org/apache/commons/lang3/time/DateUtils.java +++ b/src/main/java/org/apache/commons/lang3/time/DateUtils.java @@ -361,14 +361,14 @@ public static Date parseDateStrictly(final String str, final Locale locale, fina * @throws ParseException if none of the date patterns were suitable * @see java.util.Calendar#isLenient() */ - private static Date parseDateWithLeniency( - final String str, final Locale locale, final String[] parsePatterns, final boolean lenient) throws ParseException { + private static Date parseDateWithLeniency(final String str, final Locale locale, final String[] parsePatterns, + final boolean lenient) throws ParseException { if (str == null || parsePatterns == null) { throw new IllegalArgumentException("Date and Patterns must not be null"); } final TimeZone tz = TimeZone.getDefault(); - final Locale lcl = locale==null ? Locale.getDefault() : locale; + final Locale lcl = locale == null ? Locale.getDefault() : locale; final ParsePosition pos = new ParsePosition(0); final Calendar calendar = Calendar.getInstance(tz, lcl); calendar.setLenient(lenient); @@ -377,10 +377,10 @@ private static Date parseDateWithLeniency( final FastDateParser fdp = new FastDateParser(parsePattern, tz, lcl); calendar.clear(); try { - if (fdp.parse(str, pos, calendar) && pos.getIndex()==str.length()) { + if (fdp.parse(str, pos, calendar) && pos.getIndex() == str.length()) { return calendar.getTime(); } - } catch(final IllegalArgumentException ignore) { + } catch (final IllegalArgumentException ignore) { // leniency is preventing calendar from being set } pos.setIndex(0); From 64b2f90d20a20faab6e3cdbf6009475562740a87 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Mon, 22 Jun 2020 09:28:58 -0400 Subject: [PATCH 0182/3230] Fix bug in test. --- .../lang3/StringUtilsContainsTest.java | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/src/test/java/org/apache/commons/lang3/StringUtilsContainsTest.java b/src/test/java/org/apache/commons/lang3/StringUtilsContainsTest.java index b543bf79956..fb1db992f3e 100644 --- a/src/test/java/org/apache/commons/lang3/StringUtilsContainsTest.java +++ b/src/test/java/org/apache/commons/lang3/StringUtilsContainsTest.java @@ -244,16 +244,21 @@ public void testContainsIgnoreCase_LocaleIndependence() { { "\u00DF", "SS" }, }; - for (final Locale testLocale : locales) { - Locale.setDefault(testLocale); - for (int j = 0; j < tdata.length; j++) { - assertTrue(StringUtils.containsIgnoreCase(tdata[j][0], tdata[j][1]), + final Locale defaultLocale = Locale.getDefault(); + try { + for (final Locale testLocale : locales) { + Locale.setDefault(testLocale); + for (int j = 0; j < tdata.length; j++) { + assertTrue(StringUtils.containsIgnoreCase(tdata[j][0], tdata[j][1]), Locale.getDefault() + ": " + j + " " + tdata[j][0] + " " + tdata[j][1]); - } - for (int j = 0; j < fdata.length; j++) { - assertFalse(StringUtils.containsIgnoreCase(fdata[j][0], fdata[j][1]), + } + for (int j = 0; j < fdata.length; j++) { + assertFalse(StringUtils.containsIgnoreCase(fdata[j][0], fdata[j][1]), Locale.getDefault() + ": " + j + " " + fdata[j][0] + " " + fdata[j][1]); + } } + } finally { + Locale.setDefault(defaultLocale); } } From 91dafbcea8fe66127d5fbab5bb06d7712701feba Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Mon, 22 Jun 2020 09:29:31 -0400 Subject: [PATCH 0183/3230] Fix typos. --- .../java/org/apache/commons/lang3/StringUtilsTest.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/test/java/org/apache/commons/lang3/StringUtilsTest.java b/src/test/java/org/apache/commons/lang3/StringUtilsTest.java index 3230aa0416a..622cad56678 100644 --- a/src/test/java/org/apache/commons/lang3/StringUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/StringUtilsTest.java @@ -3279,12 +3279,12 @@ public void testToRootLowerCase() { assertEquals("title", "TITLE".toLowerCase(Locale.ROOT)); assertEquals("title", StringUtils.toRootLowerCase("TITLE")); // Make sure we are not using the default Locale: - final Locale defaultLocales = Locale.getDefault(); + final Locale defaultLocale = Locale.getDefault(); try { Locale.setDefault(TURKISH); assertEquals("title", StringUtils.toRootLowerCase("TITLE")); } finally { - Locale.setDefault(defaultLocales); + Locale.setDefault(defaultLocale); } } @@ -3299,12 +3299,12 @@ public void testToRootUpperCase() { assertEquals("TITLE", "title".toUpperCase(Locale.ROOT)); assertEquals("TITLE", StringUtils.toRootUpperCase("title")); // Make sure we are not using the default Locale: - final Locale defaultLocales = Locale.getDefault(); + final Locale defaultLocale = Locale.getDefault(); try { Locale.setDefault(TURKISH); assertEquals("TITLE", StringUtils.toRootUpperCase("title")); } finally { - Locale.setDefault(defaultLocales); + Locale.setDefault(defaultLocale); } } From 5ffe0080744ba6ed2707767653a673d51d2c0c23 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Mon, 22 Jun 2020 09:32:10 -0400 Subject: [PATCH 0184/3230] Undo "fix", @DefaultLocale is used in this test. --- .../lang3/StringUtilsContainsTest.java | 40 +++++++------------ 1 file changed, 14 insertions(+), 26 deletions(-) diff --git a/src/test/java/org/apache/commons/lang3/StringUtilsContainsTest.java b/src/test/java/org/apache/commons/lang3/StringUtilsContainsTest.java index fb1db992f3e..4a0a4ccf535 100644 --- a/src/test/java/org/apache/commons/lang3/StringUtilsContainsTest.java +++ b/src/test/java/org/apache/commons/lang3/StringUtilsContainsTest.java @@ -232,33 +232,21 @@ public void testContainsAny_StringStringArray() { public void testContainsIgnoreCase_LocaleIndependence() { final Locale[] locales = { Locale.ENGLISH, new Locale("tr"), Locale.getDefault() }; - final String[][] tdata = { - { "i", "I" }, - { "I", "i" }, - { "\u03C2", "\u03C3" }, - { "\u03A3", "\u03C2" }, - { "\u03A3", "\u03C3" }, - }; - - final String[][] fdata = { - { "\u00DF", "SS" }, - }; - - final Locale defaultLocale = Locale.getDefault(); - try { - for (final Locale testLocale : locales) { - Locale.setDefault(testLocale); - for (int j = 0; j < tdata.length; j++) { - assertTrue(StringUtils.containsIgnoreCase(tdata[j][0], tdata[j][1]), - Locale.getDefault() + ": " + j + " " + tdata[j][0] + " " + tdata[j][1]); - } - for (int j = 0; j < fdata.length; j++) { - assertFalse(StringUtils.containsIgnoreCase(fdata[j][0], fdata[j][1]), - Locale.getDefault() + ": " + j + " " + fdata[j][0] + " " + fdata[j][1]); - } + final String[][] tdata = { { "i", "I" }, { "I", "i" }, { "\u03C2", "\u03C3" }, { "\u03A3", "\u03C2" }, + { "\u03A3", "\u03C3" }, }; + + final String[][] fdata = { { "\u00DF", "SS" }, }; + + for (final Locale testLocale : locales) { + Locale.setDefault(testLocale); + for (int j = 0; j < tdata.length; j++) { + assertTrue(StringUtils.containsIgnoreCase(tdata[j][0], tdata[j][1]), + Locale.getDefault() + ": " + j + " " + tdata[j][0] + " " + tdata[j][1]); + } + for (int j = 0; j < fdata.length; j++) { + assertFalse(StringUtils.containsIgnoreCase(fdata[j][0], fdata[j][1]), + Locale.getDefault() + ": " + j + " " + fdata[j][0] + " " + fdata[j][1]); } - } finally { - Locale.setDefault(defaultLocale); } } From 744da0e2555dd6439a6c95a927bf8a638ea83f95 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Tue, 23 Jun 2020 10:40:33 -0400 Subject: [PATCH 0185/3230] Update dependencies. - org.apache.commons:commons-parent 50 -> 51 - biz.aQute.bnd:biz.aQute.bndlib 5.1.0 -> 5.1.1 - com.github.spotbugs:spotbugs 4.0.4 -> 4.0.5 --- pom.xml | 8 ++++---- src/changes/changes.xml | 3 ++- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/pom.xml b/pom.xml index 07d8cafc474..d340fe6b86a 100644 --- a/pom.xml +++ b/pom.xml @@ -22,7 +22,7 @@ org.apache.commons commons-parent - 50 + 51 4.0.0 commons-lang3 @@ -613,7 +613,7 @@ 0.8.5 3.0.0-M4 - 3.1.1 + 3.2.0 true @@ -764,7 +764,7 @@ com.github.spotbugs spotbugs - 4.0.4 + 4.0.5 @@ -778,7 +778,7 @@ biz.aQute.bnd biz.aQute.bndlib - 5.1.0 + 5.1.1 diff --git a/src/changes/changes.xml b/src/changes/changes.xml index f5e3fa5de66..0ecd04e420a 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -48,9 +48,10 @@ The type attribute can be add,update,fix,remove. remove encoding and docEncoding and use inherited values from commons-parent Fix Javadoc for StringUtils.appendIfMissingIgnoreCase() #507. + org.apache.commons:commons-parent 50 -> 51. org.junit-pioneer:junit-pioneer 0.5.4 -> 0.6.0. org.junit.jupiter:junit-jupiter 5.6.0 -> 5.6.1. - com.github.spotbugs:spotbugs 4.0.0 -> 4.0.4. + com.github.spotbugs:spotbugs 4.0.0 -> 4.0.5. com.puppycrawl.tools:checkstyle 8.29 -> 8.33. Simplify null checks in Pair.hashCode() using Objects.hashCode(). #517. Simplify null checks in Triple.hashCode() using Objects.hashCode(). #516. From 341aaa797d515a1fce5def6b41cdc481701ad389 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Tue, 23 Jun 2020 11:07:22 -0400 Subject: [PATCH 0186/3230] Added ImmutablePair factory methods left() and right(). --- src/changes/changes.xml | 1 + .../commons/lang3/tuple/ImmutablePair.java | 30 +++++++++++++++ .../lang3/tuple/ImmutablePairTest.java | 37 +++++++++++++++++++ 3 files changed, 68 insertions(+) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 0ecd04e420a..03989d56443 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -79,6 +79,7 @@ The type attribute can be add,update,fix,remove. Use Java 8 lambdas and Map operations. Change removeLastFieldSeparator to use endsWith #550. Change a Pattern to a static final field, for not letting it compile each time the function invoked. #542. + Added ImmutablePair factory methods left() and right(). diff --git a/src/main/java/org/apache/commons/lang3/tuple/ImmutablePair.java b/src/main/java/org/apache/commons/lang3/tuple/ImmutablePair.java index 9c106e63034..e6d4b925541 100644 --- a/src/main/java/org/apache/commons/lang3/tuple/ImmutablePair.java +++ b/src/main/java/org/apache/commons/lang3/tuple/ImmutablePair.java @@ -69,6 +69,21 @@ public static ImmutablePair[] emptyArray() { return (ImmutablePair[]) EMPTY_ARRAY; } + /** + *

      Creates an immutable pair of two objects inferring the generic types.

      + * + *

      This factory allows the pair to be created using inference to + * obtain the generic types.

      + * + * @param the left element type + * @param left the left element, may be null + * @return a pair formed from the two parameters, not null + * @since 3.11 + */ + public static Pair left(final L left) { + return ImmutablePair.of(left, null); + } + /** * Returns an immutable pair of nulls. * @@ -122,6 +137,21 @@ public static ImmutablePair of(final Map.Entry pair) { return new ImmutablePair<>(left, right); } + /** + *

      Creates an immutable pair of two objects inferring the generic types.

      + * + *

      This factory allows the pair to be created using inference to + * obtain the generic types.

      + * + * @param the right element type + * @param right the right element, may be null + * @return a pair formed from the two parameters, not null + * @since 3.11 + */ + public static Pair right(final R right) { + return ImmutablePair.of(null, right); + } + /** Left object */ public final L left; diff --git a/src/test/java/org/apache/commons/lang3/tuple/ImmutablePairTest.java b/src/test/java/org/apache/commons/lang3/tuple/ImmutablePairTest.java index f4e189a58bc..6dafe717445 100644 --- a/src/test/java/org/apache/commons/lang3/tuple/ImmutablePairTest.java +++ b/src/test/java/org/apache/commons/lang3/tuple/ImmutablePairTest.java @@ -21,6 +21,7 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -209,4 +210,40 @@ public void testUseAsKeyOfTreeMap() { assertEquals(item.getLeft() + "" + item.getRight(), entry.getValue()); } } + + @Test + public void testComparableLeftOnly() { + final Pair pair1 = ImmutablePair.left("A"); + final Pair pair2 = ImmutablePair.left("B"); + assertEquals("A", pair1.getLeft()); + assertEquals("B", pair2.getLeft()); + assertEquals(0, pair1.compareTo(pair1)); + assertTrue(pair1.compareTo(pair2) < 0); + assertEquals(0, pair2.compareTo(pair2)); + assertTrue(pair2.compareTo(pair1) > 0); + } + + @Test + public void testComparableRightOnly() { + final Pair pair1 = ImmutablePair.right("A"); + final Pair pair2 = ImmutablePair.right("B"); + assertEquals("A", pair1.getRight()); + assertEquals("B", pair2.getRight()); + assertEquals(0, pair1.compareTo(pair1)); + assertTrue(pair1.compareTo(pair2) < 0); + assertEquals(0, pair2.compareTo(pair2)); + assertTrue(pair2.compareTo(pair1) > 0); + } + + @Test + public void testToStringLeft() { + final Pair pair = ImmutablePair.left("Key"); + assertEquals("(Key,null)", pair.toString()); + } + + @Test + public void testToStringRight() { + final Pair pair = ImmutablePair.right("Value"); + assertEquals("(null,Value)", pair.toString()); + } } From 6315e8c138d2b23427e77271bfad2359432a570b Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Tue, 23 Jun 2020 14:22:46 -0400 Subject: [PATCH 0187/3230] Javadoc. --- src/main/java/org/apache/commons/lang3/tuple/ImmutablePair.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main/java/org/apache/commons/lang3/tuple/ImmutablePair.java b/src/main/java/org/apache/commons/lang3/tuple/ImmutablePair.java index e6d4b925541..da3011dd0de 100644 --- a/src/main/java/org/apache/commons/lang3/tuple/ImmutablePair.java +++ b/src/main/java/org/apache/commons/lang3/tuple/ImmutablePair.java @@ -76,6 +76,7 @@ public static ImmutablePair[] emptyArray() { * obtain the generic types.

      * * @param the left element type + * @param the right element type * @param left the left element, may be null * @return a pair formed from the two parameters, not null * @since 3.11 @@ -143,6 +144,7 @@ public static ImmutablePair of(final Map.Entry pair) { *

      This factory allows the pair to be created using inference to * obtain the generic types.

      * + * @param the left element type * @param the right element type * @param right the right element, may be null * @return a pair formed from the two parameters, not null From 45b32d3a9c9695af12083dfd91dd2b3f4c2912df Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Tue, 23 Jun 2020 15:10:54 -0400 Subject: [PATCH 0188/3230] Sort members. --- .../org/apache/commons/lang3/ObjectUtils.java | 1646 ++++++++--------- 1 file changed, 823 insertions(+), 823 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/ObjectUtils.java b/src/main/java/org/apache/commons/lang3/ObjectUtils.java index 940dcd808cc..f1e5fa2a9a1 100644 --- a/src/main/java/org/apache/commons/lang3/ObjectUtils.java +++ b/src/main/java/org/apache/commons/lang3/ObjectUtils.java @@ -48,6 +48,46 @@ // because it is part of the signature of deprecated methods public class ObjectUtils { + // Null + //----------------------------------------------------------------------- + /** + *

      Class used as a null placeholder where {@code null} + * has another meaning.

      + * + *

      For example, in a {@code HashMap} the + * {@link java.util.HashMap#get(java.lang.Object)} method returns + * {@code null} if the {@code Map} contains {@code null} or if there is + * no matching key. The {@code Null} placeholder can be used to distinguish + * between these two cases.

      + * + *

      Another example is {@code Hashtable}, where {@code null} + * cannot be stored.

      + */ + public static class Null implements Serializable { + /** + * Required for serialization support. Declare serialization compatibility with Commons Lang 1.0 + * + * @see java.io.Serializable + */ + private static final long serialVersionUID = 7092611880189329093L; + + /** + * Restricted constructor - singleton. + */ + Null() { + super(); + } + + /** + *

      Ensure singleton.

      + * + * @return the singleton value + */ + private Object readResolve() { + return NULL; + } + } + private static final char AT_SIGN = '@'; /** @@ -68,863 +108,767 @@ public class ObjectUtils { public static final Null NULL = new Null(); /** - *

      {@code ObjectUtils} instances should NOT be constructed in - * standard programming. Instead, the static methods on the class should - * be used, such as {@code ObjectUtils.defaultIfNull("a","b");}.

      - * - *

      This constructor is public to permit tools that require a JavaBean - * instance to operate.

      - */ - public ObjectUtils() { - super(); - } - - // Empty checks - //----------------------------------------------------------------------- - /** - *

      Checks if an Object is empty or null.

      + * Checks if all values in the array are not {@code nulls}. * - * The following types are supported: - *
        - *
      • {@link CharSequence}: Considered empty if its length is zero.
      • - *
      • {@code Array}: Considered empty if its length is zero.
      • - *
      • {@link Collection}: Considered empty if it has zero elements.
      • - *
      • {@link Map}: Considered empty if it has zero key-value mappings.
      • - *
      + *

      + * If any value is {@code null} or the array is {@code null} then + * {@code false} is returned. If all elements in array are not + * {@code null} or the array is empty (contains no elements) {@code true} + * is returned. + *

      * *
      -     * ObjectUtils.isEmpty(null)             = true
      -     * ObjectUtils.isEmpty("")               = true
      -     * ObjectUtils.isEmpty("ab")             = false
      -     * ObjectUtils.isEmpty(new int[]{})      = true
      -     * ObjectUtils.isEmpty(new int[]{1,2,3}) = false
      -     * ObjectUtils.isEmpty(1234)             = false
      +     * ObjectUtils.allNotNull(*)             = true
      +     * ObjectUtils.allNotNull(*, *)          = true
      +     * ObjectUtils.allNotNull(null)          = false
      +     * ObjectUtils.allNotNull(null, null)    = false
      +     * ObjectUtils.allNotNull(null, *)       = false
      +     * ObjectUtils.allNotNull(*, null)       = false
      +     * ObjectUtils.allNotNull(*, *, null, *) = false
            * 
      * - * @param object the {@code Object} to test, may be {@code null} - * @return {@code true} if the object has a supported type and is empty or null, - * {@code false} otherwise - * @since 3.9 + * @param values the values to test, may be {@code null} or empty + * @return {@code false} if there is at least one {@code null} value in the array or the array is {@code null}, + * {@code true} if all values in the array are not {@code null}s or array contains no elements. + * @since 3.5 */ - public static boolean isEmpty(final Object object) { - if (object == null) { - return true; - } - if (object instanceof CharSequence) { - return ((CharSequence) object).length() == 0; - } - if (object.getClass().isArray()) { - return Array.getLength(object) == 0; - } - if (object instanceof Collection) { - return ((Collection) object).isEmpty(); + public static boolean allNotNull(final Object... values) { + if (values == null) { + return false; } - if (object instanceof Map) { - return ((Map) object).isEmpty(); + + for (final Object val : values) { + if (val == null) { + return false; + } } - return false; + + return true; } /** - *

      Checks if an Object is not empty and not null.

      + * Checks if any value in the given array is not {@code null}. * - * The following types are supported: - *
        - *
      • {@link CharSequence}: Considered empty if its length is zero.
      • - *
      • {@code Array}: Considered empty if its length is zero.
      • - *
      • {@link Collection}: Considered empty if it has zero elements.
      • - *
      • {@link Map}: Considered empty if it has zero key-value mappings.
      • - *
      + *

      + * If all the values are {@code null} or the array is {@code null} + * or empty then {@code false} is returned. Otherwise {@code true} is returned. + *

      * *
      -     * ObjectUtils.isNotEmpty(null)             = false
      -     * ObjectUtils.isNotEmpty("")               = false
      -     * ObjectUtils.isNotEmpty("ab")             = true
      -     * ObjectUtils.isNotEmpty(new int[]{})      = false
      -     * ObjectUtils.isNotEmpty(new int[]{1,2,3}) = true
      -     * ObjectUtils.isNotEmpty(1234)             = true
      +     * ObjectUtils.anyNotNull(*)                = true
      +     * ObjectUtils.anyNotNull(*, null)          = true
      +     * ObjectUtils.anyNotNull(null, *)          = true
      +     * ObjectUtils.anyNotNull(null, null, *, *) = true
      +     * ObjectUtils.anyNotNull(null)             = false
      +     * ObjectUtils.anyNotNull(null, null)       = false
            * 
      * - * @param object the {@code Object} to test, may be {@code null} - * @return {@code true} if the object has an unsupported type or is not empty - * and not null, {@code false} otherwise - * @since 3.9 + * @param values the values to test, may be {@code null} or empty + * @return {@code true} if there is at least one non-null value in the array, + * {@code false} if all values in the array are {@code null}s. + * If the array is {@code null} or empty {@code false} is also returned. + * @since 3.5 */ - public static boolean isNotEmpty(final Object object) { - return !isEmpty(object); + public static boolean anyNotNull(final Object... values) { + return firstNonNull(values) != null; } + // cloning + //----------------------------------------------------------------------- /** - *

      Returns a default value if the object passed is {@code null}.

      - * - *
      -     * ObjectUtils.defaultIfNull(null, null)      = null
      -     * ObjectUtils.defaultIfNull(null, "")        = ""
      -     * ObjectUtils.defaultIfNull(null, "zz")      = "zz"
      -     * ObjectUtils.defaultIfNull("abc", *)        = "abc"
      -     * ObjectUtils.defaultIfNull(Boolean.TRUE, *) = Boolean.TRUE
      -     * 
      + *

      Clone an object.

      * * @param the type of the object - * @param object the {@code Object} to test, may be {@code null} - * @param defaultValue the default value to return, may be {@code null} - * @return {@code object} if it is not {@code null}, defaultValue otherwise - * TODO Rename to getIfNull in 4.0 - */ - public static T defaultIfNull(final T object, final T defaultValue) { - return object != null ? object : defaultValue; - } - - /** - *

      Returns the first value in the array which is not {@code null}. - * If all the values are {@code null} or the array is {@code null} - * or empty then {@code null} is returned.

      - * - *
      -     * ObjectUtils.firstNonNull(null, null)      = null
      -     * ObjectUtils.firstNonNull(null, "")        = ""
      -     * ObjectUtils.firstNonNull(null, null, "")  = ""
      -     * ObjectUtils.firstNonNull(null, "zz")      = "zz"
      -     * ObjectUtils.firstNonNull("abc", *)        = "abc"
      -     * ObjectUtils.firstNonNull(null, "xyz", *)  = "xyz"
      -     * ObjectUtils.firstNonNull(Boolean.TRUE, *) = Boolean.TRUE
      -     * ObjectUtils.firstNonNull()                = null
      -     * 
      - * - * @param the component type of the array - * @param values the values to test, may be {@code null} or empty - * @return the first value from {@code values} which is not {@code null}, - * or {@code null} if there are no non-null values + * @param obj the object to clone, null returns null + * @return the clone if the object implements {@link Cloneable} otherwise {@code null} + * @throws CloneFailedException if the object is cloneable and the clone operation fails * @since 3.0 */ - @SafeVarargs - public static T firstNonNull(final T... values) { - if (values != null) { - for (final T val : values) { - if (val != null) { - return val; + public static T clone(final T obj) { + if (obj instanceof Cloneable) { + final Object result; + if (obj.getClass().isArray()) { + final Class componentType = obj.getClass().getComponentType(); + if (componentType.isPrimitive()) { + int length = Array.getLength(obj); + result = Array.newInstance(componentType, length); + while (length-- > 0) { + Array.set(result, length, Array.get(obj, length)); + } + } else { + result = ((Object[]) obj).clone(); + } + } else { + try { + final Method clone = obj.getClass().getMethod("clone"); + result = clone.invoke(obj); + } catch (final NoSuchMethodException e) { + throw new CloneFailedException("Cloneable type " + + obj.getClass().getName() + + " has no clone method", e); + } catch (final IllegalAccessException e) { + throw new CloneFailedException("Cannot clone Cloneable type " + + obj.getClass().getName(), e); + } catch (final InvocationTargetException e) { + throw new CloneFailedException("Exception cloning Cloneable type " + + obj.getClass().getName(), e.getCause()); } } + @SuppressWarnings("unchecked") // OK because input is of type T + final T checked = (T) result; + return checked; } + return null; } /** - *

      Executes the given suppliers in order and returns the first return - * value where a value other than {@code null} is returned. - * Once a non-{@code null} value is obtained, all following suppliers are - * not executed anymore. - * If all the return values are {@code null} or no suppliers are provided - * then {@code null} is returned.

      + *

      Clone an object if possible.

      * - *
      -     * ObjectUtils.firstNonNullLazy(null, () -> null) = null
      -     * ObjectUtils.firstNonNullLazy(() -> null, () -> "") = ""
      -     * ObjectUtils.firstNonNullLazy(() -> "", () -> throw new IllegalStateException()) = ""
      -     * ObjectUtils.firstNonNullLazy(() -> null, () -> "zz) = "zz"
      -     * ObjectUtils.firstNonNullLazy() = null
      -     * 
      + *

      This method is similar to {@link #clone(Object)}, but will return the provided + * instance as the return value instead of {@code null} if the instance + * is not cloneable. This is more convenient if the caller uses different + * implementations (e.g. of a service) and some of the implementations do not allow concurrent + * processing or have state. In such cases the implementation can simply provide a proper + * clone implementation and the caller's code does not have to change.

      * - * @param the type of the return values - * @param suppliers the suppliers returning the values to test. - * {@code null} values are ignored. - * Suppliers may return {@code null} or a value of type @{code T} - * @return the first return value from {@code suppliers} which is not {@code null}, - * or {@code null} if there are no non-null values - * @since 3.10 + * @param the type of the object + * @param obj the object to clone, null returns null + * @return the clone if the object implements {@link Cloneable} otherwise the object itself + * @throws CloneFailedException if the object is cloneable and the clone operation fails + * @since 3.0 */ - @SafeVarargs - public static T getFirstNonNull(final Supplier... suppliers) { - if (suppliers != null) { - for (final Supplier supplier : suppliers) { - if (supplier != null) { - final T value = supplier.get(); - if (value != null) { - return value; - } - } - } - } - return null; + public static T cloneIfPossible(final T obj) { + final T clone = clone(obj); + return clone == null ? obj : clone; } /** - *

      - * Returns the given {@code object} is it is non-null, otherwise returns the Supplier's {@link Supplier#get()} - * value. - *

      - * - *

      - * The caller responsible for thread-safety and exception handling of default value supplier. - *

      - * - *
      -     * ObjectUtils.getIfNull(null, () -> null)     = null
      -     * ObjectUtils.getIfNull(null, null)              = null
      -     * ObjectUtils.getIfNull(null, () -> "")       = ""
      -     * ObjectUtils.getIfNull(null, () -> "zz")     = "zz"
      -     * ObjectUtils.getIfNull("abc", *)                = "abc"
      -     * ObjectUtils.getIfNull(Boolean.TRUE, *)         = Boolean.TRUE
      -     * 
      + *

      Null safe comparison of Comparables. + * {@code null} is assumed to be less than a non-{@code null} value.

      * - * @param the type of the object - * @param object the {@code Object} to test, may be {@code null} - * @param defaultSupplier the default value to return, may be {@code null} - * @return {@code object} if it is not {@code null}, {@code defaultValueSupplier.get()} otherwise - * @since 3.10 + * @param type of the values processed by this method + * @param c1 the first comparable, may be null + * @param c2 the second comparable, may be null + * @return a negative value if c1 < c2, zero if c1 = c2 + * and a positive value if c1 > c2 */ - public static T getIfNull(final T object, final Supplier defaultSupplier) { - return object != null ? object : defaultSupplier == null ? null : defaultSupplier.get(); + public static > int compare(final T c1, final T c2) { + return compare(c1, c2, false); } /** - * Checks if any value in the given array is not {@code null}. + *

      Null safe comparison of Comparables.

      * - *

      - * If all the values are {@code null} or the array is {@code null} - * or empty then {@code false} is returned. Otherwise {@code true} is returned. - *

      + * @param type of the values processed by this method + * @param c1 the first comparable, may be null + * @param c2 the second comparable, may be null + * @param nullGreater if true {@code null} is considered greater + * than a non-{@code null} value or if false {@code null} is + * considered less than a Non-{@code null} value + * @return a negative value if c1 < c2, zero if c1 = c2 + * and a positive value if c1 > c2 + * @see java.util.Comparator#compare(Object, Object) + */ + public static > int compare(final T c1, final T c2, final boolean nullGreater) { + if (c1 == c2) { + return 0; + } else if (c1 == null) { + return nullGreater ? 1 : -1; + } else if (c2 == null) { + return nullGreater ? -1 : 1; + } + return c1.compareTo(c2); + } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., * *
      -     * ObjectUtils.anyNotNull(*)                = true
      -     * ObjectUtils.anyNotNull(*, null)          = true
      -     * ObjectUtils.anyNotNull(null, *)          = true
      -     * ObjectUtils.anyNotNull(null, null, *, *) = true
      -     * ObjectUtils.anyNotNull(null)             = false
      -     * ObjectUtils.anyNotNull(null, null)       = false
      +     *     public final static boolean MAGIC_FLAG = ObjectUtils.CONST(true);
            * 
      * - * @param values the values to test, may be {@code null} or empty - * @return {@code true} if there is at least one non-null value in the array, - * {@code false} if all values in the array are {@code null}s. - * If the array is {@code null} or empty {@code false} is also returned. - * @since 3.5 + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the boolean value to return + * @return the boolean v, unchanged + * @since 3.2 */ - public static boolean anyNotNull(final Object... values) { - return firstNonNull(values) != null; + public static boolean CONST(final boolean v) { + return v; } /** - * Checks if all values in the array are not {@code nulls}. - * - *

      - * If any value is {@code null} or the array is {@code null} then - * {@code false} is returned. If all elements in array are not - * {@code null} or the array is empty (contains no elements) {@code true} - * is returned. - *

      + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., * *
      -     * ObjectUtils.allNotNull(*)             = true
      -     * ObjectUtils.allNotNull(*, *)          = true
      -     * ObjectUtils.allNotNull(null)          = false
      -     * ObjectUtils.allNotNull(null, null)    = false
      -     * ObjectUtils.allNotNull(null, *)       = false
      -     * ObjectUtils.allNotNull(*, null)       = false
      -     * ObjectUtils.allNotNull(*, *, null, *) = false
      +     *     public final static byte MAGIC_BYTE = ObjectUtils.CONST((byte) 127);
            * 
      * - * @param values the values to test, may be {@code null} or empty - * @return {@code false} if there is at least one {@code null} value in the array or the array is {@code null}, - * {@code true} if all values in the array are not {@code null}s or array contains no elements. - * @since 3.5 + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the byte value to return + * @return the byte v, unchanged + * @since 3.2 */ - public static boolean allNotNull(final Object... values) { - if (values == null) { - return false; - } - - for (final Object val : values) { - if (val == null) { - return false; - } - } - - return true; + public static byte CONST(final byte v) { + return v; } - // Null-safe equals/hashCode - //----------------------------------------------------------------------- /** - *

      Compares two objects for equality, where either one or both - * objects may be {@code null}.

      + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., * *
      -     * ObjectUtils.equals(null, null)                  = true
      -     * ObjectUtils.equals(null, "")                    = false
      -     * ObjectUtils.equals("", null)                    = false
      -     * ObjectUtils.equals("", "")                      = true
      -     * ObjectUtils.equals(Boolean.TRUE, null)          = false
      -     * ObjectUtils.equals(Boolean.TRUE, "true")        = false
      -     * ObjectUtils.equals(Boolean.TRUE, Boolean.TRUE)  = true
      -     * ObjectUtils.equals(Boolean.TRUE, Boolean.FALSE) = false
      +     *     public final static char MAGIC_CHAR = ObjectUtils.CONST('a');
            * 
      * - * @param object1 the first object, may be {@code null} - * @param object2 the second object, may be {@code null} - * @return {@code true} if the values of both objects are the same - * @deprecated this method has been replaced by {@code java.util.Objects.equals(Object, Object)} in Java 7 and will - * be removed from future releases. + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the char value to return + * @return the char v, unchanged + * @since 3.2 */ - @Deprecated - public static boolean equals(final Object object1, final Object object2) { - if (object1 == object2) { - return true; - } - if (object1 == null || object2 == null) { - return false; - } - return object1.equals(object2); + public static char CONST(final char v) { + return v; } /** - *

      Compares two objects for inequality, where either one or both - * objects may be {@code null}.

      + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., * *
      -     * ObjectUtils.notEqual(null, null)                  = false
      -     * ObjectUtils.notEqual(null, "")                    = true
      -     * ObjectUtils.notEqual("", null)                    = true
      -     * ObjectUtils.notEqual("", "")                      = false
      -     * ObjectUtils.notEqual(Boolean.TRUE, null)          = true
      -     * ObjectUtils.notEqual(Boolean.TRUE, "true")        = true
      -     * ObjectUtils.notEqual(Boolean.TRUE, Boolean.TRUE)  = false
      -     * ObjectUtils.notEqual(Boolean.TRUE, Boolean.FALSE) = true
      +     *     public final static double MAGIC_DOUBLE = ObjectUtils.CONST(1.0);
            * 
      * - * @param object1 the first object, may be {@code null} - * @param object2 the second object, may be {@code null} - * @return {@code false} if the values of both objects are the same + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the double value to return + * @return the double v, unchanged + * @since 3.2 */ - public static boolean notEqual(final Object object1, final Object object2) { - return !equals(object1, object2); + public static double CONST(final double v) { + return v; } /** - *

      Gets the hash code of an object returning zero when the - * object is {@code null}.

      + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., * *
      -     * ObjectUtils.hashCode(null)   = 0
      -     * ObjectUtils.hashCode(obj)    = obj.hashCode()
      +     *     public final static float MAGIC_FLOAT = ObjectUtils.CONST(1.0f);
            * 
      * - * @param obj the object to obtain the hash code of, may be {@code null} - * @return the hash code of the object, or zero if null - * @since 2.1 - * @deprecated this method has been replaced by {@code java.util.Objects.hashCode(Object)} in Java 7 and will be - * removed in future releases + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the float value to return + * @return the float v, unchanged + * @since 3.2 */ - @Deprecated - public static int hashCode(final Object obj) { - // hashCode(Object) retained for performance, as hash code is often critical - return obj == null ? 0 : obj.hashCode(); + public static float CONST(final float v) { + return v; } /** - *

      Gets the hash code for multiple objects.

      - * - *

      This allows a hash code to be rapidly calculated for a number of objects. - * The hash code for a single object is the not same as {@link #hashCode(Object)}. - * The hash code for multiple objects is the same as that calculated by an - * {@code ArrayList} containing the specified objects.

      + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., * *
      -     * ObjectUtils.hashCodeMulti()                 = 1
      -     * ObjectUtils.hashCodeMulti((Object[]) null)  = 1
      -     * ObjectUtils.hashCodeMulti(a)                = 31 + a.hashCode()
      -     * ObjectUtils.hashCodeMulti(a,b)              = (31 + a.hashCode()) * 31 + b.hashCode()
      -     * ObjectUtils.hashCodeMulti(a,b,c)            = ((31 + a.hashCode()) * 31 + b.hashCode()) * 31 + c.hashCode()
      +     *     public final static int MAGIC_INT = ObjectUtils.CONST(123);
            * 
      * - * @param objects the objects to obtain the hash code of, may be {@code null} - * @return the hash code of the objects, or zero if null - * @since 3.0 - * @deprecated this method has been replaced by {@code java.util.Objects.hash(Object...)} in Java 7 and will be - * removed in future releases. + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the int value to return + * @return the int v, unchanged + * @since 3.2 */ - @Deprecated - public static int hashCodeMulti(final Object... objects) { - int hash = 1; - if (objects != null) { - for (final Object object : objects) { - final int tmpHash = hashCode(object); - hash = hash * 31 + tmpHash; - } - } - return hash; + public static int CONST(final int v) { + return v; } - // Identity ToString - //----------------------------------------------------------------------- /** - *

      Gets the toString that would be produced by {@code Object} - * if a class did not override toString itself. {@code null} - * will return {@code null}.

      + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., * *
      -     * ObjectUtils.identityToString(null)         = null
      -     * ObjectUtils.identityToString("")           = "java.lang.String@1e23"
      -     * ObjectUtils.identityToString(Boolean.TRUE) = "java.lang.Boolean@7fa"
      +     *     public final static long MAGIC_LONG = ObjectUtils.CONST(123L);
            * 
      * - * @param object the object to create a toString for, may be - * {@code null} - * @return the default toString text, or {@code null} if - * {@code null} passed in + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the long value to return + * @return the long v, unchanged + * @since 3.2 */ - public static String identityToString(final Object object) { - if (object == null) { - return null; - } - final String name = object.getClass().getName(); - final String hexString = Integer.toHexString(System.identityHashCode(object)); - final StringBuilder builder = new StringBuilder(name.length() + 1 + hexString.length()); - // @formatter:off - builder.append(name) - .append(AT_SIGN) - .append(hexString); - // @formatter:off - return builder.toString(); + public static long CONST(final long v) { + return v; } /** - *

      Appends the toString that would be produced by {@code Object} - * if a class did not override toString itself. {@code null} - * will throw a NullPointerException for either of the two parameters.

      + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., * *
      -     * ObjectUtils.identityToString(appendable, "")            = appendable.append("java.lang.String@1e23"
      -     * ObjectUtils.identityToString(appendable, Boolean.TRUE)  = appendable.append("java.lang.Boolean@7fa"
      -     * ObjectUtils.identityToString(appendable, Boolean.TRUE)  = appendable.append("java.lang.Boolean@7fa")
      +     *     public final static short MAGIC_SHORT = ObjectUtils.CONST((short) 123);
            * 
      * - * @param appendable the appendable to append to - * @param object the object to create a toString for - * @throws IOException if an I/O error occurs + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the short value to return + * @return the short v, unchanged * @since 3.2 */ - public static void identityToString(final Appendable appendable, final Object object) throws IOException { - Validate.notNull(object, "Cannot get the toString of a null object"); - appendable.append(object.getClass().getName()) - .append(AT_SIGN) - .append(Integer.toHexString(System.identityHashCode(object))); + public static short CONST(final short v) { + return v; } /** - *

      Appends the toString that would be produced by {@code Object} - * if a class did not override toString itself. {@code null} - * will throw a NullPointerException for either of the two parameters.

      + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., * *
      -     * ObjectUtils.identityToString(builder, "")            = builder.append("java.lang.String@1e23"
      -     * ObjectUtils.identityToString(builder, Boolean.TRUE)  = builder.append("java.lang.Boolean@7fa"
      -     * ObjectUtils.identityToString(builder, Boolean.TRUE)  = builder.append("java.lang.Boolean@7fa")
      +     *     public final static String MAGIC_STRING = ObjectUtils.CONST("abc");
            * 
      * - * @param builder the builder to append to - * @param object the object to create a toString for + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param the Object type + * @param v the genericized Object value to return (typically a String). + * @return the genericized Object v, unchanged (typically a String). * @since 3.2 - * @deprecated as of 3.6, because StrBuilder was moved to commons-text, - * use one of the other {@code identityToString} methods instead */ - @Deprecated - public static void identityToString(final StrBuilder builder, final Object object) { - Validate.notNull(object, "Cannot get the toString of a null object"); - final String name = object.getClass().getName(); - final String hexString = Integer.toHexString(System.identityHashCode(object)); - builder.ensureCapacity(builder.length() + name.length() + 1 + hexString.length()); - builder.append(name) - .append(AT_SIGN) - .append(hexString); + public static T CONST(final T v) { + return v; } /** - *

      Appends the toString that would be produced by {@code Object} - * if a class did not override toString itself. {@code null} - * will throw a NullPointerException for either of the two parameters.

      + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., * *
      -     * ObjectUtils.identityToString(buf, "")            = buf.append("java.lang.String@1e23"
      -     * ObjectUtils.identityToString(buf, Boolean.TRUE)  = buf.append("java.lang.Boolean@7fa"
      -     * ObjectUtils.identityToString(buf, Boolean.TRUE)  = buf.append("java.lang.Boolean@7fa")
      +     *     public final static byte MAGIC_BYTE = ObjectUtils.CONST_BYTE(127);
            * 
      * - * @param buffer the buffer to append to - * @param object the object to create a toString for - * @since 2.4 + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the byte literal (as an int) value to return + * @throws IllegalArgumentException if the value passed to v + * is larger than a byte, that is, smaller than -128 or + * larger than 127. + * @return the byte v, unchanged + * @since 3.2 */ - public static void identityToString(final StringBuffer buffer, final Object object) { - Validate.notNull(object, "Cannot get the toString of a null object"); - final String name = object.getClass().getName(); - final String hexString = Integer.toHexString(System.identityHashCode(object)); - buffer.ensureCapacity(buffer.length() + name.length() + 1 + hexString.length()); - buffer.append(name) - .append(AT_SIGN) - .append(hexString); + public static byte CONST_BYTE(final int v) { + if (v < Byte.MIN_VALUE || v > Byte.MAX_VALUE) { + throw new IllegalArgumentException("Supplied value must be a valid byte literal between -128 and 127: [" + v + "]"); + } + return (byte) v; } /** - *

      Appends the toString that would be produced by {@code Object} - * if a class did not override toString itself. {@code null} - * will throw a NullPointerException for either of the two parameters.

      + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., * *
      -     * ObjectUtils.identityToString(builder, "")            = builder.append("java.lang.String@1e23"
      -     * ObjectUtils.identityToString(builder, Boolean.TRUE)  = builder.append("java.lang.Boolean@7fa"
      -     * ObjectUtils.identityToString(builder, Boolean.TRUE)  = builder.append("java.lang.Boolean@7fa")
      +     *     public final static short MAGIC_SHORT = ObjectUtils.CONST_SHORT(127);
            * 
      * - * @param builder the builder to append to - * @param object the object to create a toString for + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the short literal (as an int) value to return + * @throws IllegalArgumentException if the value passed to v + * is larger than a short, that is, smaller than -32768 or + * larger than 32767. + * @return the byte v, unchanged * @since 3.2 */ - public static void identityToString(final StringBuilder builder, final Object object) { - Validate.notNull(object, "Cannot get the toString of a null object"); - final String name = object.getClass().getName(); - final String hexString = Integer.toHexString(System.identityHashCode(object)); - builder.ensureCapacity(builder.length() + name.length() + 1 + hexString.length()); - builder.append(name) - .append(AT_SIGN) - .append(hexString); + public static short CONST_SHORT(final int v) { + if (v < Short.MIN_VALUE || v > Short.MAX_VALUE) { + throw new IllegalArgumentException("Supplied value must be a valid byte literal between -32768 and 32767: [" + v + "]"); + } + return (short) v; } - // ToString - //----------------------------------------------------------------------- /** - *

      Gets the {@code toString} of an {@code Object} returning - * an empty string ("") if {@code null} input.

      + *

      Returns a default value if the object passed is {@code null}.

      * *
      -     * ObjectUtils.toString(null)         = ""
      -     * ObjectUtils.toString("")           = ""
      -     * ObjectUtils.toString("bat")        = "bat"
      -     * ObjectUtils.toString(Boolean.TRUE) = "true"
      +     * ObjectUtils.defaultIfNull(null, null)      = null
      +     * ObjectUtils.defaultIfNull(null, "")        = ""
      +     * ObjectUtils.defaultIfNull(null, "zz")      = "zz"
      +     * ObjectUtils.defaultIfNull("abc", *)        = "abc"
      +     * ObjectUtils.defaultIfNull(Boolean.TRUE, *) = Boolean.TRUE
            * 
      * - * @see StringUtils#defaultString(String) - * @see String#valueOf(Object) - * @param obj the Object to {@code toString}, may be null - * @return the passed in Object's toString, or {@code ""} if {@code null} input - * @since 2.0 - * @deprecated this method has been replaced by {@code java.util.Objects.toString(Object)} in Java 7 and will be - * removed in future releases. Note however that said method will return "null" for null references, while this - * method returns an empty String. To preserve behavior use {@code java.util.Objects.toString(myObject, "")} + * @param the type of the object + * @param object the {@code Object} to test, may be {@code null} + * @param defaultValue the default value to return, may be {@code null} + * @return {@code object} if it is not {@code null}, defaultValue otherwise + * TODO Rename to getIfNull in 4.0 */ - @Deprecated - public static String toString(final Object obj) { - return obj == null ? StringUtils.EMPTY : obj.toString(); + public static T defaultIfNull(final T object, final T defaultValue) { + return object != null ? object : defaultValue; } + // Null-safe equals/hashCode + //----------------------------------------------------------------------- /** - *

      Gets the {@code toString} of an {@code Object} returning - * a specified text if {@code null} input.

      + *

      Compares two objects for equality, where either one or both + * objects may be {@code null}.

      * *
      -     * ObjectUtils.toString(null, null)           = null
      -     * ObjectUtils.toString(null, "null")         = "null"
      -     * ObjectUtils.toString("", "null")           = ""
      -     * ObjectUtils.toString("bat", "null")        = "bat"
      -     * ObjectUtils.toString(Boolean.TRUE, "null") = "true"
      +     * ObjectUtils.equals(null, null)                  = true
      +     * ObjectUtils.equals(null, "")                    = false
      +     * ObjectUtils.equals("", null)                    = false
      +     * ObjectUtils.equals("", "")                      = true
      +     * ObjectUtils.equals(Boolean.TRUE, null)          = false
      +     * ObjectUtils.equals(Boolean.TRUE, "true")        = false
      +     * ObjectUtils.equals(Boolean.TRUE, Boolean.TRUE)  = true
      +     * ObjectUtils.equals(Boolean.TRUE, Boolean.FALSE) = false
            * 
      * - * @see StringUtils#defaultString(String,String) - * @see String#valueOf(Object) - * @param obj the Object to {@code toString}, may be null - * @param nullStr the String to return if {@code null} input, may be null - * @return the passed in Object's toString, or {@code nullStr} if {@code null} input - * @since 2.0 - * @deprecated this method has been replaced by {@code java.util.Objects.toString(Object, String)} in Java 7 and - * will be removed in future releases. + * @param object1 the first object, may be {@code null} + * @param object2 the second object, may be {@code null} + * @return {@code true} if the values of both objects are the same + * @deprecated this method has been replaced by {@code java.util.Objects.equals(Object, Object)} in Java 7 and will + * be removed from future releases. */ @Deprecated - public static String toString(final Object obj, final String nullStr) { - return obj == null ? nullStr : obj.toString(); + public static boolean equals(final Object object1, final Object object2) { + if (object1 == object2) { + return true; + } + if (object1 == null || object2 == null) { + return false; + } + return object1.equals(object2); } - // Comparable - //----------------------------------------------------------------------- /** - *

      Null safe comparison of Comparables.

      + *

      Returns the first value in the array which is not {@code null}. + * If all the values are {@code null} or the array is {@code null} + * or empty then {@code null} is returned.

      * - * @param type of the values processed by this method - * @param values the set of comparable values, may be null - * @return - *
        - *
      • If any objects are non-null and unequal, the lesser object. - *
      • If all objects are non-null and equal, the first. - *
      • If any of the comparables are null, the lesser of the non-null objects. - *
      • If all the comparables are null, null is returned. - *
      + *
      +     * ObjectUtils.firstNonNull(null, null)      = null
      +     * ObjectUtils.firstNonNull(null, "")        = ""
      +     * ObjectUtils.firstNonNull(null, null, "")  = ""
      +     * ObjectUtils.firstNonNull(null, "zz")      = "zz"
      +     * ObjectUtils.firstNonNull("abc", *)        = "abc"
      +     * ObjectUtils.firstNonNull(null, "xyz", *)  = "xyz"
      +     * ObjectUtils.firstNonNull(Boolean.TRUE, *) = Boolean.TRUE
      +     * ObjectUtils.firstNonNull()                = null
      +     * 
      + * + * @param the component type of the array + * @param values the values to test, may be {@code null} or empty + * @return the first value from {@code values} which is not {@code null}, + * or {@code null} if there are no non-null values + * @since 3.0 */ @SafeVarargs - public static > T min(final T... values) { - T result = null; + public static T firstNonNull(final T... values) { if (values != null) { - for (final T value : values) { - if (compare(value, result, true) < 0) { - result = value; + for (final T val : values) { + if (val != null) { + return val; } } } - return result; + return null; } /** - *

      Null safe comparison of Comparables.

      + *

      Executes the given suppliers in order and returns the first return + * value where a value other than {@code null} is returned. + * Once a non-{@code null} value is obtained, all following suppliers are + * not executed anymore. + * If all the return values are {@code null} or no suppliers are provided + * then {@code null} is returned.

      * - * @param type of the values processed by this method - * @param values the set of comparable values, may be null - * @return - *
        - *
      • If any objects are non-null and unequal, the greater object. - *
      • If all objects are non-null and equal, the first. - *
      • If any of the comparables are null, the greater of the non-null objects. - *
      • If all the comparables are null, null is returned. - *
      + *
      +     * ObjectUtils.firstNonNullLazy(null, () -> null) = null
      +     * ObjectUtils.firstNonNullLazy(() -> null, () -> "") = ""
      +     * ObjectUtils.firstNonNullLazy(() -> "", () -> throw new IllegalStateException()) = ""
      +     * ObjectUtils.firstNonNullLazy(() -> null, () -> "zz) = "zz"
      +     * ObjectUtils.firstNonNullLazy() = null
      +     * 
      + * + * @param the type of the return values + * @param suppliers the suppliers returning the values to test. + * {@code null} values are ignored. + * Suppliers may return {@code null} or a value of type @{code T} + * @return the first return value from {@code suppliers} which is not {@code null}, + * or {@code null} if there are no non-null values + * @since 3.10 */ @SafeVarargs - public static > T max(final T... values) { - T result = null; - if (values != null) { - for (final T value : values) { - if (compare(value, result, false) > 0) { - result = value; + public static T getFirstNonNull(final Supplier... suppliers) { + if (suppliers != null) { + for (final Supplier supplier : suppliers) { + if (supplier != null) { + final T value = supplier.get(); + if (value != null) { + return value; + } } } } - return result; + return null; } /** - *

      Null safe comparison of Comparables. - * {@code null} is assumed to be less than a non-{@code null} value.

      + *

      + * Returns the given {@code object} is it is non-null, otherwise returns the Supplier's {@link Supplier#get()} + * value. + *

      * - * @param type of the values processed by this method - * @param c1 the first comparable, may be null - * @param c2 the second comparable, may be null - * @return a negative value if c1 < c2, zero if c1 = c2 - * and a positive value if c1 > c2 + *

      + * The caller responsible for thread-safety and exception handling of default value supplier. + *

      + * + *
      +     * ObjectUtils.getIfNull(null, () -> null)     = null
      +     * ObjectUtils.getIfNull(null, null)              = null
      +     * ObjectUtils.getIfNull(null, () -> "")       = ""
      +     * ObjectUtils.getIfNull(null, () -> "zz")     = "zz"
      +     * ObjectUtils.getIfNull("abc", *)                = "abc"
      +     * ObjectUtils.getIfNull(Boolean.TRUE, *)         = Boolean.TRUE
      +     * 
      + * + * @param the type of the object + * @param object the {@code Object} to test, may be {@code null} + * @param defaultSupplier the default value to return, may be {@code null} + * @return {@code object} if it is not {@code null}, {@code defaultValueSupplier.get()} otherwise + * @since 3.10 */ - public static > int compare(final T c1, final T c2) { - return compare(c1, c2, false); + public static T getIfNull(final T object, final Supplier defaultSupplier) { + return object != null ? object : defaultSupplier == null ? null : defaultSupplier.get(); } /** - *

      Null safe comparison of Comparables.

      + *

      Gets the hash code of an object returning zero when the + * object is {@code null}.

      * - * @param type of the values processed by this method - * @param c1 the first comparable, may be null - * @param c2 the second comparable, may be null - * @param nullGreater if true {@code null} is considered greater - * than a non-{@code null} value or if false {@code null} is - * considered less than a Non-{@code null} value - * @return a negative value if c1 < c2, zero if c1 = c2 - * and a positive value if c1 > c2 - * @see java.util.Comparator#compare(Object, Object) + *
      +     * ObjectUtils.hashCode(null)   = 0
      +     * ObjectUtils.hashCode(obj)    = obj.hashCode()
      +     * 
      + * + * @param obj the object to obtain the hash code of, may be {@code null} + * @return the hash code of the object, or zero if null + * @since 2.1 + * @deprecated this method has been replaced by {@code java.util.Objects.hashCode(Object)} in Java 7 and will be + * removed in future releases */ - public static > int compare(final T c1, final T c2, final boolean nullGreater) { - if (c1 == c2) { - return 0; - } else if (c1 == null) { - return nullGreater ? 1 : -1; - } else if (c2 == null) { - return nullGreater ? -1 : 1; - } - return c1.compareTo(c2); + @Deprecated + public static int hashCode(final Object obj) { + // hashCode(Object) retained for performance, as hash code is often critical + return obj == null ? 0 : obj.hashCode(); } /** - * Find the "best guess" middle value among comparables. If there is an even - * number of total values, the lower of the two middle values will be returned. - * @param type of values processed by this method - * @param items to compare - * @return T at middle position - * @throws NullPointerException if items is {@code null} - * @throws IllegalArgumentException if items is empty or contains {@code null} values - * @since 3.0.1 + *

      Gets the hash code for multiple objects.

      + * + *

      This allows a hash code to be rapidly calculated for a number of objects. + * The hash code for a single object is the not same as {@link #hashCode(Object)}. + * The hash code for multiple objects is the same as that calculated by an + * {@code ArrayList} containing the specified objects.

      + * + *
      +     * ObjectUtils.hashCodeMulti()                 = 1
      +     * ObjectUtils.hashCodeMulti((Object[]) null)  = 1
      +     * ObjectUtils.hashCodeMulti(a)                = 31 + a.hashCode()
      +     * ObjectUtils.hashCodeMulti(a,b)              = (31 + a.hashCode()) * 31 + b.hashCode()
      +     * ObjectUtils.hashCodeMulti(a,b,c)            = ((31 + a.hashCode()) * 31 + b.hashCode()) * 31 + c.hashCode()
      +     * 
      + * + * @param objects the objects to obtain the hash code of, may be {@code null} + * @return the hash code of the objects, or zero if null + * @since 3.0 + * @deprecated this method has been replaced by {@code java.util.Objects.hash(Object...)} in Java 7 and will be + * removed in future releases. */ - @SafeVarargs - public static > T median(final T... items) { - Validate.notEmpty(items); - Validate.noNullElements(items); - final TreeSet sort = new TreeSet<>(); - Collections.addAll(sort, items); - @SuppressWarnings("unchecked") //we know all items added were T instances - final T result = (T) sort.toArray()[(sort.size() - 1) / 2]; - return result; + @Deprecated + public static int hashCodeMulti(final Object... objects) { + int hash = 1; + if (objects != null) { + for (final Object object : objects) { + final int tmpHash = hashCode(object); + hash = hash * 31 + tmpHash; + } + } + return hash; } /** - * Find the "best guess" middle value among comparables. If there is an even - * number of total values, the lower of the two middle values will be returned. - * @param type of values processed by this method - * @param comparator to use for comparisons - * @param items to compare - * @return T at middle position - * @throws NullPointerException if items or comparator is {@code null} - * @throws IllegalArgumentException if items is empty or contains {@code null} values - * @since 3.0.1 + *

      Appends the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will throw a NullPointerException for either of the two parameters.

      + * + *
      +     * ObjectUtils.identityToString(appendable, "")            = appendable.append("java.lang.String@1e23"
      +     * ObjectUtils.identityToString(appendable, Boolean.TRUE)  = appendable.append("java.lang.Boolean@7fa"
      +     * ObjectUtils.identityToString(appendable, Boolean.TRUE)  = appendable.append("java.lang.Boolean@7fa")
      +     * 
      + * + * @param appendable the appendable to append to + * @param object the object to create a toString for + * @throws IOException if an I/O error occurs + * @since 3.2 */ - @SafeVarargs - public static T median(final Comparator comparator, final T... items) { - Validate.notEmpty(items, "null/empty items"); - Validate.noNullElements(items); - Validate.notNull(comparator, "null comparator"); - final TreeSet sort = new TreeSet<>(comparator); - Collections.addAll(sort, items); - @SuppressWarnings("unchecked") //we know all items added were T instances - final - T result = (T) sort.toArray()[(sort.size() - 1) / 2]; - return result; + public static void identityToString(final Appendable appendable, final Object object) throws IOException { + Validate.notNull(object, "Cannot get the toString of a null object"); + appendable.append(object.getClass().getName()) + .append(AT_SIGN) + .append(Integer.toHexString(System.identityHashCode(object))); } - // Mode + // Identity ToString //----------------------------------------------------------------------- /** - * Find the most frequently occurring item. + *

      Gets the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will return {@code null}.

      * - * @param type of values processed by this method - * @param items to check - * @return most populous T, {@code null} if non-unique or no items supplied - * @since 3.0.1 + *
      +     * ObjectUtils.identityToString(null)         = null
      +     * ObjectUtils.identityToString("")           = "java.lang.String@1e23"
      +     * ObjectUtils.identityToString(Boolean.TRUE) = "java.lang.Boolean@7fa"
      +     * 
      + * + * @param object the object to create a toString for, may be + * {@code null} + * @return the default toString text, or {@code null} if + * {@code null} passed in */ - @SafeVarargs - public static T mode(final T... items) { - if (ArrayUtils.isNotEmpty(items)) { - final HashMap occurrences = new HashMap<>(items.length); - for (final T t : items) { - final MutableInt count = occurrences.get(t); - if (count == null) { - occurrences.put(t, new MutableInt(1)); - } else { - count.increment(); - } - } - T result = null; - int max = 0; - for (final Map.Entry e : occurrences.entrySet()) { - final int cmp = e.getValue().intValue(); - if (cmp == max) { - result = null; - } else if (cmp > max) { - max = cmp; - result = e.getKey(); - } - } - return result; + public static String identityToString(final Object object) { + if (object == null) { + return null; } - return null; + final String name = object.getClass().getName(); + final String hexString = Integer.toHexString(System.identityHashCode(object)); + final StringBuilder builder = new StringBuilder(name.length() + 1 + hexString.length()); + // @formatter:off + builder.append(name) + .append(AT_SIGN) + .append(hexString); + // @formatter:off + return builder.toString(); } - // cloning - //----------------------------------------------------------------------- /** - *

      Clone an object.

      + *

      Appends the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will throw a NullPointerException for either of the two parameters.

      * - * @param the type of the object - * @param obj the object to clone, null returns null - * @return the clone if the object implements {@link Cloneable} otherwise {@code null} - * @throws CloneFailedException if the object is cloneable and the clone operation fails - * @since 3.0 - */ - public static T clone(final T obj) { - if (obj instanceof Cloneable) { - final Object result; - if (obj.getClass().isArray()) { - final Class componentType = obj.getClass().getComponentType(); - if (componentType.isPrimitive()) { - int length = Array.getLength(obj); - result = Array.newInstance(componentType, length); - while (length-- > 0) { - Array.set(result, length, Array.get(obj, length)); - } - } else { - result = ((Object[]) obj).clone(); - } - } else { - try { - final Method clone = obj.getClass().getMethod("clone"); - result = clone.invoke(obj); - } catch (final NoSuchMethodException e) { - throw new CloneFailedException("Cloneable type " - + obj.getClass().getName() - + " has no clone method", e); - } catch (final IllegalAccessException e) { - throw new CloneFailedException("Cannot clone Cloneable type " - + obj.getClass().getName(), e); - } catch (final InvocationTargetException e) { - throw new CloneFailedException("Exception cloning Cloneable type " - + obj.getClass().getName(), e.getCause()); - } - } - @SuppressWarnings("unchecked") // OK because input is of type T - final T checked = (T) result; - return checked; - } - - return null; + *
      +     * ObjectUtils.identityToString(builder, "")            = builder.append("java.lang.String@1e23"
      +     * ObjectUtils.identityToString(builder, Boolean.TRUE)  = builder.append("java.lang.Boolean@7fa"
      +     * ObjectUtils.identityToString(builder, Boolean.TRUE)  = builder.append("java.lang.Boolean@7fa")
      +     * 
      + * + * @param builder the builder to append to + * @param object the object to create a toString for + * @since 3.2 + * @deprecated as of 3.6, because StrBuilder was moved to commons-text, + * use one of the other {@code identityToString} methods instead + */ + @Deprecated + public static void identityToString(final StrBuilder builder, final Object object) { + Validate.notNull(object, "Cannot get the toString of a null object"); + final String name = object.getClass().getName(); + final String hexString = Integer.toHexString(System.identityHashCode(object)); + builder.ensureCapacity(builder.length() + name.length() + 1 + hexString.length()); + builder.append(name) + .append(AT_SIGN) + .append(hexString); } /** - *

      Clone an object if possible.

      + *

      Appends the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will throw a NullPointerException for either of the two parameters.

      * - *

      This method is similar to {@link #clone(Object)}, but will return the provided - * instance as the return value instead of {@code null} if the instance - * is not cloneable. This is more convenient if the caller uses different - * implementations (e.g. of a service) and some of the implementations do not allow concurrent - * processing or have state. In such cases the implementation can simply provide a proper - * clone implementation and the caller's code does not have to change.

      + *
      +     * ObjectUtils.identityToString(buf, "")            = buf.append("java.lang.String@1e23"
      +     * ObjectUtils.identityToString(buf, Boolean.TRUE)  = buf.append("java.lang.Boolean@7fa"
      +     * ObjectUtils.identityToString(buf, Boolean.TRUE)  = buf.append("java.lang.Boolean@7fa")
      +     * 
      * - * @param the type of the object - * @param obj the object to clone, null returns null - * @return the clone if the object implements {@link Cloneable} otherwise the object itself - * @throws CloneFailedException if the object is cloneable and the clone operation fails - * @since 3.0 + * @param buffer the buffer to append to + * @param object the object to create a toString for + * @since 2.4 */ - public static T cloneIfPossible(final T obj) { - final T clone = clone(obj); - return clone == null ? obj : clone; + public static void identityToString(final StringBuffer buffer, final Object object) { + Validate.notNull(object, "Cannot get the toString of a null object"); + final String name = object.getClass().getName(); + final String hexString = Integer.toHexString(System.identityHashCode(object)); + buffer.ensureCapacity(buffer.length() + name.length() + 1 + hexString.length()); + buffer.append(name) + .append(AT_SIGN) + .append(hexString); } - // Null - //----------------------------------------------------------------------- /** - *

      Class used as a null placeholder where {@code null} - * has another meaning.

      + *

      Appends the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will throw a NullPointerException for either of the two parameters.

      * - *

      For example, in a {@code HashMap} the - * {@link java.util.HashMap#get(java.lang.Object)} method returns - * {@code null} if the {@code Map} contains {@code null} or if there is - * no matching key. The {@code Null} placeholder can be used to distinguish - * between these two cases.

      + *
      +     * ObjectUtils.identityToString(builder, "")            = builder.append("java.lang.String@1e23"
      +     * ObjectUtils.identityToString(builder, Boolean.TRUE)  = builder.append("java.lang.Boolean@7fa"
      +     * ObjectUtils.identityToString(builder, Boolean.TRUE)  = builder.append("java.lang.Boolean@7fa")
      +     * 
      * - *

      Another example is {@code Hashtable}, where {@code null} - * cannot be stored.

      + * @param builder the builder to append to + * @param object the object to create a toString for + * @since 3.2 */ - public static class Null implements Serializable { - /** - * Required for serialization support. Declare serialization compatibility with Commons Lang 1.0 - * - * @see java.io.Serializable - */ - private static final long serialVersionUID = 7092611880189329093L; - - /** - * Restricted constructor - singleton. - */ - Null() { - super(); - } - - /** - *

      Ensure singleton.

      - * - * @return the singleton value - */ - private Object readResolve() { - return NULL; - } + public static void identityToString(final StringBuilder builder, final Object object) { + Validate.notNull(object, "Cannot get the toString of a null object"); + final String name = object.getClass().getName(); + final String hexString = Integer.toHexString(System.identityHashCode(object)); + builder.ensureCapacity(builder.length() + name.length() + 1 + hexString.length()); + builder.append(name) + .append(AT_SIGN) + .append(hexString); } @@ -949,249 +893,305 @@ their constant using one of the CONST() utility methods, instead: */ + // Empty checks + //----------------------------------------------------------------------- /** - * This method returns the provided value unchanged. - * This can prevent javac from inlining a constant - * field, e.g., + *

      Checks if an Object is empty or null.

      + * + * The following types are supported: + *
        + *
      • {@link CharSequence}: Considered empty if its length is zero.
      • + *
      • {@code Array}: Considered empty if its length is zero.
      • + *
      • {@link Collection}: Considered empty if it has zero elements.
      • + *
      • {@link Map}: Considered empty if it has zero key-value mappings.
      • + *
      * *
      -     *     public final static boolean MAGIC_FLAG = ObjectUtils.CONST(true);
      +     * ObjectUtils.isEmpty(null)             = true
      +     * ObjectUtils.isEmpty("")               = true
      +     * ObjectUtils.isEmpty("ab")             = false
      +     * ObjectUtils.isEmpty(new int[]{})      = true
      +     * ObjectUtils.isEmpty(new int[]{1,2,3}) = false
      +     * ObjectUtils.isEmpty(1234)             = false
            * 
      * - * This way any jars that refer to this field do not - * have to recompile themselves if the field's value - * changes at some future date. - * - * @param v the boolean value to return - * @return the boolean v, unchanged - * @since 3.2 + * @param object the {@code Object} to test, may be {@code null} + * @return {@code true} if the object has a supported type and is empty or null, + * {@code false} otherwise + * @since 3.9 */ - public static boolean CONST(final boolean v) { - return v; + public static boolean isEmpty(final Object object) { + if (object == null) { + return true; + } + if (object instanceof CharSequence) { + return ((CharSequence) object).length() == 0; + } + if (object.getClass().isArray()) { + return Array.getLength(object) == 0; + } + if (object instanceof Collection) { + return ((Collection) object).isEmpty(); + } + if (object instanceof Map) { + return ((Map) object).isEmpty(); + } + return false; } /** - * This method returns the provided value unchanged. - * This can prevent javac from inlining a constant - * field, e.g., + *

      Checks if an Object is not empty and not null.

      + * + * The following types are supported: + *
        + *
      • {@link CharSequence}: Considered empty if its length is zero.
      • + *
      • {@code Array}: Considered empty if its length is zero.
      • + *
      • {@link Collection}: Considered empty if it has zero elements.
      • + *
      • {@link Map}: Considered empty if it has zero key-value mappings.
      • + *
      * *
      -     *     public final static byte MAGIC_BYTE = ObjectUtils.CONST((byte) 127);
      +     * ObjectUtils.isNotEmpty(null)             = false
      +     * ObjectUtils.isNotEmpty("")               = false
      +     * ObjectUtils.isNotEmpty("ab")             = true
      +     * ObjectUtils.isNotEmpty(new int[]{})      = false
      +     * ObjectUtils.isNotEmpty(new int[]{1,2,3}) = true
      +     * ObjectUtils.isNotEmpty(1234)             = true
            * 
      * - * This way any jars that refer to this field do not - * have to recompile themselves if the field's value - * changes at some future date. - * - * @param v the byte value to return - * @return the byte v, unchanged - * @since 3.2 + * @param object the {@code Object} to test, may be {@code null} + * @return {@code true} if the object has an unsupported type or is not empty + * and not null, {@code false} otherwise + * @since 3.9 */ - public static byte CONST(final byte v) { - return v; + public static boolean isNotEmpty(final Object object) { + return !isEmpty(object); } /** - * This method returns the provided value unchanged. - * This can prevent javac from inlining a constant - * field, e.g., - * - *
      -     *     public final static byte MAGIC_BYTE = ObjectUtils.CONST_BYTE(127);
      -     * 
      - * - * This way any jars that refer to this field do not - * have to recompile themselves if the field's value - * changes at some future date. + *

      Null safe comparison of Comparables.

      * - * @param v the byte literal (as an int) value to return - * @throws IllegalArgumentException if the value passed to v - * is larger than a byte, that is, smaller than -128 or - * larger than 127. - * @return the byte v, unchanged - * @since 3.2 + * @param type of the values processed by this method + * @param values the set of comparable values, may be null + * @return + *
        + *
      • If any objects are non-null and unequal, the greater object. + *
      • If all objects are non-null and equal, the first. + *
      • If any of the comparables are null, the greater of the non-null objects. + *
      • If all the comparables are null, null is returned. + *
      */ - public static byte CONST_BYTE(final int v) { - if (v < Byte.MIN_VALUE || v > Byte.MAX_VALUE) { - throw new IllegalArgumentException("Supplied value must be a valid byte literal between -128 and 127: [" + v + "]"); + @SafeVarargs + public static > T max(final T... values) { + T result = null; + if (values != null) { + for (final T value : values) { + if (compare(value, result, false) > 0) { + result = value; + } + } } - return (byte) v; + return result; } /** - * This method returns the provided value unchanged. - * This can prevent javac from inlining a constant - * field, e.g., - * - *
      -     *     public final static char MAGIC_CHAR = ObjectUtils.CONST('a');
      -     * 
      - * - * This way any jars that refer to this field do not - * have to recompile themselves if the field's value - * changes at some future date. - * - * @param v the char value to return - * @return the char v, unchanged - * @since 3.2 + * Find the "best guess" middle value among comparables. If there is an even + * number of total values, the lower of the two middle values will be returned. + * @param type of values processed by this method + * @param comparator to use for comparisons + * @param items to compare + * @return T at middle position + * @throws NullPointerException if items or comparator is {@code null} + * @throws IllegalArgumentException if items is empty or contains {@code null} values + * @since 3.0.1 */ - public static char CONST(final char v) { - return v; + @SafeVarargs + public static T median(final Comparator comparator, final T... items) { + Validate.notEmpty(items, "null/empty items"); + Validate.noNullElements(items); + Validate.notNull(comparator, "null comparator"); + final TreeSet sort = new TreeSet<>(comparator); + Collections.addAll(sort, items); + @SuppressWarnings("unchecked") //we know all items added were T instances + final + T result = (T) sort.toArray()[(sort.size() - 1) / 2]; + return result; } /** - * This method returns the provided value unchanged. - * This can prevent javac from inlining a constant - * field, e.g., - * - *
      -     *     public final static short MAGIC_SHORT = ObjectUtils.CONST((short) 123);
      -     * 
      - * - * This way any jars that refer to this field do not - * have to recompile themselves if the field's value - * changes at some future date. - * - * @param v the short value to return - * @return the short v, unchanged - * @since 3.2 + * Find the "best guess" middle value among comparables. If there is an even + * number of total values, the lower of the two middle values will be returned. + * @param type of values processed by this method + * @param items to compare + * @return T at middle position + * @throws NullPointerException if items is {@code null} + * @throws IllegalArgumentException if items is empty or contains {@code null} values + * @since 3.0.1 */ - public static short CONST(final short v) { - return v; + @SafeVarargs + public static > T median(final T... items) { + Validate.notEmpty(items); + Validate.noNullElements(items); + final TreeSet sort = new TreeSet<>(); + Collections.addAll(sort, items); + @SuppressWarnings("unchecked") //we know all items added were T instances + final T result = (T) sort.toArray()[(sort.size() - 1) / 2]; + return result; } + // Comparable + //----------------------------------------------------------------------- /** - * This method returns the provided value unchanged. - * This can prevent javac from inlining a constant - * field, e.g., - * - *
      -     *     public final static short MAGIC_SHORT = ObjectUtils.CONST_SHORT(127);
      -     * 
      - * - * This way any jars that refer to this field do not - * have to recompile themselves if the field's value - * changes at some future date. + *

      Null safe comparison of Comparables.

      * - * @param v the short literal (as an int) value to return - * @throws IllegalArgumentException if the value passed to v - * is larger than a short, that is, smaller than -32768 or - * larger than 32767. - * @return the byte v, unchanged - * @since 3.2 + * @param type of the values processed by this method + * @param values the set of comparable values, may be null + * @return + *
        + *
      • If any objects are non-null and unequal, the lesser object. + *
      • If all objects are non-null and equal, the first. + *
      • If any of the comparables are null, the lesser of the non-null objects. + *
      • If all the comparables are null, null is returned. + *
      */ - public static short CONST_SHORT(final int v) { - if (v < Short.MIN_VALUE || v > Short.MAX_VALUE) { - throw new IllegalArgumentException("Supplied value must be a valid byte literal between -32768 and 32767: [" + v + "]"); + @SafeVarargs + public static > T min(final T... values) { + T result = null; + if (values != null) { + for (final T value : values) { + if (compare(value, result, true) < 0) { + result = value; + } + } } - return (short) v; + return result; } + // Mode + //----------------------------------------------------------------------- /** - * This method returns the provided value unchanged. - * This can prevent javac from inlining a constant - * field, e.g., - * - *
      -     *     public final static int MAGIC_INT = ObjectUtils.CONST(123);
      -     * 
      - * - * This way any jars that refer to this field do not - * have to recompile themselves if the field's value - * changes at some future date. + * Find the most frequently occurring item. * - * @param v the int value to return - * @return the int v, unchanged - * @since 3.2 + * @param type of values processed by this method + * @param items to check + * @return most populous T, {@code null} if non-unique or no items supplied + * @since 3.0.1 */ - public static int CONST(final int v) { - return v; + @SafeVarargs + public static T mode(final T... items) { + if (ArrayUtils.isNotEmpty(items)) { + final HashMap occurrences = new HashMap<>(items.length); + for (final T t : items) { + final MutableInt count = occurrences.get(t); + if (count == null) { + occurrences.put(t, new MutableInt(1)); + } else { + count.increment(); + } + } + T result = null; + int max = 0; + for (final Map.Entry e : occurrences.entrySet()) { + final int cmp = e.getValue().intValue(); + if (cmp == max) { + result = null; + } else if (cmp > max) { + max = cmp; + result = e.getKey(); + } + } + return result; + } + return null; } /** - * This method returns the provided value unchanged. - * This can prevent javac from inlining a constant - * field, e.g., + *

      Compares two objects for inequality, where either one or both + * objects may be {@code null}.

      * *
      -     *     public final static long MAGIC_LONG = ObjectUtils.CONST(123L);
      +     * ObjectUtils.notEqual(null, null)                  = false
      +     * ObjectUtils.notEqual(null, "")                    = true
      +     * ObjectUtils.notEqual("", null)                    = true
      +     * ObjectUtils.notEqual("", "")                      = false
      +     * ObjectUtils.notEqual(Boolean.TRUE, null)          = true
      +     * ObjectUtils.notEqual(Boolean.TRUE, "true")        = true
      +     * ObjectUtils.notEqual(Boolean.TRUE, Boolean.TRUE)  = false
      +     * ObjectUtils.notEqual(Boolean.TRUE, Boolean.FALSE) = true
            * 
      * - * This way any jars that refer to this field do not - * have to recompile themselves if the field's value - * changes at some future date. - * - * @param v the long value to return - * @return the long v, unchanged - * @since 3.2 + * @param object1 the first object, may be {@code null} + * @param object2 the second object, may be {@code null} + * @return {@code false} if the values of both objects are the same */ - public static long CONST(final long v) { - return v; + public static boolean notEqual(final Object object1, final Object object2) { + return !equals(object1, object2); } + // ToString + //----------------------------------------------------------------------- /** - * This method returns the provided value unchanged. - * This can prevent javac from inlining a constant - * field, e.g., + *

      Gets the {@code toString} of an {@code Object} returning + * an empty string ("") if {@code null} input.

      * *
      -     *     public final static float MAGIC_FLOAT = ObjectUtils.CONST(1.0f);
      +     * ObjectUtils.toString(null)         = ""
      +     * ObjectUtils.toString("")           = ""
      +     * ObjectUtils.toString("bat")        = "bat"
      +     * ObjectUtils.toString(Boolean.TRUE) = "true"
            * 
      * - * This way any jars that refer to this field do not - * have to recompile themselves if the field's value - * changes at some future date. - * - * @param v the float value to return - * @return the float v, unchanged - * @since 3.2 + * @see StringUtils#defaultString(String) + * @see String#valueOf(Object) + * @param obj the Object to {@code toString}, may be null + * @return the passed in Object's toString, or {@code ""} if {@code null} input + * @since 2.0 + * @deprecated this method has been replaced by {@code java.util.Objects.toString(Object)} in Java 7 and will be + * removed in future releases. Note however that said method will return "null" for null references, while this + * method returns an empty String. To preserve behavior use {@code java.util.Objects.toString(myObject, "")} */ - public static float CONST(final float v) { - return v; + @Deprecated + public static String toString(final Object obj) { + return obj == null ? StringUtils.EMPTY : obj.toString(); } /** - * This method returns the provided value unchanged. - * This can prevent javac from inlining a constant - * field, e.g., + *

      Gets the {@code toString} of an {@code Object} returning + * a specified text if {@code null} input.

      * *
      -     *     public final static double MAGIC_DOUBLE = ObjectUtils.CONST(1.0);
      +     * ObjectUtils.toString(null, null)           = null
      +     * ObjectUtils.toString(null, "null")         = "null"
      +     * ObjectUtils.toString("", "null")           = ""
      +     * ObjectUtils.toString("bat", "null")        = "bat"
      +     * ObjectUtils.toString(Boolean.TRUE, "null") = "true"
            * 
      * - * This way any jars that refer to this field do not - * have to recompile themselves if the field's value - * changes at some future date. - * - * @param v the double value to return - * @return the double v, unchanged - * @since 3.2 + * @see StringUtils#defaultString(String,String) + * @see String#valueOf(Object) + * @param obj the Object to {@code toString}, may be null + * @param nullStr the String to return if {@code null} input, may be null + * @return the passed in Object's toString, or {@code nullStr} if {@code null} input + * @since 2.0 + * @deprecated this method has been replaced by {@code java.util.Objects.toString(Object, String)} in Java 7 and + * will be removed in future releases. */ - public static double CONST(final double v) { - return v; + @Deprecated + public static String toString(final Object obj, final String nullStr) { + return obj == null ? nullStr : obj.toString(); } /** - * This method returns the provided value unchanged. - * This can prevent javac from inlining a constant - * field, e.g., - * - *
      -     *     public final static String MAGIC_STRING = ObjectUtils.CONST("abc");
      -     * 
      - * - * This way any jars that refer to this field do not - * have to recompile themselves if the field's value - * changes at some future date. + *

      {@code ObjectUtils} instances should NOT be constructed in + * standard programming. Instead, the static methods on the class should + * be used, such as {@code ObjectUtils.defaultIfNull("a","b");}.

      * - * @param the Object type - * @param v the genericized Object value to return (typically a String). - * @return the genericized Object v, unchanged (typically a String). - * @since 3.2 + *

      This constructor is public to permit tools that require a JavaBean + * instance to operate.

      */ - public static T CONST(final T v) { - return v; + public ObjectUtils() { + super(); } } From c26c72f8a8ee9996bff2bf139eb42fc2c56e62d8 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Tue, 23 Jun 2020 15:15:38 -0400 Subject: [PATCH 0189/3230] Add ObjectUtils.toString(Object, Supplier). --- src/changes/changes.xml | 3 ++- .../org/apache/commons/lang3/ObjectUtils.java | 26 ++++++++++++++++++- .../apache/commons/lang3/ObjectUtilsTest.java | 9 +++++++ 3 files changed, 36 insertions(+), 2 deletions(-) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 03989d56443..4694dcddb0b 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -79,7 +79,8 @@ The type attribute can be add,update,fix,remove. Use Java 8 lambdas and Map operations. Change removeLastFieldSeparator to use endsWith #550. Change a Pattern to a static final field, for not letting it compile each time the function invoked. #542. - Added ImmutablePair factory methods left() and right(). + Add ImmutablePair factory methods left() and right(). + Add ObjectUtils.toString(Object, Supplier<String>).
      diff --git a/src/main/java/org/apache/commons/lang3/ObjectUtils.java b/src/main/java/org/apache/commons/lang3/ObjectUtils.java index f1e5fa2a9a1..95e88622891 100644 --- a/src/main/java/org/apache/commons/lang3/ObjectUtils.java +++ b/src/main/java/org/apache/commons/lang3/ObjectUtils.java @@ -789,7 +789,7 @@ public static String identityToString(final Object object) { builder.append(name) .append(AT_SIGN) .append(hexString); - // @formatter:off + // @formatter:on return builder.toString(); } @@ -1182,6 +1182,30 @@ public static String toString(final Object obj, final String nullStr) { return obj == null ? nullStr : obj.toString(); } + /** + *

      Gets the {@code toString} of an {@code Object} returning + * a specified text if {@code null} input.

      + * + *
      +     * ObjectUtils.toString(obj, () -> expensive())
      +     * 
      + *
      +     * ObjectUtils.toString(null, () -> expensive())         = result of expensive()
      +     * ObjectUtils.toString(null, () -> expensive())         = result of expensive()
      +     * ObjectUtils.toString("", () -> expensive())           = ""
      +     * ObjectUtils.toString("bat", () -> expensive())        = "bat"
      +     * ObjectUtils.toString(Boolean.TRUE, () -> expensive()) = "true"
      +     * 
      + * + * @param obj the Object to {@code toString}, may be null + * @param supplier the Supplier of String used on {@code null} input, may be null + * @return the passed in Object's toString, or {@code nullStr} if {@code null} input + * @since 3.11 + */ + public static String toString(final Object obj, final Supplier supplier) { + return obj == null ? supplier == null ? null : supplier.get() : obj.toString(); + } + /** *

      {@code ObjectUtils} instances should NOT be constructed in * standard programming. Instead, the static methods on the class should diff --git a/src/test/java/org/apache/commons/lang3/ObjectUtilsTest.java b/src/test/java/org/apache/commons/lang3/ObjectUtilsTest.java index aab3a4e77e7..b1da3b69c9b 100644 --- a/src/test/java/org/apache/commons/lang3/ObjectUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/ObjectUtilsTest.java @@ -361,6 +361,15 @@ public void testToString_ObjectString() { assertEquals(Boolean.TRUE.toString(), ObjectUtils.toString(Boolean.TRUE, BAR) ); } + @Test + public void testToString_SupplierString() { + assertEquals(null, ObjectUtils.toString(null, (Supplier) null)); + assertEquals(null, ObjectUtils.toString(null, () -> null)); + // Pretend computing BAR is expensive. + assertEquals(BAR, ObjectUtils.toString(null, () -> BAR)); + assertEquals(Boolean.TRUE.toString(), ObjectUtils.toString(Boolean.TRUE, () -> BAR)); + } + @SuppressWarnings("cast") // 1 OK, because we are checking for code change @Test public void testNull() { From a14b28923e3a6d76732de072a774c6eed1f9ce61 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Wed, 24 Jun 2020 08:42:16 -0400 Subject: [PATCH 0190/3230] Clean ups. - Fix Javadoc - Simplify error message - Rmove on layer of API call. --- .../lang3/exception/ExceptionUtils.java | 28 ++++++++++--------- 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/exception/ExceptionUtils.java b/src/main/java/org/apache/commons/lang3/exception/ExceptionUtils.java index 5b48b0e43b1..8c387a9c146 100644 --- a/src/main/java/org/apache/commons/lang3/exception/ExceptionUtils.java +++ b/src/main/java/org/apache/commons/lang3/exception/ExceptionUtils.java @@ -24,12 +24,12 @@ import java.lang.reflect.UndeclaredThrowableException; import java.util.ArrayList; import java.util.List; +import java.util.Objects; import java.util.StringTokenizer; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.ClassUtils; import org.apache.commons.lang3.StringUtils; -import org.apache.commons.lang3.Validate; /** *

      Provides utilities for manipulating and examining @@ -624,20 +624,21 @@ public static void printRootCauseStackTrace(final Throwable throwable) { * that don't have nested causes.

      * * @param throwable the throwable to output, may be null - * @param stream the stream to output to, may not be null - * @throws IllegalArgumentException if the stream is {@code null} + * @param printStream the stream to output to, may not be null + * @throws NullPointerException if the printStream is {@code null} * @since 2.0 */ - public static void printRootCauseStackTrace(final Throwable throwable, final PrintStream stream) { + @SuppressWarnings("resource") + public static void printRootCauseStackTrace(final Throwable throwable, final PrintStream printStream) { if (throwable == null) { return; } - Validate.notNull(stream, "The PrintStream must not be null"); + Objects.requireNonNull(printStream, "printStream"); final String[] trace = getRootCauseStackTrace(throwable); for (final String element : trace) { - stream.println(element); + printStream.println(element); } - stream.flush(); + printStream.flush(); } /** @@ -655,20 +656,21 @@ public static void printRootCauseStackTrace(final Throwable throwable, final Pri * that don't have nested causes.

      * * @param throwable the throwable to output, may be null - * @param writer the writer to output to, may not be null - * @throws IllegalArgumentException if the writer is {@code null} + * @param printWriter the writer to output to, may not be null + * @throws NullPointerException if the printWriter is {@code null} * @since 2.0 */ - public static void printRootCauseStackTrace(final Throwable throwable, final PrintWriter writer) { + @SuppressWarnings("resource") + public static void printRootCauseStackTrace(final Throwable throwable, final PrintWriter printWriter) { if (throwable == null) { return; } - Validate.notNull(writer, "The PrintWriter must not be null"); + Objects.requireNonNull(printWriter, "printWriter"); final String[] trace = getRootCauseStackTrace(throwable); for (final String element : trace) { - writer.println(element); + printWriter.println(element); } - writer.flush(); + printWriter.flush(); } /** From dc54284ee75435773dc37022d3759c582743c189 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Wed, 24 Jun 2020 08:44:16 -0400 Subject: [PATCH 0191/3230] Javadoc. --- src/main/java/org/apache/commons/lang3/text/StrLookup.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/apache/commons/lang3/text/StrLookup.java b/src/main/java/org/apache/commons/lang3/text/StrLookup.java index f10aa73c161..7558c0b4fc1 100644 --- a/src/main/java/org/apache/commons/lang3/text/StrLookup.java +++ b/src/main/java/org/apache/commons/lang3/text/StrLookup.java @@ -29,8 +29,9 @@ * If these do not suffice, you can subclass and implement your own matcher. *

      * For example, it would be possible to implement a lookup that used the - * key as a primary key, and looked up the value on demand from the database + * key as a primary key, and looked up the value on demand from the database. * + * @param Unused. * @since 2.2 * @deprecated as of 3.6, use commons-text * From a7be33e9c6603cb15fb873ab721fbca1ef300600 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20Mu=C3=B1oz?= Date: Wed, 24 Jun 2020 05:46:21 -0700 Subject: [PATCH 0192/3230] Fixed Javadocs for setTestRecursive() (#556) --- .../org/apache/commons/lang3/builder/EqualsBuilder.java | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/builder/EqualsBuilder.java b/src/main/java/org/apache/commons/lang3/builder/EqualsBuilder.java index 6bd1058427c..50d811862d4 100644 --- a/src/main/java/org/apache/commons/lang3/builder/EqualsBuilder.java +++ b/src/main/java/org/apache/commons/lang3/builder/EqualsBuilder.java @@ -245,9 +245,12 @@ public EqualsBuilder setTestTransients(final boolean testTransients) { } /** - * Set whether to include transient fields when reflectively comparing objects. - * @param testRecursive whether to do a recursive test + * Set whether to test fields recursively, instead of using their equals method, when reflectively comparing objects. + * String objects, which cache a hash value, are automatically excluded from recursive testing. + * You may specify other exceptions by calling {@link #setBypassReflectionClasses(List)}. + * @param testRecursive whether to do a recursive test * @return EqualsBuilder - used to chain calls. + * @see #setBypassReflectionClasses(List) * @since 3.6 */ public EqualsBuilder setTestRecursive(final boolean testRecursive) { @@ -265,6 +268,7 @@ public EqualsBuilder setTestRecursive(final boolean testRecursive) { * your own set of classes here, remember to include {@code String} class, too.

      * @param bypassReflectionClasses classes to bypass reflection test * @return EqualsBuilder - used to chain calls. + * @see #setTestRecursive(boolean) * @since 3.8 */ public EqualsBuilder setBypassReflectionClasses(final List> bypassReflectionClasses) { From f070987f5d81f07662bd3430c59728d240ff18f8 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Wed, 24 Jun 2020 08:49:58 -0400 Subject: [PATCH 0193/3230] [LANG-1567] Fix Javadocs for EqualsBuilder#setTestRecursive() #556. --- src/changes/changes.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 4694dcddb0b..88936832bdd 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -81,6 +81,7 @@ The type attribute can be add,update,fix,remove. Change a Pattern to a static final field, for not letting it compile each time the function invoked. #542. Add ImmutablePair factory methods left() and right(). Add ObjectUtils.toString(Object, Supplier<String>). + Fixed Javadocs for setTestRecursive() #556. From 1dddec8ba867bc31233ba194f0753ea35818cbfd Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Wed, 24 Jun 2020 09:26:11 -0400 Subject: [PATCH 0194/3230] [LANG-1542] ToStringBuilder.reflectionToString - Wrong JSON format when object has a List/Array of Enum. --- src/changes/changes.xml | 1 + .../commons/lang3/builder/ToStringStyle.java | 51 +++--- .../lang3/builder/JsonToStringStyleTest.java | 151 +++++++++++++++++- 3 files changed, 179 insertions(+), 24 deletions(-) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 88936832bdd..7152b35fbdc 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -82,6 +82,7 @@ The type attribute can be add,update,fix,remove. Add ImmutablePair factory methods left() and right(). Add ObjectUtils.toString(Object, Supplier<String>). Fixed Javadocs for setTestRecursive() #556. + ToStringBuilder.reflectionToString - Wrong JSON format when object has a List of Enum. diff --git a/src/main/java/org/apache/commons/lang3/builder/ToStringStyle.java b/src/main/java/org/apache/commons/lang3/builder/ToStringStyle.java index 9b115739bcf..4856c32c37b 100644 --- a/src/main/java/org/apache/commons/lang3/builder/ToStringStyle.java +++ b/src/main/java/org/apache/commons/lang3/builder/ToStringStyle.java @@ -624,6 +624,16 @@ protected void appendDetail(final StringBuffer buffer, final String fieldName, f * {@code toString}, not {@code null} */ protected void appendDetail(final StringBuffer buffer, final String fieldName, final Collection coll) { + if (coll != null && !coll.isEmpty()) { + buffer.append(arrayStart); + int i = 0; + for (Object item : coll) { + appendDetail(buffer, fieldName, i++, item); + } + buffer.append(arrayEnd); + return; + } + buffer.append(coll); } @@ -919,19 +929,32 @@ protected void appendDetail(final StringBuffer buffer, final String fieldName, f buffer.append(arrayStart); for (int i = 0; i < array.length; i++) { final Object item = array[i]; - if (i > 0) { - buffer.append(arraySeparator); - } - if (item == null) { - appendNullText(buffer, fieldName); - - } else { - appendInternal(buffer, fieldName, item, arrayContentDetail); - } + appendDetail(buffer, fieldName, i, item); } buffer.append(arrayEnd); } + /** + *

      Append to the {@code toString} the detail of an + * {@code Object} array item.

      + * + * @param buffer the {@code StringBuffer} to populate + * @param fieldName the field name, typically not used as already appended + * @param i the array item index to add + * @param item the array item to add + * @since 3.11 + */ + protected void appendDetail(final StringBuffer buffer, final String fieldName, int i, final Object item) { + if (i > 0) { + buffer.append(arraySeparator); + } + if (item == null) { + appendNullText(buffer, fieldName); + } else { + appendInternal(buffer, fieldName, item, arrayContentDetail); + } + } + /** *

      Append to the {@code toString} the detail of an array type.

      * @@ -946,15 +969,7 @@ protected void reflectionAppendArrayDetail(final StringBuffer buffer, final Stri final int length = Array.getLength(array); for (int i = 0; i < length; i++) { final Object item = Array.get(array, i); - if (i > 0) { - buffer.append(arraySeparator); - } - if (item == null) { - appendNullText(buffer, fieldName); - - } else { - appendInternal(buffer, fieldName, item, arrayContentDetail); - } + appendDetail(buffer, fieldName, i, item); } buffer.append(arrayEnd); } diff --git a/src/test/java/org/apache/commons/lang3/builder/JsonToStringStyleTest.java b/src/test/java/org/apache/commons/lang3/builder/JsonToStringStyleTest.java index b0ad25462ef..ed7bf34188f 100644 --- a/src/test/java/org/apache/commons/lang3/builder/JsonToStringStyleTest.java +++ b/src/test/java/org/apache/commons/lang3/builder/JsonToStringStyleTest.java @@ -16,17 +16,20 @@ */ package org.apache.commons.lang3.builder; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; +import org.apache.commons.lang3.builder.ToStringStyleTest.Person; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; import java.util.Date; import java.util.HashMap; +import java.util.List; -import org.apache.commons.lang3.builder.ToStringStyleTest.Person; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; /** * Unit tests {@link org.apache.commons.lang3.builder.JsonToStringStyleTest}. @@ -181,6 +184,73 @@ public void testObject() { .toString()); } + @Test + public void testList() { + Student student = new Student(); + ArrayList objects = new ArrayList<>(); + + objects.add(Hobby.BOOK); + objects.add(Hobby.SPORT); + objects.add(Hobby.MUSIC); + + student.setHobbies(objects); + + assertEquals(student.toString(), "{\"hobbies\":[\"BOOK\",\"SPORT\",\"MUSIC\"]}"); + student.setHobbies(new ArrayList<>()); + assertEquals(student.toString(), "{\"hobbies\":[]}"); + student.setHobbies(null); + assertEquals(student.toString(), "{\"hobbies\":null}"); + } + + @Test + public void testArrayEnum() { + Teacher teacher = new Teacher(); + Hobby[] hobbies = new Hobby[3]; + hobbies[0] = Hobby.BOOK; + hobbies[1] = Hobby.SPORT; + hobbies[2] = Hobby.MUSIC; + + teacher.setHobbies(hobbies); + + assertEquals(teacher.toString(), "{\"hobbies\":[\"BOOK\",\"SPORT\",\"MUSIC\"]}"); + teacher.setHobbies(new Hobby[0]); + assertEquals(teacher.toString(), "{\"hobbies\":[]}"); + teacher.setHobbies(null); + assertEquals(teacher.toString(), "{\"hobbies\":null}"); + } + + @Test + public void testCombineListAndEnum() { + Teacher teacher = new Teacher(); + + Hobby[] teacherHobbies = new Hobby[3]; + teacherHobbies[0] = Hobby.BOOK; + teacherHobbies[1] = Hobby.SPORT; + teacherHobbies[2] = Hobby.MUSIC; + + teacher.setHobbies(teacherHobbies); + + Student john = new Student(); + john.setHobbies(Arrays.asList(Hobby.BOOK, Hobby.MUSIC)); + + Student alice = new Student(); + alice.setHobbies(new ArrayList<>()); + + Student bob = new Student(); + bob.setHobbies(Collections.singletonList(Hobby.BOOK)); + + ArrayList students = new ArrayList<>(); + students.add(john); + students.add(alice); + students.add(bob); + + AcademyClass academyClass = new AcademyClass(); + academyClass.setStudents(students); + academyClass.setTeacher(teacher); + + assertEquals(academyClass.toString(), "{\"students\":[{\"hobbies\":[\"BOOK\",\"MUSIC\"]},{\"hobbies\":[]},{\"hobbies\":[\"BOOK\"]}],\"teacher\":{\"hobbies\":[\"BOOK\",\"SPORT\",\"MUSIC\"]}}"); + } + @Test public void testPerson() { final Person p = new Person(); @@ -477,4 +547,73 @@ static class NestingPerson { */ Person person; } + + enum Hobby { + SPORT, + BOOK, + MUSIC + } + + enum EmptyEnum { + } + + static class Student { + List hobbies; + + public List getHobbies() { + return hobbies; + } + + public void setHobbies(List hobbies) { + this.hobbies = hobbies; + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this); + } + } + + static class Teacher { + Hobby[] hobbies; + + public Hobby[] getHobbies() { + return hobbies; + } + + public void setHobbies(Hobby[] hobbies) { + this.hobbies = hobbies; + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this); + } + } + + static class AcademyClass { + Teacher teacher; + List students; + + public void setTeacher(Teacher teacher) { + this.teacher = teacher; + } + + public void setStudents(List students) { + this.students = students; + } + + public Teacher getTeacher() { + return teacher; + } + + public List getStudents() { + return students; + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this); + } + } } From c56c77ed9502d079b3e885a65bc4a4cf666ac8ee Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Wed, 24 Jun 2020 10:41:19 -0400 Subject: [PATCH 0195/3230] Remove methods that will be new in 3.11 but which are now in the function package. --- .../org/apache/commons/lang3/Functions.java | 115 ------------------ .../apache/commons/lang3/FunctionsTest.java | 110 ----------------- 2 files changed, 225 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/Functions.java b/src/main/java/org/apache/commons/lang3/Functions.java index 4cf9d5589b2..a8cba225b73 100644 --- a/src/main/java/org/apache/commons/lang3/Functions.java +++ b/src/main/java/org/apache/commons/lang3/Functions.java @@ -313,42 +313,6 @@ public static void accept(final FailableConsumer run(() -> consumer.accept(object)); } - /** - * Consumes a consumer and rethrows any exception as a {@link RuntimeException}. - * - * @param consumer the consumer to consume - * @param value the value to consume by {@code consumer} - * @param the type of checked exception the consumer may throw - * @since 3.11 - */ - public static void accept(final FailableDoubleConsumer consumer, final double value) { - run(() -> consumer.accept(value)); - } - - /** - * Consumes a consumer and rethrows any exception as a {@link RuntimeException}. - * - * @param consumer the consumer to consume - * @param value the value to consume by {@code consumer} - * @param the type of checked exception the consumer may throw - * @since 3.11 - */ - public static void accept(final FailableIntConsumer consumer, final int value) { - run(() -> consumer.accept(value)); - } - - /** - * Consumes a consumer and rethrows any exception as a {@link RuntimeException}. - * - * @param consumer the consumer to consume - * @param value the value to consume by {@code consumer} - * @param the type of checked exception the consumer may throw - * @since 3.11 - */ - public static void accept(final FailableLongConsumer consumer, final long value) { - run(() -> consumer.accept(value)); - } - /** * Applies a function and rethrows any exception as a {@link RuntimeException}. * @@ -380,21 +344,6 @@ public static O apply(final FailableFunction function.apply(input)); } - /** - * Applies a function and rethrows any exception as a {@link RuntimeException}. - * - * @param function the function to apply - * @param left the first input to apply {@code function} on - * @param right the second input to apply {@code function} on - * @param the type of checked exception the function may throw - * @return the value returned from the function - * @since 3.11 - */ - public static double applyAsDouble(final FailableDoubleBinaryOperator function, - final double left, final double right) { - return getAsDouble(() -> function.applyAsDouble(left, right)); - } - /** * Converts the given {@link FailableBiConsumer} into a standard {@link BiConsumer}. * @@ -536,70 +485,6 @@ public static O get(final FailableSupplier suppli } } - /** - * Invokes a boolean supplier, and returns the result. - * - * @param supplier The boolean supplier to invoke. - * @param The type of checked exception, which the supplier can throw. - * @return The boolean, which has been created by the supplier - * @since 3.11 - */ - public static boolean getAsBoolean(final FailableBooleanSupplier supplier) { - try { - return supplier.getAsBoolean(); - } catch (final Throwable t) { - throw rethrow(t); - } - } - - /** - * Invokes a double supplier, and returns the result. - * - * @param supplier The double supplier to invoke. - * @param The type of checked exception, which the supplier can throw. - * @return The boolean, which has been created by the supplier - * @since 3.11 - */ - public static double getAsDouble(final FailableDoubleSupplier supplier) { - try { - return supplier.getAsDouble(); - } catch (final Throwable t) { - throw rethrow(t); - } - } - - /** - * Invokes an int supplier, and returns the result. - * - * @param supplier The int supplier to invoke. - * @param The type of checked exception, which the supplier can throw. - * @return The boolean, which has been created by the supplier - * @since 3.11 - */ - public static int getAsInt(final FailableIntSupplier supplier) { - try { - return supplier.getAsInt(); - } catch (final Throwable t) { - throw rethrow(t); - } - } - - /** - * Invokes a long supplier, and returns the result. - * - * @param supplier The long supplier to invoke. - * @param The type of checked exception, which the supplier can throw. - * @return The boolean, which has been created by the supplier - * @since 3.11 - */ - public static long getAsLong(final FailableLongSupplier supplier) { - try { - return supplier.getAsLong(); - } catch (final Throwable t) { - throw rethrow(t); - } - } - /** *

      * Rethrows a {@link Throwable} as an unchecked exception. If the argument is already unchecked, namely a diff --git a/src/test/java/org/apache/commons/lang3/FunctionsTest.java b/src/test/java/org/apache/commons/lang3/FunctionsTest.java index 3b2aa0e2625..3e58fd79041 100644 --- a/src/test/java/org/apache/commons/lang3/FunctionsTest.java +++ b/src/test/java/org/apache/commons/lang3/FunctionsTest.java @@ -510,19 +510,6 @@ public void testApplyBiFunction() { assertEquals(0, i.intValue()); } - @Test - public void testApplyDoubleBinaryOperator() { - final IllegalStateException ise = new IllegalStateException(); - final Testable testable = new Testable<>(ise); - Throwable e = assertThrows(IllegalStateException.class, - () -> Functions.applyAsDouble(testable::testDoubleDouble, 1d, 2d)); - assertSame(ise, e); - - final Testable testable2 = new Testable<>(null); - final double i = Functions.applyAsDouble(testable2::testDoubleDouble, 1d, 2d); - assertEquals(3d, i); - } - @Test public void testApplyFunction() { final IllegalStateException ise = new IllegalStateException(); @@ -736,103 +723,6 @@ public void testFunction() { assertEquals(0, function.apply(null).intValue()); } - @Test - public void testGetAsBooleanSupplier() { - final IllegalStateException ise = new IllegalStateException(); - final Testable testable = new Testable<>(ise); - Throwable e = assertThrows(IllegalStateException.class, - () -> Functions.getAsBoolean(testable::testAsBooleanPrimitive)); - assertSame(ise, e); - - final Error error = new OutOfMemoryError(); - testable.setThrowable(error); - e = assertThrows(OutOfMemoryError.class, () -> Functions.getAsBoolean(testable::testAsBooleanPrimitive)); - assertSame(error, e); - - final IOException ioe = new IOException("Unknown I/O error"); - testable.setThrowable(ioe); - e = assertThrows(UncheckedIOException.class, () -> Functions.getAsBoolean(testable::testAsBooleanPrimitive)); - final Throwable t = e.getCause(); - assertNotNull(t); - assertSame(ioe, t); - - testable.setThrowable(null); - assertFalse(Functions.getAsBoolean(testable::testAsBooleanPrimitive)); - } - - @Test - public void testGetAsDoubleSupplier() { - final IllegalStateException ise = new IllegalStateException(); - final Testable testable = new Testable<>(ise); - Throwable e = assertThrows(IllegalStateException.class, - () -> Functions.getAsDouble(testable::testAsDoublePrimitive)); - assertSame(ise, e); - - final Error error = new OutOfMemoryError(); - testable.setThrowable(error); - e = assertThrows(OutOfMemoryError.class, () -> Functions.getAsDouble(testable::testAsDoublePrimitive)); - assertSame(error, e); - - final IOException ioe = new IOException("Unknown I/O error"); - testable.setThrowable(ioe); - e = assertThrows(UncheckedIOException.class, () -> Functions.getAsDouble(testable::testAsDoublePrimitive)); - final Throwable t = e.getCause(); - assertNotNull(t); - assertSame(ioe, t); - - testable.setThrowable(null); - assertEquals(0, Functions.getAsDouble(testable::testAsDoublePrimitive)); - } - - @Test - public void testGetAsIntSupplier() { - final IllegalStateException ise = new IllegalStateException(); - final Testable testable = new Testable<>(ise); - Throwable e = assertThrows(IllegalStateException.class, () -> Functions.getAsInt(testable::testAsIntPrimitive)); - assertSame(ise, e); - - final Error error = new OutOfMemoryError(); - testable.setThrowable(error); - e = assertThrows(OutOfMemoryError.class, () -> Functions.getAsInt(testable::testAsIntPrimitive)); - assertSame(error, e); - - final IOException ioe = new IOException("Unknown I/O error"); - testable.setThrowable(ioe); - e = assertThrows(UncheckedIOException.class, () -> Functions.getAsInt(testable::testAsIntPrimitive)); - final Throwable t = e.getCause(); - assertNotNull(t); - assertSame(ioe, t); - - testable.setThrowable(null); - final int i = Functions.getAsInt(testable::testAsInteger); - assertEquals(0, i); - } - - @Test - public void testGetAsLongSupplier() { - final IllegalStateException ise = new IllegalStateException(); - final Testable testable = new Testable<>(ise); - Throwable e = assertThrows(IllegalStateException.class, - () -> Functions.getAsLong(testable::testAsLongPrimitive)); - assertSame(ise, e); - - final Error error = new OutOfMemoryError(); - testable.setThrowable(error); - e = assertThrows(OutOfMemoryError.class, () -> Functions.getAsLong(testable::testAsLongPrimitive)); - assertSame(error, e); - - final IOException ioe = new IOException("Unknown I/O error"); - testable.setThrowable(ioe); - e = assertThrows(UncheckedIOException.class, () -> Functions.getAsLong(testable::testAsLongPrimitive)); - final Throwable t = e.getCause(); - assertNotNull(t); - assertSame(ioe, t); - - testable.setThrowable(null); - final long i = Functions.getAsLong(testable::testAsLongPrimitive); - assertEquals(0, i); - } - @Test public void testGetFromSupplier() { FailureOnOddInvocations.invocations = 0; From fb184a7650fa0e5419c5afb51c88c2d40ef47d63 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Wed, 24 Jun 2020 10:43:04 -0400 Subject: [PATCH 0196/3230] Clean up imports. --- .../org/apache/commons/lang3/ArchUtils.java | 4 +- .../org/apache/commons/lang3/Functions.java | 8 ---- .../org/apache/commons/lang3/StringUtils.java | 2 +- .../lang3/builder/ToStringExclude.java | 2 +- .../lang3/concurrent/TimedSemaphore.java | 4 +- .../commons/lang3/math/NumberUtils.java | 2 +- .../commons/lang3/AnnotationUtilsTest.java | 2 +- .../apache/commons/lang3/ArchUtilsTest.java | 14 +++---- .../apache/commons/lang3/ArrayUtilsTest.java | 2 +- .../commons/lang3/CharEncodingTest.java | 4 +- .../apache/commons/lang3/ClassUtilsTest.java | 32 ++++++++-------- .../apache/commons/lang3/FunctionsTest.java | 1 - .../apache/commons/lang3/JavaVersionTest.java | 4 +- .../lang3/NotImplementedExceptionTest.java | 3 +- .../apache/commons/lang3/RandomUtilsTest.java | 4 +- .../lang3/StringUtilsStartsEndsWithTest.java | 4 +- .../apache/commons/lang3/SystemUtilsTest.java | 8 ++-- .../apache/commons/lang3/ValidateTest.java | 16 ++++---- .../lang3/builder/JsonToStringStyleTest.java | 12 +++--- .../builder/NoClassNameToStringStyleTest.java | 10 ++--- ...tringBuilderExcludeWithAnnotationTest.java | 2 +- .../ReflectionToStringBuilderSummaryTest.java | 4 +- .../ReflectionToStringBuilderTest.java | 4 +- .../concurrent/BackgroundInitializerTest.java | 4 +- .../CircuitBreakingExceptionTest.java | 6 +-- .../lang3/concurrent/ConcurrentUtilsTest.java | 2 +- .../lang3/concurrent/MemoizerTest.java | 8 ++-- .../AbstractExceptionContextTest.java | 5 +-- .../exception/CloneFailedExceptionTest.java | 4 +- .../commons/lang3/math/NumberUtilsTest.java | 2 +- .../lang3/mutable/MutableBooleanTest.java | 4 +- .../lang3/mutable/MutableByteTest.java | 4 +- .../lang3/mutable/MutableDoubleTest.java | 4 +- .../lang3/mutable/MutableFloatTest.java | 4 +- .../commons/lang3/mutable/MutableIntTest.java | 4 +- .../lang3/mutable/MutableLongTest.java | 4 +- .../lang3/mutable/MutableShortTest.java | 4 +- .../commons/lang3/reflect/FieldUtilsTest.java | 37 +++++++++---------- .../lang3/reflect/InheritanceUtilsTest.java | 6 +-- .../lang3/reflect/MethodUtilsTest.java | 2 +- .../lang3/text/CompositeFormatTest.java | 4 +- .../lang3/text/ExtendedMessageFormatTest.java | 6 +-- .../text/StrBuilderAppendInsertTest.java | 4 +- .../commons/lang3/text/StrBuilderTest.java | 3 +- .../commons/lang3/text/StrTokenizerTest.java | 3 +- .../text/translate/OctalUnescaperTest.java | 3 +- .../UnicodeUnpairedSurrogateRemoverTest.java | 1 + .../lang3/time/DateUtilsFragmentTest.java | 6 +-- .../lang3/time/DateUtilsRoundingTest.java | 6 +-- .../lang3/time/FastDateParserTest.java | 1 + .../FastDateParser_TimeZoneStrategyTest.java | 8 ++-- .../commons/lang3/time/FastTimeZoneTest.java | 4 +- .../commons/lang3/time/StopWatchTest.java | 2 +- .../lang3/tuple/ImmutableTripleTest.java | 2 +- 54 files changed, 148 insertions(+), 157 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/ArchUtils.java b/src/main/java/org/apache/commons/lang3/ArchUtils.java index e0b2aae8cab..20ba2fb4ca6 100644 --- a/src/main/java/org/apache/commons/lang3/ArchUtils.java +++ b/src/main/java/org/apache/commons/lang3/ArchUtils.java @@ -16,12 +16,12 @@ */ package org.apache.commons.lang3; -import org.apache.commons.lang3.arch.Processor; - import java.util.HashMap; import java.util.Map; import java.util.stream.Stream; +import org.apache.commons.lang3.arch.Processor; + /** * An utility class for the os.arch System Property. The class defines methods for * identifying the architecture of the current JVM. diff --git a/src/main/java/org/apache/commons/lang3/Functions.java b/src/main/java/org/apache/commons/lang3/Functions.java index a8cba225b73..7186caa521c 100644 --- a/src/main/java/org/apache/commons/lang3/Functions.java +++ b/src/main/java/org/apache/commons/lang3/Functions.java @@ -32,14 +32,6 @@ import java.util.stream.Stream; import org.apache.commons.lang3.Streams.FailableStream; -import org.apache.commons.lang3.function.FailableBooleanSupplier; -import org.apache.commons.lang3.function.FailableDoubleBinaryOperator; -import org.apache.commons.lang3.function.FailableDoubleConsumer; -import org.apache.commons.lang3.function.FailableDoubleSupplier; -import org.apache.commons.lang3.function.FailableIntConsumer; -import org.apache.commons.lang3.function.FailableIntSupplier; -import org.apache.commons.lang3.function.FailableLongConsumer; -import org.apache.commons.lang3.function.FailableLongSupplier; /** * This class provides utility functions, and classes for working with the {@code java.util.function} package, or more diff --git a/src/main/java/org/apache/commons/lang3/StringUtils.java b/src/main/java/org/apache/commons/lang3/StringUtils.java index ec9f6160cfc..1ae2e38e4a4 100644 --- a/src/main/java/org/apache/commons/lang3/StringUtils.java +++ b/src/main/java/org/apache/commons/lang3/StringUtils.java @@ -21,11 +21,11 @@ import java.text.Normalizer; import java.util.ArrayList; import java.util.Arrays; +import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Objects; -import java.util.HashSet; import java.util.Set; import java.util.function.Supplier; import java.util.regex.Pattern; diff --git a/src/main/java/org/apache/commons/lang3/builder/ToStringExclude.java b/src/main/java/org/apache/commons/lang3/builder/ToStringExclude.java index 41dcf67396d..2b399f288d8 100755 --- a/src/main/java/org/apache/commons/lang3/builder/ToStringExclude.java +++ b/src/main/java/org/apache/commons/lang3/builder/ToStringExclude.java @@ -19,8 +19,8 @@ import java.lang.annotation.ElementType; import java.lang.annotation.Retention; -import java.lang.annotation.Target; import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; /** * Use this annotation to exclude a field from being used by diff --git a/src/main/java/org/apache/commons/lang3/concurrent/TimedSemaphore.java b/src/main/java/org/apache/commons/lang3/concurrent/TimedSemaphore.java index 23c3cf3eb46..28e0eb1d703 100644 --- a/src/main/java/org/apache/commons/lang3/concurrent/TimedSemaphore.java +++ b/src/main/java/org/apache/commons/lang3/concurrent/TimedSemaphore.java @@ -16,13 +16,13 @@ */ package org.apache.commons.lang3.concurrent; -import org.apache.commons.lang3.Validate; - import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; +import org.apache.commons.lang3.Validate; + /** *

      * A specialized semaphore implementation that provides a number of diff --git a/src/main/java/org/apache/commons/lang3/math/NumberUtils.java b/src/main/java/org/apache/commons/lang3/math/NumberUtils.java index 38240c2d161..c9ea0695649 100644 --- a/src/main/java/org/apache/commons/lang3/math/NumberUtils.java +++ b/src/main/java/org/apache/commons/lang3/math/NumberUtils.java @@ -19,8 +19,8 @@ import java.lang.reflect.Array; import java.math.BigDecimal; import java.math.BigInteger; - import java.math.RoundingMode; + import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.Validate; diff --git a/src/test/java/org/apache/commons/lang3/AnnotationUtilsTest.java b/src/test/java/org/apache/commons/lang3/AnnotationUtilsTest.java index a791daafbe4..32824f30863 100644 --- a/src/test/java/org/apache/commons/lang3/AnnotationUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/AnnotationUtilsTest.java @@ -40,8 +40,8 @@ import java.util.Collection; import java.util.Map; -import org.junit.jupiter.api.Test; import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** */ diff --git a/src/test/java/org/apache/commons/lang3/ArchUtilsTest.java b/src/test/java/org/apache/commons/lang3/ArchUtilsTest.java index 0ba4c055955..1c3851a3632 100644 --- a/src/test/java/org/apache/commons/lang3/ArchUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/ArchUtilsTest.java @@ -16,17 +16,17 @@ */ package org.apache.commons.lang3; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import org.apache.commons.lang3.arch.Processor; import org.apache.commons.lang3.arch.Processor.Arch; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; - /** * Test class for {@link ArchUtils}. */ diff --git a/src/test/java/org/apache/commons/lang3/ArrayUtilsTest.java b/src/test/java/org/apache/commons/lang3/ArrayUtilsTest.java index 78d61f0a703..f5b40ad126f 100644 --- a/src/test/java/org/apache/commons/lang3/ArrayUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/ArrayUtilsTest.java @@ -30,8 +30,8 @@ import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.util.Arrays; -import java.util.Collections; import java.util.BitSet; +import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.Map; diff --git a/src/test/java/org/apache/commons/lang3/CharEncodingTest.java b/src/test/java/org/apache/commons/lang3/CharEncodingTest.java index 37a09ae3e91..15cc34a17f1 100644 --- a/src/test/java/org/apache/commons/lang3/CharEncodingTest.java +++ b/src/test/java/org/apache/commons/lang3/CharEncodingTest.java @@ -21,10 +21,10 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.jupiter.api.Test; - import java.nio.charset.StandardCharsets; +import org.junit.jupiter.api.Test; + /** * Tests CharEncoding. * diff --git a/src/test/java/org/apache/commons/lang3/ClassUtilsTest.java b/src/test/java/org/apache/commons/lang3/ClassUtilsTest.java index 68b19a01720..e9b9c117664 100644 --- a/src/test/java/org/apache/commons/lang3/ClassUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/ClassUtilsTest.java @@ -16,13 +16,15 @@ */ package org.apache.commons.lang3; -import org.apache.commons.lang3.ClassUtils.Interfaces; -import org.apache.commons.lang3.reflect.testbed.GenericConsumer; -import org.apache.commons.lang3.reflect.testbed.GenericParent; -import org.apache.commons.lang3.reflect.testbed.StringParameterizedChild; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.lang.reflect.Constructor; import java.lang.reflect.Method; @@ -35,15 +37,13 @@ import java.util.Map; import java.util.Set; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNotSame; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; +import org.apache.commons.lang3.ClassUtils.Interfaces; +import org.apache.commons.lang3.reflect.testbed.GenericConsumer; +import org.apache.commons.lang3.reflect.testbed.GenericParent; +import org.apache.commons.lang3.reflect.testbed.StringParameterizedChild; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; /** * Unit tests {@link org.apache.commons.lang3.ClassUtils}. diff --git a/src/test/java/org/apache/commons/lang3/FunctionsTest.java b/src/test/java/org/apache/commons/lang3/FunctionsTest.java index 3e58fd79041..798591294bf 100644 --- a/src/test/java/org/apache/commons/lang3/FunctionsTest.java +++ b/src/test/java/org/apache/commons/lang3/FunctionsTest.java @@ -17,7 +17,6 @@ package org.apache.commons.lang3; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; diff --git a/src/test/java/org/apache/commons/lang3/JavaVersionTest.java b/src/test/java/org/apache/commons/lang3/JavaVersionTest.java index c06b57c6b82..fbfd62dc998 100644 --- a/src/test/java/org/apache/commons/lang3/JavaVersionTest.java +++ b/src/test/java/org/apache/commons/lang3/JavaVersionTest.java @@ -18,8 +18,6 @@ */ package org.apache.commons.lang3; -import org.junit.jupiter.api.Test; - import static org.apache.commons.lang3.JavaVersion.JAVA_0_9; import static org.apache.commons.lang3.JavaVersion.JAVA_10; import static org.apache.commons.lang3.JavaVersion.JAVA_11; @@ -43,6 +41,8 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Test; + /** * Unit tests {@link org.apache.commons.lang3.JavaVersion}. */ diff --git a/src/test/java/org/apache/commons/lang3/NotImplementedExceptionTest.java b/src/test/java/org/apache/commons/lang3/NotImplementedExceptionTest.java index 77f7638511b..5bd6b391b90 100644 --- a/src/test/java/org/apache/commons/lang3/NotImplementedExceptionTest.java +++ b/src/test/java/org/apache/commons/lang3/NotImplementedExceptionTest.java @@ -16,10 +16,11 @@ */ package org.apache.commons.lang3; -import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; +import org.junit.jupiter.api.Test; + /** * Unit tests {@link org.apache.commons.lang3.NotImplementedException}. */ diff --git a/src/test/java/org/apache/commons/lang3/RandomUtilsTest.java b/src/test/java/org/apache/commons/lang3/RandomUtilsTest.java index 6a0a2434a1d..b05c71906e2 100644 --- a/src/test/java/org/apache/commons/lang3/RandomUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/RandomUtilsTest.java @@ -23,11 +23,11 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.jupiter.api.Test; - import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; +import org.junit.jupiter.api.Test; + /** * Tests for {@link RandomUtils} */ diff --git a/src/test/java/org/apache/commons/lang3/StringUtilsStartsEndsWithTest.java b/src/test/java/org/apache/commons/lang3/StringUtilsStartsEndsWithTest.java index a0be2da7c15..b7e4cd84257 100644 --- a/src/test/java/org/apache/commons/lang3/StringUtilsStartsEndsWithTest.java +++ b/src/test/java/org/apache/commons/lang3/StringUtilsStartsEndsWithTest.java @@ -16,11 +16,11 @@ */ package org.apache.commons.lang3; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Test; + /** * Unit tests {@link org.apache.commons.lang3.StringUtils} - StartsWith/EndsWith methods diff --git a/src/test/java/org/apache/commons/lang3/SystemUtilsTest.java b/src/test/java/org/apache/commons/lang3/SystemUtilsTest.java index be5af2d008e..85aa59bc370 100644 --- a/src/test/java/org/apache/commons/lang3/SystemUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/SystemUtilsTest.java @@ -19,6 +19,10 @@ package org.apache.commons.lang3; +import static org.apache.commons.lang3.JavaVersion.JAVA_10; +import static org.apache.commons.lang3.JavaVersion.JAVA_11; +import static org.apache.commons.lang3.JavaVersion.JAVA_12; +import static org.apache.commons.lang3.JavaVersion.JAVA_13; import static org.apache.commons.lang3.JavaVersion.JAVA_1_1; import static org.apache.commons.lang3.JavaVersion.JAVA_1_2; import static org.apache.commons.lang3.JavaVersion.JAVA_1_3; @@ -28,10 +32,6 @@ import static org.apache.commons.lang3.JavaVersion.JAVA_1_7; import static org.apache.commons.lang3.JavaVersion.JAVA_1_8; import static org.apache.commons.lang3.JavaVersion.JAVA_9; -import static org.apache.commons.lang3.JavaVersion.JAVA_10; -import static org.apache.commons.lang3.JavaVersion.JAVA_11; -import static org.apache.commons.lang3.JavaVersion.JAVA_12; -import static org.apache.commons.lang3.JavaVersion.JAVA_13; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; diff --git a/src/test/java/org/apache/commons/lang3/ValidateTest.java b/src/test/java/org/apache/commons/lang3/ValidateTest.java index 0aa6edfdbbf..e273ae52b71 100644 --- a/src/test/java/org/apache/commons/lang3/ValidateTest.java +++ b/src/test/java/org/apache/commons/lang3/ValidateTest.java @@ -18,8 +18,12 @@ */ package org.apache.commons.lang3; -import org.junit.jupiter.api.Nested; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; @@ -29,12 +33,8 @@ import java.util.Map; import java.util.Set; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; /** * Unit tests {@link org.apache.commons.lang3.Validate}. diff --git a/src/test/java/org/apache/commons/lang3/builder/JsonToStringStyleTest.java b/src/test/java/org/apache/commons/lang3/builder/JsonToStringStyleTest.java index ed7bf34188f..623ddb90aba 100644 --- a/src/test/java/org/apache/commons/lang3/builder/JsonToStringStyleTest.java +++ b/src/test/java/org/apache/commons/lang3/builder/JsonToStringStyleTest.java @@ -16,10 +16,8 @@ */ package org.apache.commons.lang3.builder; -import org.apache.commons.lang3.builder.ToStringStyleTest.Person; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.ArrayList; import java.util.Arrays; @@ -28,8 +26,10 @@ import java.util.HashMap; import java.util.List; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; +import org.apache.commons.lang3.builder.ToStringStyleTest.Person; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Unit tests {@link org.apache.commons.lang3.builder.JsonToStringStyleTest}. diff --git a/src/test/java/org/apache/commons/lang3/builder/NoClassNameToStringStyleTest.java b/src/test/java/org/apache/commons/lang3/builder/NoClassNameToStringStyleTest.java index 97a1e4d9917..bd950009b9c 100644 --- a/src/test/java/org/apache/commons/lang3/builder/NoClassNameToStringStyleTest.java +++ b/src/test/java/org/apache/commons/lang3/builder/NoClassNameToStringStyleTest.java @@ -16,15 +16,15 @@ */ package org.apache.commons.lang3.builder; -import org.apache.commons.lang3.builder.ToStringStyleTest.Person; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.ArrayList; import java.util.HashMap; -import static org.junit.jupiter.api.Assertions.assertEquals; +import org.apache.commons.lang3.builder.ToStringStyleTest.Person; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Unit tests {@link ToStringStyle#NO_CLASS_NAME_STYLE}. diff --git a/src/test/java/org/apache/commons/lang3/builder/ReflectionToStringBuilderExcludeWithAnnotationTest.java b/src/test/java/org/apache/commons/lang3/builder/ReflectionToStringBuilderExcludeWithAnnotationTest.java index 03e2bbaca2b..b8d464369c0 100644 --- a/src/test/java/org/apache/commons/lang3/builder/ReflectionToStringBuilderExcludeWithAnnotationTest.java +++ b/src/test/java/org/apache/commons/lang3/builder/ReflectionToStringBuilderExcludeWithAnnotationTest.java @@ -17,9 +17,9 @@ package org.apache.commons.lang3.builder; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.not; -import static org.hamcrest.MatcherAssert.assertThat; import org.junit.jupiter.api.Test; diff --git a/src/test/java/org/apache/commons/lang3/builder/ReflectionToStringBuilderSummaryTest.java b/src/test/java/org/apache/commons/lang3/builder/ReflectionToStringBuilderSummaryTest.java index dfd549c2499..02840f0376d 100644 --- a/src/test/java/org/apache/commons/lang3/builder/ReflectionToStringBuilderSummaryTest.java +++ b/src/test/java/org/apache/commons/lang3/builder/ReflectionToStringBuilderSummaryTest.java @@ -16,10 +16,10 @@ */ package org.apache.commons.lang3.builder; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; + public class ReflectionToStringBuilderSummaryTest { @SuppressWarnings("unused") diff --git a/src/test/java/org/apache/commons/lang3/builder/ReflectionToStringBuilderTest.java b/src/test/java/org/apache/commons/lang3/builder/ReflectionToStringBuilderTest.java index b85bd9a7557..1765ca49898 100644 --- a/src/test/java/org/apache/commons/lang3/builder/ReflectionToStringBuilderTest.java +++ b/src/test/java/org/apache/commons/lang3/builder/ReflectionToStringBuilderTest.java @@ -16,10 +16,10 @@ */ package org.apache.commons.lang3.builder; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertThrows; +import org.junit.jupiter.api.Test; + public class ReflectionToStringBuilderTest { @Test diff --git a/src/test/java/org/apache/commons/lang3/concurrent/BackgroundInitializerTest.java b/src/test/java/org/apache/commons/lang3/concurrent/BackgroundInitializerTest.java index ecb4a160f99..c541e8f2968 100644 --- a/src/test/java/org/apache/commons/lang3/concurrent/BackgroundInitializerTest.java +++ b/src/test/java/org/apache/commons/lang3/concurrent/BackgroundInitializerTest.java @@ -16,8 +16,6 @@ */ package org.apache.commons.lang3.concurrent; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; @@ -32,6 +30,8 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; +import org.junit.jupiter.api.Test; + public class BackgroundInitializerTest { /** * Helper method for checking whether the initialize() method was correctly diff --git a/src/test/java/org/apache/commons/lang3/concurrent/CircuitBreakingExceptionTest.java b/src/test/java/org/apache/commons/lang3/concurrent/CircuitBreakingExceptionTest.java index 573f1388cbf..bf19b49c46a 100644 --- a/src/test/java/org/apache/commons/lang3/concurrent/CircuitBreakingExceptionTest.java +++ b/src/test/java/org/apache/commons/lang3/concurrent/CircuitBreakingExceptionTest.java @@ -16,14 +16,14 @@ */ package org.apache.commons.lang3.concurrent; -import org.apache.commons.lang3.exception.AbstractExceptionTest; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; +import org.apache.commons.lang3.exception.AbstractExceptionTest; +import org.junit.jupiter.api.Test; + /** * JUnit tests for {@link CircuitBreakingException}. diff --git a/src/test/java/org/apache/commons/lang3/concurrent/ConcurrentUtilsTest.java b/src/test/java/org/apache/commons/lang3/concurrent/ConcurrentUtilsTest.java index 075c6f80703..d5d55f5b26f 100644 --- a/src/test/java/org/apache/commons/lang3/concurrent/ConcurrentUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/concurrent/ConcurrentUtilsTest.java @@ -18,8 +18,8 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; diff --git a/src/test/java/org/apache/commons/lang3/concurrent/MemoizerTest.java b/src/test/java/org/apache/commons/lang3/concurrent/MemoizerTest.java index a6c4dd208a9..d45800d49c8 100644 --- a/src/test/java/org/apache/commons/lang3/concurrent/MemoizerTest.java +++ b/src/test/java/org/apache/commons/lang3/concurrent/MemoizerTest.java @@ -16,15 +16,15 @@ */ package org.apache.commons.lang3.concurrent; -import org.easymock.EasyMock; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.replay; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; +import org.easymock.EasyMock; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + public class MemoizerTest { private Computable computable; diff --git a/src/test/java/org/apache/commons/lang3/exception/AbstractExceptionContextTest.java b/src/test/java/org/apache/commons/lang3/exception/AbstractExceptionContextTest.java index 81b36736067..36c49111ae8 100644 --- a/src/test/java/org/apache/commons/lang3/exception/AbstractExceptionContextTest.java +++ b/src/test/java/org/apache/commons/lang3/exception/AbstractExceptionContextTest.java @@ -16,9 +16,6 @@ */ package org.apache.commons.lang3.exception; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.BeforeEach; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; @@ -33,6 +30,8 @@ import org.apache.commons.lang3.SerializationUtils; import org.apache.commons.lang3.tuple.Pair; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** diff --git a/src/test/java/org/apache/commons/lang3/exception/CloneFailedExceptionTest.java b/src/test/java/org/apache/commons/lang3/exception/CloneFailedExceptionTest.java index 3ea05e7ea39..5123fe174c6 100644 --- a/src/test/java/org/apache/commons/lang3/exception/CloneFailedExceptionTest.java +++ b/src/test/java/org/apache/commons/lang3/exception/CloneFailedExceptionTest.java @@ -16,13 +16,13 @@ */ package org.apache.commons.lang3.exception; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; +import org.junit.jupiter.api.Test; + /** * JUnit tests for {@link CloneFailedExceptionTest}. */ diff --git a/src/test/java/org/apache/commons/lang3/math/NumberUtilsTest.java b/src/test/java/org/apache/commons/lang3/math/NumberUtilsTest.java index 922120be42a..523cb0cc4d2 100644 --- a/src/test/java/org/apache/commons/lang3/math/NumberUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/math/NumberUtilsTest.java @@ -27,8 +27,8 @@ import java.lang.reflect.Modifier; import java.math.BigDecimal; import java.math.BigInteger; - import java.math.RoundingMode; + import org.junit.jupiter.api.Test; /** diff --git a/src/test/java/org/apache/commons/lang3/mutable/MutableBooleanTest.java b/src/test/java/org/apache/commons/lang3/mutable/MutableBooleanTest.java index e159ea593cd..02155a25734 100644 --- a/src/test/java/org/apache/commons/lang3/mutable/MutableBooleanTest.java +++ b/src/test/java/org/apache/commons/lang3/mutable/MutableBooleanTest.java @@ -17,14 +17,14 @@ package org.apache.commons.lang3.mutable; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Test; + /** * JUnit tests. * diff --git a/src/test/java/org/apache/commons/lang3/mutable/MutableByteTest.java b/src/test/java/org/apache/commons/lang3/mutable/MutableByteTest.java index fc3b4afa5b3..1f2e9788b38 100644 --- a/src/test/java/org/apache/commons/lang3/mutable/MutableByteTest.java +++ b/src/test/java/org/apache/commons/lang3/mutable/MutableByteTest.java @@ -16,12 +16,12 @@ */ package org.apache.commons.lang3.mutable; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertThrows; +import org.junit.jupiter.api.Test; + /** * JUnit tests. * diff --git a/src/test/java/org/apache/commons/lang3/mutable/MutableDoubleTest.java b/src/test/java/org/apache/commons/lang3/mutable/MutableDoubleTest.java index 48f83995f31..ccb8fc71d55 100644 --- a/src/test/java/org/apache/commons/lang3/mutable/MutableDoubleTest.java +++ b/src/test/java/org/apache/commons/lang3/mutable/MutableDoubleTest.java @@ -16,13 +16,13 @@ */ package org.apache.commons.lang3.mutable; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Test; + /** * JUnit tests. * diff --git a/src/test/java/org/apache/commons/lang3/mutable/MutableFloatTest.java b/src/test/java/org/apache/commons/lang3/mutable/MutableFloatTest.java index 03b8e6b5d9d..f3105bbbfe0 100644 --- a/src/test/java/org/apache/commons/lang3/mutable/MutableFloatTest.java +++ b/src/test/java/org/apache/commons/lang3/mutable/MutableFloatTest.java @@ -16,13 +16,13 @@ */ package org.apache.commons.lang3.mutable; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Test; + /** * JUnit tests. * diff --git a/src/test/java/org/apache/commons/lang3/mutable/MutableIntTest.java b/src/test/java/org/apache/commons/lang3/mutable/MutableIntTest.java index 72b9960b56e..a02a2c53255 100644 --- a/src/test/java/org/apache/commons/lang3/mutable/MutableIntTest.java +++ b/src/test/java/org/apache/commons/lang3/mutable/MutableIntTest.java @@ -16,12 +16,12 @@ */ package org.apache.commons.lang3.mutable; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertThrows; +import org.junit.jupiter.api.Test; + /** * JUnit tests. * diff --git a/src/test/java/org/apache/commons/lang3/mutable/MutableLongTest.java b/src/test/java/org/apache/commons/lang3/mutable/MutableLongTest.java index efac772e497..8d1b999d225 100644 --- a/src/test/java/org/apache/commons/lang3/mutable/MutableLongTest.java +++ b/src/test/java/org/apache/commons/lang3/mutable/MutableLongTest.java @@ -16,12 +16,12 @@ */ package org.apache.commons.lang3.mutable; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertThrows; +import org.junit.jupiter.api.Test; + /** * JUnit tests. * diff --git a/src/test/java/org/apache/commons/lang3/mutable/MutableShortTest.java b/src/test/java/org/apache/commons/lang3/mutable/MutableShortTest.java index f44020c3e2a..c5b32cf6d96 100644 --- a/src/test/java/org/apache/commons/lang3/mutable/MutableShortTest.java +++ b/src/test/java/org/apache/commons/lang3/mutable/MutableShortTest.java @@ -16,12 +16,12 @@ */ package org.apache.commons.lang3.mutable; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertThrows; +import org.junit.jupiter.api.Test; + /** * JUnit tests. * diff --git a/src/test/java/org/apache/commons/lang3/reflect/FieldUtilsTest.java b/src/test/java/org/apache/commons/lang3/reflect/FieldUtilsTest.java index 20ae2acadb8..f52de064eae 100644 --- a/src/test/java/org/apache/commons/lang3/reflect/FieldUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/reflect/FieldUtilsTest.java @@ -16,8 +16,25 @@ */ package org.apache.commons.lang3.reflect; -import org.apache.commons.lang3.ArrayUtils; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import static org.junit.jupiter.api.Assumptions.assumeTrue; +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; + +import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.JavaVersion; import org.apache.commons.lang3.SystemUtils; import org.apache.commons.lang3.reflect.testbed.Ambig; @@ -31,24 +48,6 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.Modifier; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; -import static org.junit.jupiter.api.Assumptions.assumeTrue; - /** * Unit tests FieldUtils */ diff --git a/src/test/java/org/apache/commons/lang3/reflect/InheritanceUtilsTest.java b/src/test/java/org/apache/commons/lang3/reflect/InheritanceUtilsTest.java index d03bc4fb10f..874acf66481 100644 --- a/src/test/java/org/apache/commons/lang3/reflect/InheritanceUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/reflect/InheritanceUtilsTest.java @@ -16,14 +16,14 @@ */ package org.apache.commons.lang3.reflect; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + import org.apache.commons.lang3.reflect.testbed.AnotherChild; import org.apache.commons.lang3.reflect.testbed.AnotherParent; import org.apache.commons.lang3.reflect.testbed.Grandchild; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - /** * Unit tests InheritanceUtils */ diff --git a/src/test/java/org/apache/commons/lang3/reflect/MethodUtilsTest.java b/src/test/java/org/apache/commons/lang3/reflect/MethodUtilsTest.java index 9966efe21b4..ceafcac087f 100644 --- a/src/test/java/org/apache/commons/lang3/reflect/MethodUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/reflect/MethodUtilsTest.java @@ -16,9 +16,9 @@ */ package org.apache.commons.lang3.reflect; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasItemInArray; import static org.hamcrest.Matchers.hasItems; -import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; diff --git a/src/test/java/org/apache/commons/lang3/text/CompositeFormatTest.java b/src/test/java/org/apache/commons/lang3/text/CompositeFormatTest.java index ec2f0403d56..63015fb2b5a 100644 --- a/src/test/java/org/apache/commons/lang3/text/CompositeFormatTest.java +++ b/src/test/java/org/apache/commons/lang3/text/CompositeFormatTest.java @@ -17,8 +17,6 @@ package org.apache.commons.lang3.text; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; import java.text.FieldPosition; @@ -27,6 +25,8 @@ import java.text.SimpleDateFormat; import java.util.Locale; +import org.junit.jupiter.api.Test; + /** * Unit tests for {@link org.apache.commons.lang3.text.CompositeFormat}. */ diff --git a/src/test/java/org/apache/commons/lang3/text/ExtendedMessageFormatTest.java b/src/test/java/org/apache/commons/lang3/text/ExtendedMessageFormatTest.java index 4a3ad319981..7aa3c201f88 100644 --- a/src/test/java/org/apache/commons/lang3/text/ExtendedMessageFormatTest.java +++ b/src/test/java/org/apache/commons/lang3/text/ExtendedMessageFormatTest.java @@ -16,9 +16,6 @@ */ package org.apache.commons.lang3.text; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.BeforeEach; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; @@ -36,6 +33,9 @@ import java.util.Locale; import java.util.Map; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + /** * Test case for {@link ExtendedMessageFormat}. * diff --git a/src/test/java/org/apache/commons/lang3/text/StrBuilderAppendInsertTest.java b/src/test/java/org/apache/commons/lang3/text/StrBuilderAppendInsertTest.java index 6059fda35e3..8ae0b90bc30 100644 --- a/src/test/java/org/apache/commons/lang3/text/StrBuilderAppendInsertTest.java +++ b/src/test/java/org/apache/commons/lang3/text/StrBuilderAppendInsertTest.java @@ -17,8 +17,6 @@ package org.apache.commons.lang3.text; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -28,6 +26,8 @@ import java.util.Collections; import java.util.Iterator; +import org.junit.jupiter.api.Test; + /** * Unit tests for {@link org.apache.commons.lang3.text.StrBuilder}. */ diff --git a/src/test/java/org/apache/commons/lang3/text/StrBuilderTest.java b/src/test/java/org/apache/commons/lang3/text/StrBuilderTest.java index cd13cdaadfa..ef7c567e42d 100644 --- a/src/test/java/org/apache/commons/lang3/text/StrBuilderTest.java +++ b/src/test/java/org/apache/commons/lang3/text/StrBuilderTest.java @@ -17,8 +17,6 @@ package org.apache.commons.lang3.text; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -38,6 +36,7 @@ import java.nio.CharBuffer; import org.apache.commons.lang3.ArrayUtils; +import org.junit.jupiter.api.Test; /** * Unit tests for {@link org.apache.commons.lang3.text.StrBuilder}. diff --git a/src/test/java/org/apache/commons/lang3/text/StrTokenizerTest.java b/src/test/java/org/apache/commons/lang3/text/StrTokenizerTest.java index acb18e74363..4ca0dac8edb 100644 --- a/src/test/java/org/apache/commons/lang3/text/StrTokenizerTest.java +++ b/src/test/java/org/apache/commons/lang3/text/StrTokenizerTest.java @@ -17,8 +17,6 @@ package org.apache.commons.lang3.text; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotSame; @@ -32,6 +30,7 @@ import java.util.NoSuchElementException; import org.apache.commons.lang3.ArrayUtils; +import org.junit.jupiter.api.Test; /** * Unit test for Tokenizer. diff --git a/src/test/java/org/apache/commons/lang3/text/translate/OctalUnescaperTest.java b/src/test/java/org/apache/commons/lang3/text/translate/OctalUnescaperTest.java index 99e938b5b44..6071d64d9a9 100644 --- a/src/test/java/org/apache/commons/lang3/text/translate/OctalUnescaperTest.java +++ b/src/test/java/org/apache/commons/lang3/text/translate/OctalUnescaperTest.java @@ -17,9 +17,10 @@ package org.apache.commons.lang3.text.translate; -import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; + /** * Unit tests for {@link org.apache.commons.lang3.text.translate.OctalUnescaper}. */ diff --git a/src/test/java/org/apache/commons/lang3/text/translate/UnicodeUnpairedSurrogateRemoverTest.java b/src/test/java/org/apache/commons/lang3/text/translate/UnicodeUnpairedSurrogateRemoverTest.java index 7c9d4353efe..7b23586b991 100644 --- a/src/test/java/org/apache/commons/lang3/text/translate/UnicodeUnpairedSurrogateRemoverTest.java +++ b/src/test/java/org/apache/commons/lang3/text/translate/UnicodeUnpairedSurrogateRemoverTest.java @@ -22,6 +22,7 @@ import java.io.CharArrayWriter; import java.io.IOException; + import org.junit.jupiter.api.Test; /** diff --git a/src/test/java/org/apache/commons/lang3/time/DateUtilsFragmentTest.java b/src/test/java/org/apache/commons/lang3/time/DateUtilsFragmentTest.java index be6f23ba164..a920455a7e2 100644 --- a/src/test/java/org/apache/commons/lang3/time/DateUtilsFragmentTest.java +++ b/src/test/java/org/apache/commons/lang3/time/DateUtilsFragmentTest.java @@ -16,15 +16,15 @@ */ package org.apache.commons.lang3.time; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.BeforeEach; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.Calendar; import java.util.Date; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + public class DateUtilsFragmentTest { private static final int months = 7; // second final prime before 12 diff --git a/src/test/java/org/apache/commons/lang3/time/DateUtilsRoundingTest.java b/src/test/java/org/apache/commons/lang3/time/DateUtilsRoundingTest.java index 65b0ec4bca3..a13b161a2a6 100644 --- a/src/test/java/org/apache/commons/lang3/time/DateUtilsRoundingTest.java +++ b/src/test/java/org/apache/commons/lang3/time/DateUtilsRoundingTest.java @@ -16,9 +16,6 @@ */ package org.apache.commons.lang3.time; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.BeforeEach; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; @@ -28,6 +25,9 @@ import java.util.Date; import java.util.Locale; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + /** * These Unit-tests will check all possible extremes when using some rounding-methods of DateUtils. * The extremes are tested at the switch-point in milliseconds diff --git a/src/test/java/org/apache/commons/lang3/time/FastDateParserTest.java b/src/test/java/org/apache/commons/lang3/time/FastDateParserTest.java index 529d662336f..4c7fd3f92e6 100644 --- a/src/test/java/org/apache/commons/lang3/time/FastDateParserTest.java +++ b/src/test/java/org/apache/commons/lang3/time/FastDateParserTest.java @@ -33,6 +33,7 @@ import java.util.Locale; import java.util.Map; import java.util.TimeZone; + import org.apache.commons.lang3.LocaleUtils; import org.apache.commons.lang3.SerializationUtils; import org.junit.jupiter.api.Test; diff --git a/src/test/java/org/apache/commons/lang3/time/FastDateParser_TimeZoneStrategyTest.java b/src/test/java/org/apache/commons/lang3/time/FastDateParser_TimeZoneStrategyTest.java index bd9fb044846..d2f106ec4bd 100644 --- a/src/test/java/org/apache/commons/lang3/time/FastDateParser_TimeZoneStrategyTest.java +++ b/src/test/java/org/apache/commons/lang3/time/FastDateParser_TimeZoneStrategyTest.java @@ -16,9 +16,7 @@ */ package org.apache.commons.lang3.time; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.MethodSource; +import static org.junit.jupiter.api.Assertions.assertNotEquals; import java.text.DateFormatSymbols; import java.text.ParseException; @@ -26,7 +24,9 @@ import java.util.Locale; import java.util.TimeZone; -import static org.junit.jupiter.api.Assertions.assertNotEquals; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; class FastDateParser_TimeZoneStrategyTest { diff --git a/src/test/java/org/apache/commons/lang3/time/FastTimeZoneTest.java b/src/test/java/org/apache/commons/lang3/time/FastTimeZoneTest.java index 70ca71af936..70e8d0d4cfd 100644 --- a/src/test/java/org/apache/commons/lang3/time/FastTimeZoneTest.java +++ b/src/test/java/org/apache/commons/lang3/time/FastTimeZoneTest.java @@ -16,12 +16,12 @@ */ package org.apache.commons.lang3.time; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.TimeZone; +import org.junit.jupiter.api.Test; + /** * Tests for FastTimeZone */ diff --git a/src/test/java/org/apache/commons/lang3/time/StopWatchTest.java b/src/test/java/org/apache/commons/lang3/time/StopWatchTest.java index 61e9792fd1b..65e6dde38ba 100644 --- a/src/test/java/org/apache/commons/lang3/time/StopWatchTest.java +++ b/src/test/java/org/apache/commons/lang3/time/StopWatchTest.java @@ -17,8 +17,8 @@ package org.apache.commons.lang3.time; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; diff --git a/src/test/java/org/apache/commons/lang3/tuple/ImmutableTripleTest.java b/src/test/java/org/apache/commons/lang3/tuple/ImmutableTripleTest.java index d6d8a64a1df..2be49421448 100644 --- a/src/test/java/org/apache/commons/lang3/tuple/ImmutableTripleTest.java +++ b/src/test/java/org/apache/commons/lang3/tuple/ImmutableTripleTest.java @@ -29,8 +29,8 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; -import java.util.TreeMap; import java.util.Map.Entry; +import java.util.TreeMap; import org.junit.jupiter.api.Test; From 94d5208dd90c645290c3e184c4a8592c4cb3028a Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Wed, 24 Jun 2020 10:44:46 -0400 Subject: [PATCH 0197/3230] Fix boxing/unboxing. --- src/main/java/org/apache/commons/lang3/function/Failable.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/function/Failable.java b/src/main/java/org/apache/commons/lang3/function/Failable.java index 1017146b090..d33e9ee9130 100644 --- a/src/main/java/org/apache/commons/lang3/function/Failable.java +++ b/src/main/java/org/apache/commons/lang3/function/Failable.java @@ -463,7 +463,7 @@ public static FailableStream stream(final Stream stream) { */ public static boolean test(final FailableBiPredicate predicate, final O1 object1, final O2 object2) { - return get(() -> predicate.test(object1, object2)); + return getAsBoolean(() -> predicate.test(object1, object2)); } /** @@ -476,7 +476,7 @@ public static boolean test(final FailableBiPredica * @return the boolean value returned by the predicate */ public static boolean test(final FailablePredicate predicate, final O object) { - return get(() -> predicate.test(object)); + return getAsBoolean(() -> predicate.test(object)); } /** From c10c62ed737b57abaec72acca4c830492e2595c7 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Wed, 24 Jun 2020 10:47:00 -0400 Subject: [PATCH 0198/3230] Fix boxing/unboxing. --- .../org/apache/commons/lang3/Functions.java | 22 ++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/Functions.java b/src/main/java/org/apache/commons/lang3/Functions.java index 7186caa521c..ff4134fc1f4 100644 --- a/src/main/java/org/apache/commons/lang3/Functions.java +++ b/src/main/java/org/apache/commons/lang3/Functions.java @@ -32,6 +32,7 @@ import java.util.stream.Stream; import org.apache.commons.lang3.Streams.FailableStream; +import org.apache.commons.lang3.function.FailableBooleanSupplier; /** * This class provides utility functions, and classes for working with the {@code java.util.function} package, or more @@ -93,7 +94,7 @@ public interface FailableBiConsumer { */ void accept(O1 object1, O2 object2) throws T; } - + /** * A functional interface like {@link BiFunction} that declares a {@code Throwable}. * @@ -477,6 +478,21 @@ public static O get(final FailableSupplier suppli } } + /** + * Invokes a boolean supplier, and returns the result. + * + * @param supplier The boolean supplier to invoke. + * @param The type of checked exception, which the supplier can throw. + * @return The boolean, which has been created by the supplier + */ + private static boolean getAsBoolean(final FailableBooleanSupplier supplier) { + try { + return supplier.getAsBoolean(); + } catch (final Throwable t) { + throw rethrow(t); + } + } + /** *

      * Rethrows a {@link Throwable} as an unchecked exception. If the argument is already unchecked, namely a @@ -574,7 +590,7 @@ public static FailableStream stream(final Stream stream) { */ public static boolean test(final FailableBiPredicate predicate, final O1 object1, final O2 object2) { - return get(() -> predicate.test(object1, object2)); + return getAsBoolean(() -> predicate.test(object1, object2)); } /** @@ -587,7 +603,7 @@ public static boolean test(final FailableBiPredica * @return the boolean value returned by the predicate */ public static boolean test(final FailablePredicate predicate, final O object) { - return get(() -> predicate.test(object)); + return getAsBoolean(() -> predicate.test(object)); } /** From 05803b0d5826891c03927b2b1a49de8a77799f72 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Wed, 24 Jun 2020 10:53:55 -0400 Subject: [PATCH 0199/3230] Add JavaVersion enum constants for Java 16. Tested with: openjdk version "16-ea" 2021-03-16 OpenJDK Runtime Environment (build 16-ea+2-35) OpenJDK 64-Bit Server VM (build 16-ea+2-35, mixed mode, sharing) --- src/changes/changes.xml | 1 + src/main/java/org/apache/commons/lang3/JavaVersion.java | 9 +++++++++ .../java/org/apache/commons/lang3/JavaVersionTest.java | 4 +++- 3 files changed, 13 insertions(+), 1 deletion(-) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 7152b35fbdc..04c5729f90f 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -76,6 +76,7 @@ The type attribute can be add,update,fix,remove. Simplify if as some conditions are covered by others #543. StringUtils.replaceEachRepeatedly gives IllegalStateException #505. Add JavaVersion enum constants for Java 14 and 15. #553. + Add JavaVersion enum constants for Java 16. Use Java 8 lambdas and Map operations. Change removeLastFieldSeparator to use endsWith #550. Change a Pattern to a static final field, for not letting it compile each time the function invoked. #542. diff --git a/src/main/java/org/apache/commons/lang3/JavaVersion.java b/src/main/java/org/apache/commons/lang3/JavaVersion.java index d275607b9a4..b882e8ce72f 100644 --- a/src/main/java/org/apache/commons/lang3/JavaVersion.java +++ b/src/main/java/org/apache/commons/lang3/JavaVersion.java @@ -129,6 +129,13 @@ public enum JavaVersion { */ JAVA_15(15.0f, "15"), + /** + * Java 16 + * + * @since 3.11 + */ + JAVA_16(16.0f, "16"), + /** * The most recent java version. Mainly introduced to avoid to break when a new version of Java is used. */ @@ -242,6 +249,8 @@ static JavaVersion get(final String nom) { return JAVA_14; } else if ("15".equals(nom)) { return JAVA_15; + } else if ("16".equals(nom)) { + return JAVA_16; } final float v = toFloatVersion(nom); if ((v - 1.) < 1.) { // then we need to check decimals > .9 diff --git a/src/test/java/org/apache/commons/lang3/JavaVersionTest.java b/src/test/java/org/apache/commons/lang3/JavaVersionTest.java index fbfd62dc998..4db4bfde850 100644 --- a/src/test/java/org/apache/commons/lang3/JavaVersionTest.java +++ b/src/test/java/org/apache/commons/lang3/JavaVersionTest.java @@ -25,6 +25,7 @@ import static org.apache.commons.lang3.JavaVersion.JAVA_13; import static org.apache.commons.lang3.JavaVersion.JAVA_14; import static org.apache.commons.lang3.JavaVersion.JAVA_15; +import static org.apache.commons.lang3.JavaVersion.JAVA_16; import static org.apache.commons.lang3.JavaVersion.JAVA_1_1; import static org.apache.commons.lang3.JavaVersion.JAVA_1_2; import static org.apache.commons.lang3.JavaVersion.JAVA_1_3; @@ -66,10 +67,11 @@ public void testGetJavaVersion() { assertEquals(JAVA_13, get("13"), "13 failed"); assertEquals(JAVA_14, get("14"), "14 failed"); assertEquals(JAVA_15, get("15"), "15 failed"); + assertEquals(JAVA_16, get("16"), "16 failed"); assertEquals(JAVA_RECENT, get("1.10"), "1.10 failed"); // assertNull("2.10 unexpectedly worked", get("2.10")); assertEquals(get("1.5"), getJavaVersion("1.5"), "Wrapper method failed"); - assertEquals(JAVA_RECENT, get("16"), "Unhandled"); // LANG-1384 + assertEquals(JAVA_RECENT, get("17"), "Unhandled"); // LANG-1384 } @Test From c5c839ff821e04a6914fdfcd227fb0edf9d2f164 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Wed, 24 Jun 2020 10:54:37 -0400 Subject: [PATCH 0200/3230] Whitespace. --- src/main/java/org/apache/commons/lang3/Functions.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/apache/commons/lang3/Functions.java b/src/main/java/org/apache/commons/lang3/Functions.java index ff4134fc1f4..8eeb1374cdf 100644 --- a/src/main/java/org/apache/commons/lang3/Functions.java +++ b/src/main/java/org/apache/commons/lang3/Functions.java @@ -94,7 +94,7 @@ public interface FailableBiConsumer { */ void accept(O1 object1, O2 object2) throws T; } - + /** * A functional interface like {@link BiFunction} that declares a {@code Throwable}. * From cae8364d9e44065272eea22f5a64e78443b8f641 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Wed, 24 Jun 2020 10:55:15 -0400 Subject: [PATCH 0201/3230] Use final. --- .../commons/lang3/CharSequenceUtils.java | 4 +- .../org/apache/commons/lang3/StringUtils.java | 6 +-- .../commons/lang3/builder/ToStringStyle.java | 4 +- .../apache/commons/lang3/FunctionsTest.java | 46 +++++++++---------- .../apache/commons/lang3/StringUtilsTest.java | 26 +++++------ .../lang3/builder/JsonToStringStyleTest.java | 30 ++++++------ .../commons/lang3/concurrent/LocksTest.java | 6 +-- 7 files changed, 61 insertions(+), 61 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/CharSequenceUtils.java b/src/main/java/org/apache/commons/lang3/CharSequenceUtils.java index fdb91220bb2..c6af33a068c 100644 --- a/src/main/java/org/apache/commons/lang3/CharSequenceUtils.java +++ b/src/main/java/org/apache/commons/lang3/CharSequenceUtils.java @@ -295,8 +295,8 @@ static boolean regionMatches(final CharSequence cs, final boolean ignoreCase, fi } // The real same check as in String.regionMatches(): - char u1 = Character.toUpperCase(c1); - char u2 = Character.toUpperCase(c2); + final char u1 = Character.toUpperCase(c1); + final char u2 = Character.toUpperCase(c2); if (u1 != u2 && Character.toLowerCase(u1) != Character.toLowerCase(u2)) { return false; } diff --git a/src/main/java/org/apache/commons/lang3/StringUtils.java b/src/main/java/org/apache/commons/lang3/StringUtils.java index 1ae2e38e4a4..5b872301622 100644 --- a/src/main/java/org/apache/commons/lang3/StringUtils.java +++ b/src/main/java/org/apache/commons/lang3/StringUtils.java @@ -6693,8 +6693,8 @@ private static String replaceEach( // if recursing, this shouldn't be less than 0 if (timeToLive < 0) { - Set searchSet = new HashSet<>(Arrays.asList(searchList)); - Set replacementSet = new HashSet<>(Arrays.asList(replacementList)); + final Set searchSet = new HashSet<>(Arrays.asList(searchList)); + final Set replacementSet = new HashSet<>(Arrays.asList(replacementList)); searchSet.retainAll(replacementSet); if (searchSet.size() > 0) { throw new IllegalStateException("Aborting to protect against StackOverflowError - " + @@ -8277,7 +8277,7 @@ public static String[] stripAll(final String... strs) { * @return the stripped Strings, {@code null} if null array input */ public static String[] stripAll(final String[] strs, final String stripChars) { - int strsLen = ArrayUtils.getLength(strs); + final int strsLen = ArrayUtils.getLength(strs); if (strsLen == 0) { return strs; } diff --git a/src/main/java/org/apache/commons/lang3/builder/ToStringStyle.java b/src/main/java/org/apache/commons/lang3/builder/ToStringStyle.java index 4856c32c37b..56fda5556ab 100644 --- a/src/main/java/org/apache/commons/lang3/builder/ToStringStyle.java +++ b/src/main/java/org/apache/commons/lang3/builder/ToStringStyle.java @@ -627,7 +627,7 @@ protected void appendDetail(final StringBuffer buffer, final String fieldName, f if (coll != null && !coll.isEmpty()) { buffer.append(arrayStart); int i = 0; - for (Object item : coll) { + for (final Object item : coll) { appendDetail(buffer, fieldName, i++, item); } buffer.append(arrayEnd); @@ -944,7 +944,7 @@ protected void appendDetail(final StringBuffer buffer, final String fieldName, f * @param item the array item to add * @since 3.11 */ - protected void appendDetail(final StringBuffer buffer, final String fieldName, int i, final Object item) { + protected void appendDetail(final StringBuffer buffer, final String fieldName, final int i, final Object item) { if (i > 0) { buffer.append(arraySeparator); } diff --git a/src/test/java/org/apache/commons/lang3/FunctionsTest.java b/src/test/java/org/apache/commons/lang3/FunctionsTest.java index 798591294bf..cd0607de77b 100644 --- a/src/test/java/org/apache/commons/lang3/FunctionsTest.java +++ b/src/test/java/org/apache/commons/lang3/FunctionsTest.java @@ -76,17 +76,17 @@ static boolean failingBool() throws SomeException { return true; } - static boolean testDouble(double value) throws SomeException { + static boolean testDouble(final double value) throws SomeException { throwOnOdd(); return true; } - static boolean testInt(int value) throws SomeException { + static boolean testInt(final int value) throws SomeException { throwOnOdd(); return true; } - static boolean testLong(long value) throws SomeException { + static boolean testLong(final long value) throws SomeException { throwOnOdd(); return true; } @@ -159,7 +159,7 @@ public void test() throws Throwable { test(throwable); } - public Object test(Object input1, Object input2) throws Throwable { + public Object test(final Object input1, final Object input2) throws Throwable { test(throwable); return acceptedObject; } @@ -225,41 +225,41 @@ public long testAsLongPrimitive(final Throwable throwable) throws Throwable { return 0; } - public void testDouble(double i) throws Throwable { + public void testDouble(final double i) throws Throwable { test(throwable); acceptedPrimitiveObject1 = (P) ((Double) i); } - public double testDoubleDouble(double i, double j) throws Throwable { + public double testDoubleDouble(final double i, final double j) throws Throwable { test(throwable); acceptedPrimitiveObject1 = (P) ((Double) i); acceptedPrimitiveObject2 = (P) ((Double) j); return 3d; } - public void testInt(int i) throws Throwable { + public void testInt(final int i) throws Throwable { test(throwable); acceptedPrimitiveObject1 = (P) ((Integer) i); } - public void testLong(long i) throws Throwable { + public void testLong(final long i) throws Throwable { test(throwable); acceptedPrimitiveObject1 = (P) ((Long) i); } - public void testObjDouble(T object, double i) throws Throwable { + public void testObjDouble(final T object, final double i) throws Throwable { test(throwable); acceptedObject = object; acceptedPrimitiveObject1 = (P) ((Double) i); } - public void testObjInt(T object, int i) throws Throwable { + public void testObjInt(final T object, final int i) throws Throwable { test(throwable); acceptedObject = object; acceptedPrimitiveObject1 = (P) ((Integer) i); } - public void testObjLong(T object, long i) throws Throwable { + public void testObjLong(final T object, final long i) throws Throwable { test(throwable); acceptedObject = object; acceptedPrimitiveObject1 = (P) ((Long) i); @@ -800,7 +800,7 @@ public void testThrows_FailableBiConsumer_Object_Throwable() { new Functions.FailableBiConsumer() { @Override - public void accept(Object object1, Object object2) throws Throwable { + public void accept(final Object object1, final Object object2) throws Throwable { throw new IOException("test"); } }; @@ -815,7 +815,7 @@ public void testThrows_FailableBiConsumer_String_IOException() { new Functions.FailableBiConsumer() { @Override - public void accept(String object1, String object2) throws IOException { + public void accept(final String object1, final String object2) throws IOException { throw new IOException("test"); } @@ -831,7 +831,7 @@ public void testThrows_FailableBiFunction_Object_Throwable() { new Functions.FailableBiFunction() { @Override - public Object apply(Object input1, Object input2) throws Throwable { + public Object apply(final Object input1, final Object input2) throws Throwable { throw new IOException("test"); } }; @@ -846,7 +846,7 @@ public void testThrows_FailableBiFunction_String_IOException() { new Functions.FailableBiFunction() { @Override - public String apply(String input1, String input2) throws IOException { + public String apply(final String input1, final String input2) throws IOException { throw new IOException("test"); } }; @@ -861,7 +861,7 @@ public void testThrows_FailableBiPredicate_Object_Throwable() { new Functions.FailableBiPredicate() { @Override - public boolean test(Object object1, Object object2) throws Throwable { + public boolean test(final Object object1, final Object object2) throws Throwable { throw new IOException("test"); } }; @@ -876,7 +876,7 @@ public void testThrows_FailableBiPredicate_String_IOException() { new Functions.FailableBiPredicate() { @Override - public boolean test(String object1, String object2) throws IOException { + public boolean test(final String object1, final String object2) throws IOException { throw new IOException("test"); } }; @@ -921,7 +921,7 @@ public void testThrows_FailableConsumer_Object_Throwable() { new Functions.FailableConsumer() { @Override - public void accept(Object object) throws Throwable { + public void accept(final Object object) throws Throwable { throw new IOException("test"); } @@ -937,7 +937,7 @@ public void testThrows_FailableConsumer_String_IOException() { new Functions.FailableConsumer() { @Override - public void accept(String object) throws IOException { + public void accept(final String object) throws IOException { throw new IOException("test"); } @@ -953,7 +953,7 @@ public void testThrows_FailableFunction_Object_Throwable() { new Functions.FailableFunction() { @Override - public Object apply(Object input) throws Throwable { + public Object apply(final Object input) throws Throwable { throw new IOException("test"); } }; @@ -968,7 +968,7 @@ public void testThrows_FailableFunction_String_IOException() { new Functions.FailableFunction() { @Override - public String apply(String input) throws IOException { + public String apply(final String input) throws IOException { throw new IOException("test"); } }; @@ -983,7 +983,7 @@ public void testThrows_FailablePredicate_Object_Throwable() { new Functions.FailablePredicate() { @Override - public boolean test(Object object) throws Throwable { + public boolean test(final Object object) throws Throwable { throw new IOException("test"); } }; @@ -998,7 +998,7 @@ public void testThrows_FailablePredicate_String_IOException() { new Functions.FailablePredicate() { @Override - public boolean test(String object) throws IOException { + public boolean test(final String object) throws IOException { throw new IOException("test"); } }; diff --git a/src/test/java/org/apache/commons/lang3/StringUtilsTest.java b/src/test/java/org/apache/commons/lang3/StringUtilsTest.java index 622cad56678..7c657d0f861 100644 --- a/src/test/java/org/apache/commons/lang3/StringUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/StringUtilsTest.java @@ -60,11 +60,11 @@ public class StringUtilsTest { static final String NON_TRIMMABLE; static { - StringBuilder ws = new StringBuilder(); - StringBuilder nws = new StringBuilder(); + final StringBuilder ws = new StringBuilder(); + final StringBuilder nws = new StringBuilder(); final String hs = String.valueOf(((char) 160)); - StringBuilder tr = new StringBuilder(); - StringBuilder ntr = new StringBuilder(); + final StringBuilder tr = new StringBuilder(); + final StringBuilder ntr = new StringBuilder(); for (int i = 0; i < Character.MAX_VALUE; i++) { if (Character.isWhitespace((char) i)) { ws.append(String.valueOf((char) i)); @@ -3310,25 +3310,25 @@ public void testToRootUpperCase() { @Test public void testGeorgianSample() { - char[] arrayI = new char[]{ + final char[] arrayI = new char[]{ //Latin Small Letter dotless I (char) 0x0131, //Greek Capital Letter Theta (char) 0x03F4 }; - char[] arrayJ = new char[]{ + final char[] arrayJ = new char[]{ //Latin Capital Letter I with dot above (char) 0x0130, //Greek Theta Symbol (char) 0x03D1 }; - for (char i : arrayI) { - for (char j : arrayJ) { - String si = String.valueOf(i); - String sj = String.valueOf(j); - boolean res1 = si.equalsIgnoreCase(sj); - CharSequence ci = new StringBuilder(si); - CharSequence cj = new StringBuilder(sj); + for (final char i : arrayI) { + for (final char j : arrayJ) { + final String si = String.valueOf(i); + final String sj = String.valueOf(j); + final boolean res1 = si.equalsIgnoreCase(sj); + final CharSequence ci = new StringBuilder(si); + final CharSequence cj = new StringBuilder(sj); boolean res2 = StringUtils.startsWithIgnoreCase(ci, cj); assertEquals(res1, res2, "si : " + si + " sj : " + sj); res2 = StringUtils.endsWithIgnoreCase(ci, cj); diff --git a/src/test/java/org/apache/commons/lang3/builder/JsonToStringStyleTest.java b/src/test/java/org/apache/commons/lang3/builder/JsonToStringStyleTest.java index 623ddb90aba..23895118a8f 100644 --- a/src/test/java/org/apache/commons/lang3/builder/JsonToStringStyleTest.java +++ b/src/test/java/org/apache/commons/lang3/builder/JsonToStringStyleTest.java @@ -186,8 +186,8 @@ public void testObject() { @Test public void testList() { - Student student = new Student(); - ArrayList objects = new ArrayList<>(); + final Student student = new Student(); + final ArrayList objects = new ArrayList<>(); objects.add(Hobby.BOOK); objects.add(Hobby.SPORT); @@ -204,8 +204,8 @@ public void testList() { @Test public void testArrayEnum() { - Teacher teacher = new Teacher(); - Hobby[] hobbies = new Hobby[3]; + final Teacher teacher = new Teacher(); + final Hobby[] hobbies = new Hobby[3]; hobbies[0] = Hobby.BOOK; hobbies[1] = Hobby.SPORT; hobbies[2] = Hobby.MUSIC; @@ -221,30 +221,30 @@ public void testArrayEnum() { @Test public void testCombineListAndEnum() { - Teacher teacher = new Teacher(); + final Teacher teacher = new Teacher(); - Hobby[] teacherHobbies = new Hobby[3]; + final Hobby[] teacherHobbies = new Hobby[3]; teacherHobbies[0] = Hobby.BOOK; teacherHobbies[1] = Hobby.SPORT; teacherHobbies[2] = Hobby.MUSIC; teacher.setHobbies(teacherHobbies); - Student john = new Student(); + final Student john = new Student(); john.setHobbies(Arrays.asList(Hobby.BOOK, Hobby.MUSIC)); - Student alice = new Student(); + final Student alice = new Student(); alice.setHobbies(new ArrayList<>()); - Student bob = new Student(); + final Student bob = new Student(); bob.setHobbies(Collections.singletonList(Hobby.BOOK)); - ArrayList students = new ArrayList<>(); + final ArrayList students = new ArrayList<>(); students.add(john); students.add(alice); students.add(bob); - AcademyClass academyClass = new AcademyClass(); + final AcademyClass academyClass = new AcademyClass(); academyClass.setStudents(students); academyClass.setTeacher(teacher); @@ -564,7 +564,7 @@ public List getHobbies() { return hobbies; } - public void setHobbies(List hobbies) { + public void setHobbies(final List hobbies) { this.hobbies = hobbies; } @@ -581,7 +581,7 @@ public Hobby[] getHobbies() { return hobbies; } - public void setHobbies(Hobby[] hobbies) { + public void setHobbies(final Hobby[] hobbies) { this.hobbies = hobbies; } @@ -595,11 +595,11 @@ static class AcademyClass { Teacher teacher; List students; - public void setTeacher(Teacher teacher) { + public void setTeacher(final Teacher teacher) { this.teacher = teacher; } - public void setStudents(List students) { + public void setStudents(final List students) { this.students = students; } diff --git a/src/test/java/org/apache/commons/lang3/concurrent/LocksTest.java b/src/test/java/org/apache/commons/lang3/concurrent/LocksTest.java index 461bb539ea1..2d577ecdb77 100644 --- a/src/test/java/org/apache/commons/lang3/concurrent/LocksTest.java +++ b/src/test/java/org/apache/commons/lang3/concurrent/LocksTest.java @@ -44,7 +44,7 @@ public void testWriteLock() throws Exception { runTest(DELAY, true, l -> assertTrue(l >= NUMBER_OF_THREADS*DELAY)); } - private void runTest(long delay, boolean exclusiveLock, LongConsumer runTimeCheck) throws InterruptedException { + private void runTest(final long delay, final boolean exclusiveLock, final LongConsumer runTimeCheck) throws InterruptedException { final boolean[] booleanValues = new boolean[10]; final Lock lock = Locks.lock(booleanValues); final boolean[] runningValues = new boolean[10]; @@ -78,13 +78,13 @@ private void runTest(long delay, boolean exclusiveLock, LongConsumer runTimeChec runTimeCheck.accept(endTime-startTime); } - protected void modify(boolean[] booleanArray, int offset, boolean value) { + protected void modify(final boolean[] booleanArray, final int offset, final boolean value) { synchronized(booleanArray) { booleanArray[offset] = value; } } - protected boolean someValueIsTrue(boolean[] booleanArray) { + protected boolean someValueIsTrue(final boolean[] booleanArray) { synchronized(booleanArray) { for (int i = 0; i < booleanArray.length; i++) { if (booleanArray[i]) { From 43fe903cadef99ef243afa8cf6e20522cff96831 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Wed, 24 Jun 2020 12:50:17 -0400 Subject: [PATCH 0202/3230] com.github.spotbugs:spotbugs 4.0.5 -> 4.0.6. commons.surefire.version 3.0.0-M4 -> 3.0.0-M5. --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index d340fe6b86a..c05b502cf23 100644 --- a/pom.xml +++ b/pom.xml @@ -612,7 +612,7 @@ benchmarks 0.8.5 - 3.0.0-M4 + 3.0.0-M5 3.2.0 @@ -764,7 +764,7 @@ com.github.spotbugs spotbugs - 4.0.5 + 4.0.6 From 1861ab9388ebd997799720e5913b2c8553c6514c Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Wed, 24 Jun 2020 12:51:04 -0400 Subject: [PATCH 0203/3230] Use the same generic parameter names as the JRE. --- src/changes/changes.xml | 11 ++++++----- .../commons/lang3/function/FailableBiConsumer.java | 13 +++++++------ .../commons/lang3/function/FailableBiFunction.java | 12 ++++++------ .../commons/lang3/function/FailableBiPredicate.java | 12 ++++++------ .../lang3/function/FailableBooleanSupplier.java | 8 ++++---- .../commons/lang3/function/FailableCallable.java | 8 ++++---- .../commons/lang3/function/FailableConsumer.java | 8 ++++---- .../function/FailableDoubleBinaryOperator.java | 8 ++++---- .../lang3/function/FailableDoubleConsumer.java | 8 ++++---- .../lang3/function/FailableDoubleFunction.java | 8 ++++---- .../lang3/function/FailableDoublePredicate.java | 8 ++++---- .../lang3/function/FailableDoubleSupplier.java | 8 ++++---- .../lang3/function/FailableDoubleToIntFunction.java | 8 ++++---- .../function/FailableDoubleToLongFunction.java | 8 ++++---- .../commons/lang3/function/FailableFunction.java | 10 +++++----- .../lang3/function/FailableIntBinaryOperator.java | 8 ++++---- .../commons/lang3/function/FailableIntConsumer.java | 8 ++++---- .../commons/lang3/function/FailableIntFunction.java | 8 ++++---- .../lang3/function/FailableIntPredicate.java | 8 ++++---- .../commons/lang3/function/FailableIntSupplier.java | 8 ++++---- .../lang3/function/FailableIntToDoubleFunction.java | 8 ++++---- .../lang3/function/FailableIntToLongFunction.java | 8 ++++---- .../lang3/function/FailableLongBinaryOperator.java | 8 ++++---- .../lang3/function/FailableLongConsumer.java | 8 ++++---- .../lang3/function/FailableLongFunction.java | 8 ++++---- .../lang3/function/FailableLongPredicate.java | 8 ++++---- .../lang3/function/FailableLongSupplier.java | 8 ++++---- .../function/FailableLongToDoubleFunction.java | 8 ++++---- .../lang3/function/FailableLongToIntFunction.java | 8 ++++---- .../lang3/function/FailableObjDoubleConsumer.java | 10 +++++----- .../lang3/function/FailableObjIntConsumer.java | 10 +++++----- .../lang3/function/FailableObjLongConsumer.java | 10 +++++----- .../commons/lang3/function/FailablePredicate.java | 10 +++++----- .../commons/lang3/function/FailableRunnable.java | 8 ++++---- .../commons/lang3/function/FailableSupplier.java | 8 ++++---- .../lang3/function/FailableToDoubleBiFunction.java | 12 ++++++------ .../lang3/function/FailableToDoubleFunction.java | 10 +++++----- .../lang3/function/FailableToIntBiFunction.java | 12 ++++++------ .../lang3/function/FailableToIntFunction.java | 10 +++++----- .../lang3/function/FailableToLongBiFunction.java | 12 ++++++------ .../lang3/function/FailableToLongFunction.java | 10 +++++----- 41 files changed, 187 insertions(+), 185 deletions(-) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 04c5729f90f..9c8259b45bc 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -48,11 +48,6 @@ The type attribute can be add,update,fix,remove. remove encoding and docEncoding and use inherited values from commons-parent Fix Javadoc for StringUtils.appendIfMissingIgnoreCase() #507. - org.apache.commons:commons-parent 50 -> 51. - org.junit-pioneer:junit-pioneer 0.5.4 -> 0.6.0. - org.junit.jupiter:junit-jupiter 5.6.0 -> 5.6.1. - com.github.spotbugs:spotbugs 4.0.0 -> 4.0.5. - com.puppycrawl.tools:checkstyle 8.29 -> 8.33. Simplify null checks in Pair.hashCode() using Objects.hashCode(). #517. Simplify null checks in Triple.hashCode() using Objects.hashCode(). #516. Simplify some if statements in StringUtils. #521. @@ -84,6 +79,12 @@ The type attribute can be add,update,fix,remove. Add ObjectUtils.toString(Object, Supplier<String>). Fixed Javadocs for setTestRecursive() #556. ToStringBuilder.reflectionToString - Wrong JSON format when object has a List of Enum. + org.apache.commons:commons-parent 50 -> 51. + org.junit-pioneer:junit-pioneer 0.5.4 -> 0.6.0. + org.junit.jupiter:junit-jupiter 5.6.0 -> 5.6.1. + com.github.spotbugs:spotbugs 4.0.0 -> 4.0.6. + com.puppycrawl.tools:checkstyle 8.29 -> 8.33. + commons.surefire.version 3.0.0-M4 -> 3.0.0-M5.. diff --git a/src/main/java/org/apache/commons/lang3/function/FailableBiConsumer.java b/src/main/java/org/apache/commons/lang3/function/FailableBiConsumer.java index cd9bedebdc1..342f5ece69b 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableBiConsumer.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableBiConsumer.java @@ -22,20 +22,21 @@ /** * A functional interface like {@link BiConsumer} that declares a {@code Throwable}. * - * @param Consumed type 1. - * @param Consumed type 2. - * @param Thrown exception. + * @param Consumed type 1. + * @param Consumed type 2. + * @param Thrown exception. * @since 3.11 */ @FunctionalInterface -public interface FailableBiConsumer { +public interface FailableBiConsumer { /** * Accepts the consumer. * * @param object1 the first parameter for the consumable to accept * @param object2 the second parameter for the consumable to accept - * @throws T Thrown when the consumer fails. + * @throws E Thrown when the consumer fails. */ - void accept(O1 object1, O2 object2) throws T; + void accept(T object1, U object2) throws E; + } diff --git a/src/main/java/org/apache/commons/lang3/function/FailableBiFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableBiFunction.java index ccb87c1ccf0..d112be8e981 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableBiFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableBiFunction.java @@ -22,14 +22,14 @@ /** * A functional interface like {@link BiFunction} that declares a {@code Throwable}. * - * @param Input type 1. - * @param Input type 2. + * @param Input type 1. + * @param Input type 2. * @param Return type. - * @param Thrown exception. + * @param Thrown exception. * @since 3.11 */ @FunctionalInterface -public interface FailableBiFunction { +public interface FailableBiFunction { /** * Applies this function. @@ -37,7 +37,7 @@ public interface FailableBiFunction { * @param input1 the first input for the function * @param input2 the second input for the function * @return the result of the function - * @throws T Thrown when the function fails. + * @throws E Thrown when the function fails. */ - R apply(O1 input1, O2 input2) throws T; + R apply(T input1, U input2) throws E; } diff --git a/src/main/java/org/apache/commons/lang3/function/FailableBiPredicate.java b/src/main/java/org/apache/commons/lang3/function/FailableBiPredicate.java index 725588056e1..22993572a77 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableBiPredicate.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableBiPredicate.java @@ -22,13 +22,13 @@ /** * A functional interface like {@link BiPredicate} that declares a {@code Throwable}. * - * @param Predicate type 1. - * @param Predicate type 2. - * @param Thrown exception. + * @param Predicate type 1. + * @param Predicate type 2. + * @param Thrown exception. * @since 3.11 */ @FunctionalInterface -public interface FailableBiPredicate { +public interface FailableBiPredicate { /** * Tests the predicate. @@ -36,7 +36,7 @@ public interface FailableBiPredicate { * @param object1 the first object to test the predicate on * @param object2 the second object to test the predicate on * @return the predicate's evaluation - * @throws T if the predicate fails + * @throws E if the predicate fails */ - boolean test(O1 object1, O2 object2) throws T; + boolean test(T object1, U object2) throws E; } diff --git a/src/main/java/org/apache/commons/lang3/function/FailableBooleanSupplier.java b/src/main/java/org/apache/commons/lang3/function/FailableBooleanSupplier.java index 25870de42a0..89facde0ea7 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableBooleanSupplier.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableBooleanSupplier.java @@ -22,17 +22,17 @@ /** * A functional interface like {@link BooleanSupplier} that declares a {@code Throwable}. * - * @param Thrown exception. + * @param Thrown exception. * @since 3.11 */ @FunctionalInterface -public interface FailableBooleanSupplier { +public interface FailableBooleanSupplier { /** * Supplies a boolean. * * @return a result - * @throws T if the supplier fails + * @throws E if the supplier fails */ - boolean getAsBoolean() throws T; + boolean getAsBoolean() throws E; } diff --git a/src/main/java/org/apache/commons/lang3/function/FailableCallable.java b/src/main/java/org/apache/commons/lang3/function/FailableCallable.java index 5d0d637d445..7e3a4d40cb7 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableCallable.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableCallable.java @@ -21,17 +21,17 @@ * A functional interface like {@link java.util.concurrent.Callable} that declares a {@code Throwable}. * * @param Return type. - * @param Thrown exception. + * @param Thrown exception. * @since 3.11 */ @FunctionalInterface -public interface FailableCallable { +public interface FailableCallable { /** * Calls the callable. * * @return The value returned from the callable - * @throws T if the callable fails + * @throws E if the callable fails */ - R call() throws T; + R call() throws E; } diff --git a/src/main/java/org/apache/commons/lang3/function/FailableConsumer.java b/src/main/java/org/apache/commons/lang3/function/FailableConsumer.java index f969dc167ac..acb73cc51ed 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableConsumer.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableConsumer.java @@ -23,17 +23,17 @@ * A functional interface like {@link Consumer} that declares a {@code Throwable}. * * @param Consumed type 1. - * @param Thrown exception. + * @param Thrown exception. * @since 3.11 */ @FunctionalInterface -public interface FailableConsumer { +public interface FailableConsumer { /** * Accepts the consumer. * * @param object the parameter for the consumable to accept - * @throws T Thrown when the consumer fails. + * @throws E Thrown when the consumer fails. */ - void accept(O object) throws T; + void accept(O object) throws E; } diff --git a/src/main/java/org/apache/commons/lang3/function/FailableDoubleBinaryOperator.java b/src/main/java/org/apache/commons/lang3/function/FailableDoubleBinaryOperator.java index 19680444b56..aefc8b791a6 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableDoubleBinaryOperator.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableDoubleBinaryOperator.java @@ -22,11 +22,11 @@ /** * A functional interface like {@link DoubleBinaryOperator} that declares a {@code Throwable}. * - * @param Thrown exception. + * @param Thrown exception. * @since 3.11 */ @FunctionalInterface -public interface FailableDoubleBinaryOperator { +public interface FailableDoubleBinaryOperator { /** * Applies this operator to the given operands. @@ -34,7 +34,7 @@ public interface FailableDoubleBinaryOperator { * @param left the first operand * @param right the second operand * @return the operator result - * @throws T if the operation fails + * @throws E if the operation fails */ - double applyAsDouble(double left, double right) throws T; + double applyAsDouble(double left, double right) throws E; } diff --git a/src/main/java/org/apache/commons/lang3/function/FailableDoubleConsumer.java b/src/main/java/org/apache/commons/lang3/function/FailableDoubleConsumer.java index 63bc40e8bb4..9b70da82a4c 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableDoubleConsumer.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableDoubleConsumer.java @@ -22,17 +22,17 @@ /** * A functional interface like {@link DoubleConsumer} that declares a {@code Throwable}. * - * @param Thrown exception. + * @param Thrown exception. * @since 3.11 */ @FunctionalInterface -public interface FailableDoubleConsumer { +public interface FailableDoubleConsumer { /** * Accepts the consumer. * * @param value the parameter for the consumable to accept - * @throws T Thrown when the consumer fails. + * @throws E Thrown when the consumer fails. */ - void accept(double value) throws T; + void accept(double value) throws E; } diff --git a/src/main/java/org/apache/commons/lang3/function/FailableDoubleFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableDoubleFunction.java index 48dec105eec..175a05e8530 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableDoubleFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableDoubleFunction.java @@ -23,18 +23,18 @@ * A functional interface like {@link DoubleFunction} that declares a {@code Throwable}. * * @param Return type. - * @param Thrown exception. + * @param Thrown exception. * @since 3.11 */ @FunctionalInterface -public interface FailableDoubleFunction { +public interface FailableDoubleFunction { /** * Applies this function. * * @param input the input for the function * @return the result of the function - * @throws T Thrown when the function fails. + * @throws E Thrown when the function fails. */ - R apply(double input) throws T; + R apply(double input) throws E; } diff --git a/src/main/java/org/apache/commons/lang3/function/FailableDoublePredicate.java b/src/main/java/org/apache/commons/lang3/function/FailableDoublePredicate.java index e4bf1630169..abdd2cb7ee8 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableDoublePredicate.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableDoublePredicate.java @@ -22,18 +22,18 @@ /** * A functional interface like {@link DoublePredicate} that declares a {@code Throwable}. * - * @param Thrown exception. + * @param Thrown exception. * @since 3.11 */ @FunctionalInterface -public interface FailableDoublePredicate { +public interface FailableDoublePredicate { /** * Tests the predicate. * * @param value the parameter for the predicate to accept. * @return {@code true} if the input argument matches the predicate, {@code false} otherwise. - * @throws T Thrown when the consumer fails. + * @throws E Thrown when the consumer fails. */ - boolean test(double value) throws T; + boolean test(double value) throws E; } diff --git a/src/main/java/org/apache/commons/lang3/function/FailableDoubleSupplier.java b/src/main/java/org/apache/commons/lang3/function/FailableDoubleSupplier.java index 47ac1290180..0024ef2c7b2 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableDoubleSupplier.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableDoubleSupplier.java @@ -22,17 +22,17 @@ /** * A functional interface like {@link DoubleSupplier} that declares a {@code Throwable}. * - * @param Thrown exception. + * @param Thrown exception. * @since 3.11 */ @FunctionalInterface -public interface FailableDoubleSupplier { +public interface FailableDoubleSupplier { /** * Supplies a double. * * @return a result - * @throws T if the supplier fails + * @throws E if the supplier fails */ - double getAsDouble() throws T; + double getAsDouble() throws E; } diff --git a/src/main/java/org/apache/commons/lang3/function/FailableDoubleToIntFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableDoubleToIntFunction.java index 403400f8a61..eb9e9405fca 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableDoubleToIntFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableDoubleToIntFunction.java @@ -22,18 +22,18 @@ /** * A functional interface like {@link DoubleToIntFunction} that declares a {@code Throwable}. * - * @param Thrown exception. + * @param Thrown exception. * @since 3.11 */ @FunctionalInterface -public interface FailableDoubleToIntFunction { +public interface FailableDoubleToIntFunction { /** * Applies this function to the given argument. * * @param value the function argument * @return the function result - * @throws T Thrown when the function fails. + * @throws E Thrown when the function fails. */ - int applyAsInt(double value) throws T; + int applyAsInt(double value) throws E; } diff --git a/src/main/java/org/apache/commons/lang3/function/FailableDoubleToLongFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableDoubleToLongFunction.java index 71cab0e651a..2a5b0ff1566 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableDoubleToLongFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableDoubleToLongFunction.java @@ -22,18 +22,18 @@ /** * A functional interface like {@link DoubleToLongFunction} that declares a {@code Throwable}. * - * @param Thrown exception. + * @param Thrown exception. * @since 3.11 */ @FunctionalInterface -public interface FailableDoubleToLongFunction { +public interface FailableDoubleToLongFunction { /** * Applies this function to the given argument. * * @param value the function argument * @return the function result - * @throws T if the operation fails + * @throws E if the operation fails */ - int applyAsLong(double value) throws T; + int applyAsLong(double value) throws E; } diff --git a/src/main/java/org/apache/commons/lang3/function/FailableFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableFunction.java index 3aad2108964..7de44379660 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableFunction.java @@ -22,20 +22,20 @@ /** * A functional interface like {@link Function} that declares a {@code Throwable}. * - * @param Input type 1. + * @param Input type 1. * @param Return type. - * @param Thrown exception. + * @param Thrown exception. * @since 3.11 */ @FunctionalInterface -public interface FailableFunction { +public interface FailableFunction { /** * Applies this function. * * @param input the input for the function * @return the result of the function - * @throws T Thrown when the function fails. + * @throws E Thrown when the function fails. */ - R apply(I input) throws T; + R apply(T input) throws E; } diff --git a/src/main/java/org/apache/commons/lang3/function/FailableIntBinaryOperator.java b/src/main/java/org/apache/commons/lang3/function/FailableIntBinaryOperator.java index 7e41e547b80..bc2263024e1 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableIntBinaryOperator.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableIntBinaryOperator.java @@ -22,11 +22,11 @@ /** * A functional interface like {@link IntBinaryOperator} that declares a {@code Throwable}. * - * @param Thrown exception. + * @param Thrown exception. * @since 3.11 */ @FunctionalInterface -public interface FailableIntBinaryOperator { +public interface FailableIntBinaryOperator { /** * Applies this operator to the given operands. @@ -34,7 +34,7 @@ public interface FailableIntBinaryOperator { * @param left the first operand * @param right the second operand * @return the operator result - * @throws T if the operation fails + * @throws E if the operation fails */ - int applyAsInt(int left, int right) throws T; + int applyAsInt(int left, int right) throws E; } diff --git a/src/main/java/org/apache/commons/lang3/function/FailableIntConsumer.java b/src/main/java/org/apache/commons/lang3/function/FailableIntConsumer.java index e7ce74c6248..506cb67e60f 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableIntConsumer.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableIntConsumer.java @@ -22,17 +22,17 @@ /** * A functional interface like {@link IntConsumer} that declares a {@code Throwable}. * - * @param Thrown exception. + * @param Thrown exception. * @since 3.11 */ @FunctionalInterface -public interface FailableIntConsumer { +public interface FailableIntConsumer { /** * Accepts the consumer. * * @param value the parameter for the consumable to accept - * @throws T Thrown when the consumer fails. + * @throws E Thrown when the consumer fails. */ - void accept(int value) throws T; + void accept(int value) throws E; } diff --git a/src/main/java/org/apache/commons/lang3/function/FailableIntFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableIntFunction.java index 907f0983810..7c2d0bcabf5 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableIntFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableIntFunction.java @@ -23,18 +23,18 @@ * A functional interface like {@link IntFunction} that declares a {@code Throwable}. * * @param Return type. - * @param Thrown exception. + * @param Thrown exception. * @since 3.11 */ @FunctionalInterface -public interface FailableIntFunction { +public interface FailableIntFunction { /** * Applies this function. * * @param input the input for the function * @return the result of the function - * @throws T Thrown when the function fails. + * @throws E Thrown when the function fails. */ - R apply(int input) throws T; + R apply(int input) throws E; } diff --git a/src/main/java/org/apache/commons/lang3/function/FailableIntPredicate.java b/src/main/java/org/apache/commons/lang3/function/FailableIntPredicate.java index 3687f9c77c7..837ba319c79 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableIntPredicate.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableIntPredicate.java @@ -22,18 +22,18 @@ /** * A functional interface like {@link IntPredicate} that declares a {@code Throwable}. * - * @param Thrown exception. + * @param Thrown exception. * @since 3.11 */ @FunctionalInterface -public interface FailableIntPredicate { +public interface FailableIntPredicate { /** * Tests the predicate. * * @param value the parameter for the predicate to accept. * @return {@code true} if the input argument matches the predicate, {@code false} otherwise. - * @throws T Thrown when the consumer fails. + * @throws E Thrown when the consumer fails. */ - boolean test(int value) throws T; + boolean test(int value) throws E; } diff --git a/src/main/java/org/apache/commons/lang3/function/FailableIntSupplier.java b/src/main/java/org/apache/commons/lang3/function/FailableIntSupplier.java index f1f72e47c00..d1478aa4ef5 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableIntSupplier.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableIntSupplier.java @@ -22,17 +22,17 @@ /** * A functional interface like {@link IntSupplier} that declares a {@code Throwable}. * - * @param Thrown exception. + * @param Thrown exception. * @since 3.11 */ @FunctionalInterface -public interface FailableIntSupplier { +public interface FailableIntSupplier { /** * Supplies an int. * * @return a result - * @throws T if the supplier fails + * @throws E if the supplier fails */ - int getAsInt() throws T; + int getAsInt() throws E; } diff --git a/src/main/java/org/apache/commons/lang3/function/FailableIntToDoubleFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableIntToDoubleFunction.java index 51a81ac056d..93afd897985 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableIntToDoubleFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableIntToDoubleFunction.java @@ -22,18 +22,18 @@ /** * A functional interface like {@link IntToDoubleFunction} that declares a {@code Throwable}. * - * @param Thrown exception. + * @param Thrown exception. * @since 3.11 */ @FunctionalInterface -public interface FailableIntToDoubleFunction { +public interface FailableIntToDoubleFunction { /** * Applies this function to the given argument. * * @param value the function argument * @return the function result - * @throws T Thrown when the function fails. + * @throws E Thrown when the function fails. */ - double applyAsDouble(int value) throws T; + double applyAsDouble(int value) throws E; } diff --git a/src/main/java/org/apache/commons/lang3/function/FailableIntToLongFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableIntToLongFunction.java index aef8c574164..de23ae738d0 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableIntToLongFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableIntToLongFunction.java @@ -22,18 +22,18 @@ /** * A functional interface like {@link IntToLongFunction} that declares a {@code Throwable}. * - * @param Thrown exception. + * @param Thrown exception. * @since 3.11 */ @FunctionalInterface -public interface FailableIntToLongFunction { +public interface FailableIntToLongFunction { /** * Applies this function to the given argument. * * @param value the function argument * @return the function result - * @throws T Thrown when the function fails. + * @throws E Thrown when the function fails. */ - long applyAsLong(int value) throws T; + long applyAsLong(int value) throws E; } diff --git a/src/main/java/org/apache/commons/lang3/function/FailableLongBinaryOperator.java b/src/main/java/org/apache/commons/lang3/function/FailableLongBinaryOperator.java index 6ddf2abd4e7..a7a3e080a1b 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableLongBinaryOperator.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableLongBinaryOperator.java @@ -22,11 +22,11 @@ /** * A functional interface like {@link LongBinaryOperator} that declares a {@code Throwable}. * - * @param Thrown exception. + * @param Thrown exception. * @since 3.11 */ @FunctionalInterface -public interface FailableLongBinaryOperator { +public interface FailableLongBinaryOperator { /** * Applies this operator to the given operands. @@ -34,7 +34,7 @@ public interface FailableLongBinaryOperator { * @param left the first operand * @param right the second operand * @return the operator result - * @throws T if the operation fails + * @throws E if the operation fails */ - long applyAsLong(long left, long right) throws T; + long applyAsLong(long left, long right) throws E; } diff --git a/src/main/java/org/apache/commons/lang3/function/FailableLongConsumer.java b/src/main/java/org/apache/commons/lang3/function/FailableLongConsumer.java index 465112ecb00..0565ff3b78d 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableLongConsumer.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableLongConsumer.java @@ -22,17 +22,17 @@ /** * A functional interface like {@link LongConsumer} that declares a {@code Throwable}. * - * @param Thrown exception. + * @param Thrown exception. * @since 3.11 */ @FunctionalInterface -public interface FailableLongConsumer { +public interface FailableLongConsumer { /** * Accepts the consumer. * * @param object the parameter for the consumable to accept - * @throws T Thrown when the consumer fails. + * @throws E Thrown when the consumer fails. */ - void accept(long object) throws T; + void accept(long object) throws E; } diff --git a/src/main/java/org/apache/commons/lang3/function/FailableLongFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableLongFunction.java index b36b2720c25..2811e741197 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableLongFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableLongFunction.java @@ -23,18 +23,18 @@ * A functional interface like {@link LongFunction} that declares a {@code Throwable}. * * @param Return type. - * @param Thrown exception. + * @param Thrown exception. * @since 3.11 */ @FunctionalInterface -public interface FailableLongFunction { +public interface FailableLongFunction { /** * Applies this function. * * @param input the input for the function * @return the result of the function - * @throws T Thrown when the function fails. + * @throws E Thrown when the function fails. */ - R apply(long input) throws T; + R apply(long input) throws E; } diff --git a/src/main/java/org/apache/commons/lang3/function/FailableLongPredicate.java b/src/main/java/org/apache/commons/lang3/function/FailableLongPredicate.java index 32550822dfa..3c756ca9770 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableLongPredicate.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableLongPredicate.java @@ -22,18 +22,18 @@ /** * A functional interface like {@link LongPredicate} that declares a {@code Throwable}. * - * @param Thrown exception. + * @param Thrown exception. * @since 3.11 */ @FunctionalInterface -public interface FailableLongPredicate { +public interface FailableLongPredicate { /** * Tests the predicate. * * @param value the parameter for the predicate to accept. * @return {@code true} if the input argument matches the predicate, {@code false} otherwise. - * @throws T Thrown when the consumer fails. + * @throws E Thrown when the consumer fails. */ - boolean test(long value) throws T; + boolean test(long value) throws E; } diff --git a/src/main/java/org/apache/commons/lang3/function/FailableLongSupplier.java b/src/main/java/org/apache/commons/lang3/function/FailableLongSupplier.java index 31d42a24e02..07d246dbbe5 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableLongSupplier.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableLongSupplier.java @@ -22,17 +22,17 @@ /** * A functional interface like {@link LongSupplier} that declares a {@code Throwable}. * - * @param Thrown exception. + * @param Thrown exception. * @since 3.11 */ @FunctionalInterface -public interface FailableLongSupplier { +public interface FailableLongSupplier { /** * Supplies a long. * * @return a result - * @throws T if the supplier fails + * @throws E if the supplier fails */ - long getAsLong() throws T; + long getAsLong() throws E; } diff --git a/src/main/java/org/apache/commons/lang3/function/FailableLongToDoubleFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableLongToDoubleFunction.java index f83d6a29c56..b272c9d0a2f 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableLongToDoubleFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableLongToDoubleFunction.java @@ -22,18 +22,18 @@ /** * A functional interface like {@link LongToDoubleFunction} that declares a {@code Throwable}. * - * @param Thrown exception. + * @param Thrown exception. * @since 3.11 */ @FunctionalInterface -public interface FailableLongToDoubleFunction { +public interface FailableLongToDoubleFunction { /** * Applies this function to the given argument. * * @param value the function argument * @return the function result - * @throws T Thrown when the function fails. + * @throws E Thrown when the function fails. */ - double applyAsDouble(long value) throws T; + double applyAsDouble(long value) throws E; } diff --git a/src/main/java/org/apache/commons/lang3/function/FailableLongToIntFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableLongToIntFunction.java index 825491e26b4..1066c3c2c6a 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableLongToIntFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableLongToIntFunction.java @@ -22,18 +22,18 @@ /** * A functional interface like {@link LongToIntFunction} that declares a {@code Throwable}. * - * @param Thrown exception. + * @param Thrown exception. * @since 3.11 */ @FunctionalInterface -public interface FailableLongToIntFunction { +public interface FailableLongToIntFunction { /** * Applies this function to the given argument. * * @param value the function argument * @return the function result - * @throws T Thrown when the function fails. + * @throws E Thrown when the function fails. */ - int applyAsInt(long value) throws T; + int applyAsInt(long value) throws E; } diff --git a/src/main/java/org/apache/commons/lang3/function/FailableObjDoubleConsumer.java b/src/main/java/org/apache/commons/lang3/function/FailableObjDoubleConsumer.java index 70555d5b0de..105c8746280 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableObjDoubleConsumer.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableObjDoubleConsumer.java @@ -22,19 +22,19 @@ /** * A functional interface like {@link ObjDoubleConsumer} that declares a {@code Throwable}. * - * @param the type of the object argument to the operation. - * @param Thrown exception. + * @param the type of the object argument to the operation. + * @param Thrown exception. * @since 3.11 */ @FunctionalInterface -public interface FailableObjDoubleConsumer { +public interface FailableObjDoubleConsumer { /** * Accepts the consumer. * * @param object the object parameter for the consumable to accept. * @param value the double parameter for the consumable to accept. - * @throws T Thrown when the consumer fails. + * @throws E Thrown when the consumer fails. */ - void accept(O object, double value) throws T; + void accept(T object, double value) throws E; } diff --git a/src/main/java/org/apache/commons/lang3/function/FailableObjIntConsumer.java b/src/main/java/org/apache/commons/lang3/function/FailableObjIntConsumer.java index 68954a4df35..71c89252a34 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableObjIntConsumer.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableObjIntConsumer.java @@ -22,19 +22,19 @@ /** * A functional interface like {@link ObjIntConsumer} that declares a {@code Throwable}. * - * @param the type of the object argument to the operation. - * @param Thrown exception. + * @param the type of the object argument to the operation. + * @param Thrown exception. * @since 3.11 */ @FunctionalInterface -public interface FailableObjIntConsumer { +public interface FailableObjIntConsumer { /** * Accepts the consumer. * * @param object the object parameter for the consumable to accept. * @param value the int parameter for the consumable to accept. - * @throws T Thrown when the consumer fails. + * @throws E Thrown when the consumer fails. */ - void accept(O object, int value) throws T; + void accept(T object, int value) throws E; } diff --git a/src/main/java/org/apache/commons/lang3/function/FailableObjLongConsumer.java b/src/main/java/org/apache/commons/lang3/function/FailableObjLongConsumer.java index a503f5ee25b..b84b4d7a3ac 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableObjLongConsumer.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableObjLongConsumer.java @@ -22,19 +22,19 @@ /** * A functional interface like {@link ObjLongConsumer} that declares a {@code Throwable}. * - * @param the type of the object argument to the operation. - * @param Thrown exception. + * @param the type of the object argument to the operation. + * @param Thrown exception. * @since 3.11 */ @FunctionalInterface -public interface FailableObjLongConsumer { +public interface FailableObjLongConsumer { /** * Accepts the consumer. * * @param object the object parameter for the consumable to accept. * @param value the long parameter for the consumable to accept. - * @throws T Thrown when the consumer fails. + * @throws E Thrown when the consumer fails. */ - void accept(O object, long value) throws T; + void accept(T object, long value) throws E; } diff --git a/src/main/java/org/apache/commons/lang3/function/FailablePredicate.java b/src/main/java/org/apache/commons/lang3/function/FailablePredicate.java index 6e461ce0a22..999107a1526 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailablePredicate.java +++ b/src/main/java/org/apache/commons/lang3/function/FailablePredicate.java @@ -22,19 +22,19 @@ /** * A functional interface like {@link Predicate} that declares a {@code Throwable}. * - * @param Predicate type 1. - * @param Thrown exception. + * @param Predicate type 1. + * @param Thrown exception. * @since 3.11 */ @FunctionalInterface -public interface FailablePredicate { +public interface FailablePredicate { /** * Tests the predicate. * * @param object the object to test the predicate on * @return the predicate's evaluation - * @throws T if the predicate fails + * @throws E if the predicate fails */ - boolean test(I object) throws T; + boolean test(T object) throws E; } diff --git a/src/main/java/org/apache/commons/lang3/function/FailableRunnable.java b/src/main/java/org/apache/commons/lang3/function/FailableRunnable.java index f783b338ce6..06bd72f5ea1 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableRunnable.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableRunnable.java @@ -20,16 +20,16 @@ /** * A functional interface like {@link Runnable} that declares a {@code Throwable}. * - * @param Thrown exception. + * @param Thrown exception. * @since 3.11 */ @FunctionalInterface -public interface FailableRunnable { +public interface FailableRunnable { /** * Runs the function. * - * @throws T Thrown when the function fails. + * @throws E Thrown when the function fails. */ - void run() throws T; + void run() throws E; } diff --git a/src/main/java/org/apache/commons/lang3/function/FailableSupplier.java b/src/main/java/org/apache/commons/lang3/function/FailableSupplier.java index a8ff7680131..1a109569533 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableSupplier.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableSupplier.java @@ -23,17 +23,17 @@ * A functional interface like {@link Supplier} that declares a {@code Throwable}. * * @param Return type. - * @param Thrown exception. + * @param Thrown exception. * @since 3.11 */ @FunctionalInterface -public interface FailableSupplier { +public interface FailableSupplier { /** * Supplies an object * * @return a result - * @throws T if the supplier fails + * @throws E if the supplier fails */ - R get() throws T; + R get() throws E; } diff --git a/src/main/java/org/apache/commons/lang3/function/FailableToDoubleBiFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableToDoubleBiFunction.java index 766383b9ad8..4ac14bd57e4 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableToDoubleBiFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableToDoubleBiFunction.java @@ -22,13 +22,13 @@ /** * A functional interface like {@link ToDoubleBiFunction} that declares a {@code Throwable}. * - * @param the type of the first argument to the function - * @param the type of the second argument to the function - * @param Thrown exception. + * @param the type of the first argument to the function + * @param the type of the second argument to the function + * @param Thrown exception. * @since 3.11 */ @FunctionalInterface -public interface FailableToDoubleBiFunction { +public interface FailableToDoubleBiFunction { /** * Applies this function to the given arguments. @@ -36,7 +36,7 @@ public interface FailableToDoubleBiFunction { * @param t the first function argument * @param u the second function argument * @return the function result - * @throws T Thrown when the function fails. + * @throws E Thrown when the function fails. */ - double applyAsDouble(O1 t, O2 u) throws T; + double applyAsDouble(T t, U u) throws E; } diff --git a/src/main/java/org/apache/commons/lang3/function/FailableToDoubleFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableToDoubleFunction.java index 9e3fedd8a05..43feba59010 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableToDoubleFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableToDoubleFunction.java @@ -22,19 +22,19 @@ /** * A functional interface like {@link ToDoubleFunction} that declares a {@code Throwable}. * - * @param the type of the first argument to the function - * @param Thrown exception. + * @param the type of the first argument to the function + * @param Thrown exception. * @since 3.11 */ @FunctionalInterface -public interface FailableToDoubleFunction { +public interface FailableToDoubleFunction { /** * Applies this function to the given arguments. * * @param t the first function argument * @return the function result - * @throws T Thrown when the function fails. + * @throws E Thrown when the function fails. */ - double applyAsDouble(I t) throws T; + double applyAsDouble(T t) throws E; } diff --git a/src/main/java/org/apache/commons/lang3/function/FailableToIntBiFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableToIntBiFunction.java index 7430a09c6e4..1b7c3e2df51 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableToIntBiFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableToIntBiFunction.java @@ -22,13 +22,13 @@ /** * A functional interface like {@link ToIntBiFunction} that declares a {@code Throwable}. * - * @param the type of the first argument to the function - * @param the type of the second argument to the function - * @param Thrown exception. + * @param the type of the first argument to the function + * @param the type of the second argument to the function + * @param Thrown exception. * @since 3.11 */ @FunctionalInterface -public interface FailableToIntBiFunction { +public interface FailableToIntBiFunction { /** * Applies this function to the given arguments. @@ -36,7 +36,7 @@ public interface FailableToIntBiFunction { * @param t the first function argument * @param u the second function argument * @return the function result - * @throws T Thrown when the function fails. + * @throws E Thrown when the function fails. */ - int applyAsInt(O1 t, O2 u) throws T; + int applyAsInt(T t, U u) throws E; } diff --git a/src/main/java/org/apache/commons/lang3/function/FailableToIntFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableToIntFunction.java index 0fc91ade3f4..1bba1c92225 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableToIntFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableToIntFunction.java @@ -22,19 +22,19 @@ /** * A functional interface like {@link ToIntFunction} that declares a {@code Throwable}. * - * @param the type of the first argument to the function - * @param Thrown exception. + * @param the type of the first argument to the function + * @param Thrown exception. * @since 3.11 */ @FunctionalInterface -public interface FailableToIntFunction { +public interface FailableToIntFunction { /** * Applies this function to the given arguments. * * @param t the first function argument * @return the function result - * @throws T Thrown when the function fails. + * @throws E Thrown when the function fails. */ - int applyAsInt(I t) throws T; + int applyAsInt(T t) throws E; } diff --git a/src/main/java/org/apache/commons/lang3/function/FailableToLongBiFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableToLongBiFunction.java index 6a34026a8a8..e49347ffc7a 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableToLongBiFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableToLongBiFunction.java @@ -22,13 +22,13 @@ /** * A functional interface like {@link ToLongBiFunction} that declares a {@code Throwable}. * - * @param the type of the first argument to the function - * @param the type of the second argument to the function - * @param Thrown exception. + * @param the type of the first argument to the function + * @param the type of the second argument to the function + * @param Thrown exception. * @since 3.11 */ @FunctionalInterface -public interface FailableToLongBiFunction { +public interface FailableToLongBiFunction { /** * Applies this function to the given arguments. @@ -36,7 +36,7 @@ public interface FailableToLongBiFunction { * @param t the first function argument * @param u the second function argument * @return the function result - * @throws T Thrown when the function fails. + * @throws E Thrown when the function fails. */ - long applyAsLong(O1 t, O2 u) throws T; + long applyAsLong(T t, U u) throws E; } diff --git a/src/main/java/org/apache/commons/lang3/function/FailableToLongFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableToLongFunction.java index f46bbcc1532..5b790af5b06 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableToLongFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableToLongFunction.java @@ -22,19 +22,19 @@ /** * A functional interface like {@link ToLongFunction} that declares a {@code Throwable}. * - * @param the type of the first argument to the function - * @param Thrown exception. + * @param the type of the first argument to the function + * @param Thrown exception. * @since 3.11 */ @FunctionalInterface -public interface FailableToLongFunction { +public interface FailableToLongFunction { /** * Applies this function to the given arguments. * * @param t the first function argument * @return the function result - * @throws T Thrown when the function fails. + * @throws E Thrown when the function fails. */ - long applyAsLong(I t) throws T; + long applyAsLong(T t) throws E; } From 4cf50486a3b50d632686039a1701e3584fe19377 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Wed, 24 Jun 2020 13:00:21 -0400 Subject: [PATCH 0204/3230] Use the same generic parameter names as the JRE. --- .../commons/lang3/function/Failable.java | 150 +++++++++--------- 1 file changed, 75 insertions(+), 75 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/function/Failable.java b/src/main/java/org/apache/commons/lang3/function/Failable.java index d33e9ee9130..7ff69bdb45d 100644 --- a/src/main/java/org/apache/commons/lang3/function/Failable.java +++ b/src/main/java/org/apache/commons/lang3/function/Failable.java @@ -76,12 +76,12 @@ public class Failable { * @param consumer the consumer to consume * @param object1 the first object to consume by {@code consumer} * @param object2 the second object to consume by {@code consumer} - * @param the type of the first argument the consumer accepts - * @param the type of the second argument the consumer accepts - * @param the type of checked exception the consumer may throw + * @param the type of the first argument the consumer accepts + * @param the type of the second argument the consumer accepts + * @param the type of checked exception the consumer may throw */ - public static void accept(final FailableBiConsumer consumer, - final O1 object1, final O2 object2) { + public static void accept(final FailableBiConsumer consumer, + final T object1, final U object2) { run(() -> consumer.accept(object1, object2)); } @@ -90,10 +90,10 @@ public static void accept(final FailableBiConsumer * * @param consumer the consumer to consume * @param object the object to consume by {@code consumer} - * @param the type the consumer accepts - * @param the type of checked exception the consumer may throw + * @param the type the consumer accepts + * @param the type of checked exception the consumer may throw */ - public static void accept(final FailableConsumer consumer, final O object) { + public static void accept(final FailableConsumer consumer, final T object) { run(() -> consumer.accept(object)); } @@ -102,9 +102,9 @@ public static void accept(final FailableConsumer * * @param consumer the consumer to consume * @param value the value to consume by {@code consumer} - * @param the type of checked exception the consumer may throw + * @param the type of checked exception the consumer may throw */ - public static void accept(final FailableDoubleConsumer consumer, final double value) { + public static void accept(final FailableDoubleConsumer consumer, final double value) { run(() -> consumer.accept(value)); } @@ -113,9 +113,9 @@ public static void accept(final FailableDoubleConsumer * * @param consumer the consumer to consume * @param value the value to consume by {@code consumer} - * @param the type of checked exception the consumer may throw + * @param the type of checked exception the consumer may throw */ - public static void accept(final FailableIntConsumer consumer, final int value) { + public static void accept(final FailableIntConsumer consumer, final int value) { run(() -> consumer.accept(value)); } @@ -124,9 +124,9 @@ public static void accept(final FailableIntConsumer con * * @param consumer the consumer to consume * @param value the value to consume by {@code consumer} - * @param the type of checked exception the consumer may throw + * @param the type of checked exception the consumer may throw */ - public static void accept(final FailableLongConsumer consumer, final long value) { + public static void accept(final FailableLongConsumer consumer, final long value) { run(() -> consumer.accept(value)); } @@ -136,14 +136,14 @@ public static void accept(final FailableLongConsumer co * @param function the function to apply * @param input1 the first input to apply {@code function} on * @param input2 the second input to apply {@code function} on - * @param the type of the first argument the function accepts - * @param the type of the second argument the function accepts - * @param the return type of the function - * @param the type of checked exception the function may throw + * @param the type of the first argument the function accepts + * @param the type of the second argument the function accepts + * @param the return type of the function + * @param the type of checked exception the function may throw * @return the value returned from the function */ - public static O apply(final FailableBiFunction function, - final O1 input1, final O2 input2) { + public static R apply(final FailableBiFunction function, + final T input1, final U input2) { return get(() -> function.apply(input1, input2)); } @@ -152,12 +152,12 @@ public static O apply(final FailableBiFunction< * * @param function the function to apply * @param input the input to apply {@code function} on - * @param the type of the argument the function accepts - * @param the return type of the function - * @param the type of checked exception the function may throw + * @param the type of the argument the function accepts + * @param the return type of the function + * @param the type of checked exception the function may throw * @return the value returned from the function */ - public static O apply(final FailableFunction function, final I input) { + public static R apply(final FailableFunction function, final T input) { return get(() -> function.apply(input)); } @@ -167,10 +167,10 @@ public static O apply(final FailableFunction the type of checked exception the function may throw + * @param the type of checked exception the function may throw * @return the value returned from the function */ - public static double applyAsDouble(final FailableDoubleBinaryOperator function, + public static double applyAsDouble(final FailableDoubleBinaryOperator function, final double left, final double right) { return getAsDouble(() -> function.applyAsDouble(left, right)); } @@ -178,82 +178,82 @@ public static double applyAsDouble(final FailableDoubleBin /** * Converts the given {@link FailableBiConsumer} into a standard {@link BiConsumer}. * - * @param the type of the first argument of the consumers - * @param the type of the second argument of the consumers + * @param the type of the first argument of the consumers + * @param the type of the second argument of the consumers * @param consumer a failable {@code BiConsumer} * @return a standard {@code BiConsumer} */ - public static BiConsumer asBiConsumer(final FailableBiConsumer consumer) { + public static BiConsumer asBiConsumer(final FailableBiConsumer consumer) { return (input1, input2) -> accept(consumer, input1, input2); } /** * Converts the given {@link FailableBiFunction} into a standard {@link BiFunction}. * - * @param the type of the first argument of the input of the functions - * @param the type of the second argument of the input of the functions - * @param the type of the output of the functions + * @param the type of the first argument of the input of the functions + * @param the type of the second argument of the input of the functions + * @param the type of the output of the functions * @param function a {@code FailableBiFunction} * @return a standard {@code BiFunction} */ - public static BiFunction asBiFunction(final FailableBiFunction function) { + public static BiFunction asBiFunction(final FailableBiFunction function) { return (input1, input2) -> apply(function, input1, input2); } /** * Converts the given {@link FailableBiPredicate} into a standard {@link BiPredicate}. * - * @param the type of the first argument used by the predicates - * @param the type of the second argument used by the predicates + * @param the type of the first argument used by the predicates + * @param the type of the second argument used by the predicates * @param predicate a {@code FailableBiPredicate} * @return a standard {@code BiPredicate} */ - public static BiPredicate asBiPredicate(final FailableBiPredicate predicate) { + public static BiPredicate asBiPredicate(final FailableBiPredicate predicate) { return (input1, input2) -> test(predicate, input1, input2); } /** * Converts the given {@link FailableCallable} into a standard {@link Callable}. * - * @param the type used by the callables + * @param the type used by the callables * @param callable a {@code FailableCallable} * @return a standard {@code Callable} */ - public static Callable asCallable(final FailableCallable callable) { + public static Callable asCallable(final FailableCallable callable) { return () -> call(callable); } /** * Converts the given {@link FailableConsumer} into a standard {@link Consumer}. * - * @param the type used by the consumers + * @param the type used by the consumers * @param consumer a {@code FailableConsumer} * @return a standard {@code Consumer} */ - public static Consumer asConsumer(final FailableConsumer consumer) { + public static Consumer asConsumer(final FailableConsumer consumer) { return input -> accept(consumer, input); } /** * Converts the given {@link FailableFunction} into a standard {@link Function}. * - * @param the type of the input of the functions - * @param the type of the output of the functions + * @param the type of the input of the functions + * @param the type of the output of the functions * @param function a {code FailableFunction} * @return a standard {@code Function} */ - public static Function asFunction(final FailableFunction function) { + public static Function asFunction(final FailableFunction function) { return input -> apply(function, input); } /** * Converts the given {@link FailablePredicate} into a standard {@link Predicate}. * - * @param the type used by the predicates + * @param the type used by the predicates * @param predicate a {@code FailablePredicate} * @return a standard {@code Predicate} */ - public static Predicate asPredicate(final FailablePredicate predicate) { + public static Predicate asPredicate(final FailablePredicate predicate) { return input -> test(predicate, input); } @@ -270,11 +270,11 @@ public static Runnable asRunnable(final FailableRunnable runnable) { /** * Converts the given {@link FailableSupplier} into a standard {@link Supplier}. * - * @param the type supplied by the suppliers + * @param the type supplied by the suppliers * @param supplier a {@code FailableSupplier} * @return a standard {@code Supplier} */ - public static Supplier asSupplier(final FailableSupplier supplier) { + public static Supplier asSupplier(final FailableSupplier supplier) { return () -> get(supplier); } @@ -282,11 +282,11 @@ public static Supplier asSupplier(final FailableSupplier supplier) * Calls a callable and rethrows any exception as a {@link RuntimeException}. * * @param callable the callable to call - * @param the return type of the callable - * @param the type of checked exception the callable may throw + * @param the return type of the callable + * @param the type of checked exception the callable may throw * @return the value returned from the callable */ - public static O call(final FailableCallable callable) { + public static V call(final FailableCallable callable) { return get(callable::call); } @@ -294,11 +294,11 @@ public static O call(final FailableCallable calla * Invokes a supplier, and returns the result. * * @param supplier The supplier to invoke. - * @param The suppliers output type. - * @param The type of checked exception, which the supplier can throw. + * @param The suppliers output type. + * @param The type of checked exception, which the supplier can throw. * @return The object, which has been created by the supplier */ - public static O get(final FailableSupplier supplier) { + public static T get(final FailableSupplier supplier) { try { return supplier.get(); } catch (final Throwable t) { @@ -310,10 +310,10 @@ public static O get(final FailableSupplier suppli * Invokes a boolean supplier, and returns the result. * * @param supplier The boolean supplier to invoke. - * @param The type of checked exception, which the supplier can throw. + * @param The type of checked exception, which the supplier can throw. * @return The boolean, which has been created by the supplier */ - public static boolean getAsBoolean(final FailableBooleanSupplier supplier) { + public static boolean getAsBoolean(final FailableBooleanSupplier supplier) { try { return supplier.getAsBoolean(); } catch (final Throwable t) { @@ -325,10 +325,10 @@ public static boolean getAsBoolean(final FailableBooleanSu * Invokes a double supplier, and returns the result. * * @param supplier The double supplier to invoke. - * @param The type of checked exception, which the supplier can throw. + * @param The type of checked exception, which the supplier can throw. * @return The boolean, which has been created by the supplier */ - public static double getAsDouble(final FailableDoubleSupplier supplier) { + public static double getAsDouble(final FailableDoubleSupplier supplier) { try { return supplier.getAsDouble(); } catch (final Throwable t) { @@ -340,10 +340,10 @@ public static double getAsDouble(final FailableDoubleSuppl * Invokes an int supplier, and returns the result. * * @param supplier The int supplier to invoke. - * @param The type of checked exception, which the supplier can throw. + * @param The type of checked exception, which the supplier can throw. * @return The boolean, which has been created by the supplier */ - public static int getAsInt(final FailableIntSupplier supplier) { + public static int getAsInt(final FailableIntSupplier supplier) { try { return supplier.getAsInt(); } catch (final Throwable t) { @@ -355,10 +355,10 @@ public static int getAsInt(final FailableIntSupplier su * Invokes a long supplier, and returns the result. * * @param supplier The long supplier to invoke. - * @param The type of checked exception, which the supplier can throw. + * @param The type of checked exception, which the supplier can throw. * @return The boolean, which has been created by the supplier */ - public static long getAsLong(final FailableLongSupplier supplier) { + public static long getAsLong(final FailableLongSupplier supplier) { try { return supplier.getAsLong(); } catch (final Throwable t) { @@ -410,9 +410,9 @@ public static RuntimeException rethrow(final Throwable throwable) { * Runs a runnable and rethrows any exception as a {@link RuntimeException}. * * @param runnable The runnable to run - * @param the type of checked exception the runnable may throw + * @param the type of checked exception the runnable may throw */ - public static void run(final FailableRunnable runnable) { + public static void run(final FailableRunnable runnable) { try { runnable.run(); } catch (final Throwable t) { @@ -429,10 +429,10 @@ public static void run(final FailableRunnable runnable) * * * @param collection The collection, which is being converted into a {@link FailableStream}. - * @param The collections element type. (In turn, the result streams element type.) + * @param The collections element type. (In turn, the result streams element type.) * @return The created {@link FailableStream}. */ - public static FailableStream stream(final Collection collection) { + public static FailableStream stream(final Collection collection) { return new FailableStream<>(collection.stream()); } @@ -443,10 +443,10 @@ public static FailableStream stream(final Collection collection) { * {@link Function}, {@link Consumer}, etc. * * @param stream The stream, which is being converted into a {@link FailableStream}. - * @param The streams element type. + * @param The streams element type. * @return The created {@link FailableStream}. */ - public static FailableStream stream(final Stream stream) { + public static FailableStream stream(final Stream stream) { return new FailableStream<>(stream); } @@ -456,13 +456,13 @@ public static FailableStream stream(final Stream stream) { * @param predicate the predicate to test * @param object1 the first input to test by {@code predicate} * @param object2 the second input to test by {@code predicate} - * @param the type of the first argument the predicate tests - * @param the type of the second argument the predicate tests - * @param the type of checked exception the predicate may throw + * @param the type of the first argument the predicate tests + * @param the type of the second argument the predicate tests + * @param the type of checked exception the predicate may throw * @return the boolean value returned by the predicate */ - public static boolean test(final FailableBiPredicate predicate, - final O1 object1, final O2 object2) { + public static boolean test(final FailableBiPredicate predicate, + final T object1, final U object2) { return getAsBoolean(() -> predicate.test(object1, object2)); } @@ -471,11 +471,11 @@ public static boolean test(final FailableBiPredica * * @param predicate the predicate to test * @param object the input to test by {@code predicate} - * @param the type of argument the predicate tests - * @param the type of checked exception the predicate may throw + * @param the type of argument the predicate tests + * @param the type of checked exception the predicate may throw * @return the boolean value returned by the predicate */ - public static boolean test(final FailablePredicate predicate, final O object) { + public static boolean test(final FailablePredicate predicate, final T object) { return getAsBoolean(() -> predicate.test(object)); } From 91731736990da48ebb60554eeaf4e22146eafc32 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Wed, 24 Jun 2020 16:58:52 -0400 Subject: [PATCH 0205/3230] [LANG-1568] org.apache.commons.lang3.function.FailableBiConsumer.andThen(FailableBiConsumer) --- .../lang3/function/FailableBiConsumer.java | 39 ++- .../commons/lang3/function/package-info.java | 2 +- .../lang3/function/FailableFunctionsTest.java | 265 ++++++++---------- 3 files changed, 161 insertions(+), 145 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/function/FailableBiConsumer.java b/src/main/java/org/apache/commons/lang3/function/FailableBiConsumer.java index 342f5ece69b..34ace1b03a8 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableBiConsumer.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableBiConsumer.java @@ -17,6 +17,7 @@ package org.apache.commons.lang3.function; +import java.util.Objects; import java.util.function.BiConsumer; /** @@ -30,13 +31,45 @@ @FunctionalInterface public interface FailableBiConsumer { + /** NOP singleton */ + @SuppressWarnings("rawtypes") + final FailableBiConsumer NOP = (t, u) -> {/* NOP */}; + + /** + * Returns The NOP singleton. + * + * @param Consumed type 1. + * @param Consumed type 2. + * @param Thrown exception. + * @return The NOP singleton. + */ + static FailableBiConsumer nop() { + return NOP; + } + /** * Accepts the consumer. * - * @param object1 the first parameter for the consumable to accept - * @param object2 the second parameter for the consumable to accept + * @param t the first parameter for the consumable to accept + * @param u the second parameter for the consumable to accept * @throws E Thrown when the consumer fails. */ - void accept(T object1, U object2) throws E; + void accept(T t, U u) throws E; + + /** + * Returns a composed {@code FailableBiConsumer} that performs like {@link BiConsumer#andThen(BiConsumer)}. + * + * @param after the operation to perform after this one. + * @return a composed {@code FailableBiConsumer} that performs like {@link BiConsumer#andThen(BiConsumer)}. + * @throws E Thrown when a consumer fails. + * @throws NullPointerException if {@code after} is null + */ + default FailableBiConsumer andThen(FailableBiConsumer after) throws E { + Objects.requireNonNull(after); + return (t, u) -> { + accept(t, u); + after.accept(t, u); + }; + } } diff --git a/src/main/java/org/apache/commons/lang3/function/package-info.java b/src/main/java/org/apache/commons/lang3/function/package-info.java index aae4c7dd31c..5cc1d9a63d6 100644 --- a/src/main/java/org/apache/commons/lang3/function/package-info.java +++ b/src/main/java/org/apache/commons/lang3/function/package-info.java @@ -19,7 +19,7 @@ * for working with Java 8 lambdas. * *

      Contains failable functional interfaces that address the fact that lambdas are supposed not to - * throw Exceptions, at least not checked Exceptions, AKA instances of {@link java.lang.Exception}. + * throw Exceptions, at least not checked Exceptions, A.K.A. instances of {@link java.lang.Exception}. * A failable functional interface declares a type of Exception that may be raised if the function * fails. * diff --git a/src/test/java/org/apache/commons/lang3/function/FailableFunctionsTest.java b/src/test/java/org/apache/commons/lang3/function/FailableFunctionsTest.java index 7390ab683ea..0560725945f 100644 --- a/src/test/java/org/apache/commons/lang3/function/FailableFunctionsTest.java +++ b/src/test/java/org/apache/commons/lang3/function/FailableFunctionsTest.java @@ -45,6 +45,9 @@ */ public class FailableFunctionsTest { + private static final IllegalStateException ILLEGAL_STATE_EXCEPTION = new IllegalStateException(); + private static final OutOfMemoryError ERROR = new OutOfMemoryError(); + public static class CloseableObject { private boolean closed; @@ -267,14 +270,12 @@ public void testObjLong(final T object, final long i) throws Throwable { @Test void testAcceptBiConsumer() { - final IllegalStateException ise = new IllegalStateException(); final Testable testable = new Testable<>(null); - Throwable e = assertThrows(IllegalStateException.class, () -> Failable.accept(Testable::test, testable, ise)); - assertSame(ise, e); + Throwable e = assertThrows(IllegalStateException.class, () -> Failable.accept(Testable::test, testable, ILLEGAL_STATE_EXCEPTION)); + assertSame(ILLEGAL_STATE_EXCEPTION, e); - final Error error = new OutOfMemoryError(); - e = assertThrows(OutOfMemoryError.class, () -> Failable.accept(Testable::test, testable, error)); - assertSame(error, e); + e = assertThrows(OutOfMemoryError.class, () -> Failable.accept(Testable::test, testable, ERROR)); + assertSame(ERROR, e); final IOException ioe = new IOException("Unknown I/O error"); testable.setThrowable(ioe); @@ -289,15 +290,13 @@ void testAcceptBiConsumer() { @Test void testAcceptConsumer() { - final IllegalStateException ise = new IllegalStateException(); - final Testable testable = new Testable<>(ise); + final Testable testable = new Testable<>(ILLEGAL_STATE_EXCEPTION); Throwable e = assertThrows(IllegalStateException.class, () -> Failable.accept(Testable::test, testable)); - assertSame(ise, e); + assertSame(ILLEGAL_STATE_EXCEPTION, e); - final Error error = new OutOfMemoryError(); - testable.setThrowable(error); + testable.setThrowable(ERROR); e = assertThrows(OutOfMemoryError.class, () -> Failable.accept(Testable::test, testable)); - assertSame(error, e); + assertSame(ERROR, e); final IOException ioe = new IOException("Unknown I/O error"); testable.setThrowable(ioe); @@ -312,16 +311,14 @@ void testAcceptConsumer() { @Test void testAcceptDoubleConsumer() { - final IllegalStateException ise = new IllegalStateException(); - final Testable testable = new Testable<>(ise); + final Testable testable = new Testable<>(ILLEGAL_STATE_EXCEPTION); Throwable e = assertThrows(IllegalStateException.class, () -> Failable.accept(testable::testDouble, 1d)); - assertSame(ise, e); + assertSame(ILLEGAL_STATE_EXCEPTION, e); assertNull(testable.getAcceptedPrimitiveObject1()); - final Error error = new OutOfMemoryError(); - testable.setThrowable(error); + testable.setThrowable(ERROR); e = assertThrows(OutOfMemoryError.class, () -> Failable.accept(testable::testDouble, 1d)); - assertSame(error, e); + assertSame(ERROR, e); assertNull(testable.getAcceptedPrimitiveObject1()); final IOException ioe = new IOException("Unknown I/O error"); @@ -339,16 +336,14 @@ void testAcceptDoubleConsumer() { @Test void testAcceptIntConsumer() { - final IllegalStateException ise = new IllegalStateException(); - final Testable testable = new Testable<>(ise); + final Testable testable = new Testable<>(ILLEGAL_STATE_EXCEPTION); Throwable e = assertThrows(IllegalStateException.class, () -> Failable.accept(testable::testInt, 1)); - assertSame(ise, e); + assertSame(ILLEGAL_STATE_EXCEPTION, e); assertNull(testable.getAcceptedPrimitiveObject1()); - final Error error = new OutOfMemoryError(); - testable.setThrowable(error); + testable.setThrowable(ERROR); e = assertThrows(OutOfMemoryError.class, () -> Failable.accept(testable::testInt, 1)); - assertSame(error, e); + assertSame(ERROR, e); assertNull(testable.getAcceptedPrimitiveObject1()); final IOException ioe = new IOException("Unknown I/O error"); @@ -366,16 +361,14 @@ void testAcceptIntConsumer() { @Test void testAcceptLongConsumer() { - final IllegalStateException ise = new IllegalStateException(); - final Testable testable = new Testable<>(ise); + final Testable testable = new Testable<>(ILLEGAL_STATE_EXCEPTION); Throwable e = assertThrows(IllegalStateException.class, () -> Failable.accept(testable::testLong, 1L)); - assertSame(ise, e); + assertSame(ILLEGAL_STATE_EXCEPTION, e); assertNull(testable.getAcceptedPrimitiveObject1()); - final Error error = new OutOfMemoryError(); - testable.setThrowable(error); + testable.setThrowable(ERROR); e = assertThrows(OutOfMemoryError.class, () -> Failable.accept(testable::testLong, 1L)); - assertSame(error, e); + assertSame(ERROR, e); assertNull(testable.getAcceptedPrimitiveObject1()); final IOException ioe = new IOException("Unknown I/O error"); @@ -393,18 +386,16 @@ void testAcceptLongConsumer() { @Test void testAcceptObjDoubleConsumer() { - final IllegalStateException ise = new IllegalStateException(); - final Testable testable = new Testable<>(ise); + final Testable testable = new Testable<>(ILLEGAL_STATE_EXCEPTION); Throwable e = assertThrows(IllegalStateException.class, () -> Failable.accept(testable::testObjDouble, "X", 1d)); - assertSame(ise, e); + assertSame(ILLEGAL_STATE_EXCEPTION, e); assertNull(testable.getAcceptedObject()); assertNull(testable.getAcceptedPrimitiveObject1()); - final Error error = new OutOfMemoryError(); - testable.setThrowable(error); + testable.setThrowable(ERROR); e = assertThrows(OutOfMemoryError.class, () -> Failable.accept(testable::testObjDouble, "X", 1d)); - assertSame(error, e); + assertSame(ERROR, e); assertNull(testable.getAcceptedObject()); assertNull(testable.getAcceptedPrimitiveObject1()); @@ -425,17 +416,15 @@ void testAcceptObjDoubleConsumer() { @Test void testAcceptObjIntConsumer() { - final IllegalStateException ise = new IllegalStateException(); - final Testable testable = new Testable<>(ise); + final Testable testable = new Testable<>(ILLEGAL_STATE_EXCEPTION); Throwable e = assertThrows(IllegalStateException.class, () -> Failable.accept(testable::testObjInt, "X", 1)); - assertSame(ise, e); + assertSame(ILLEGAL_STATE_EXCEPTION, e); assertNull(testable.getAcceptedObject()); assertNull(testable.getAcceptedPrimitiveObject1()); - final Error error = new OutOfMemoryError(); - testable.setThrowable(error); + testable.setThrowable(ERROR); e = assertThrows(OutOfMemoryError.class, () -> Failable.accept(testable::testObjInt, "X", 1)); - assertSame(error, e); + assertSame(ERROR, e); assertNull(testable.getAcceptedObject()); assertNull(testable.getAcceptedPrimitiveObject1()); @@ -456,17 +445,15 @@ void testAcceptObjIntConsumer() { @Test void testAcceptObjLongConsumer() { - final IllegalStateException ise = new IllegalStateException(); - final Testable testable = new Testable<>(ise); + final Testable testable = new Testable<>(ILLEGAL_STATE_EXCEPTION); Throwable e = assertThrows(IllegalStateException.class, () -> Failable.accept(testable::testObjLong, "X", 1L)); - assertSame(ise, e); + assertSame(ILLEGAL_STATE_EXCEPTION, e); assertNull(testable.getAcceptedObject()); assertNull(testable.getAcceptedPrimitiveObject1()); - final Error error = new OutOfMemoryError(); - testable.setThrowable(error); + testable.setThrowable(ERROR); e = assertThrows(OutOfMemoryError.class, () -> Failable.accept(testable::testObjLong, "X", 1L)); - assertSame(error, e); + assertSame(ERROR, e); assertNull(testable.getAcceptedObject()); assertNull(testable.getAcceptedPrimitiveObject1()); @@ -487,15 +474,13 @@ void testAcceptObjLongConsumer() { @Test public void testApplyBiFunction() { - final IllegalStateException ise = new IllegalStateException(); final Testable testable = new Testable<>(null); Throwable e = assertThrows(IllegalStateException.class, - () -> Failable.apply(Testable::testAsInteger, testable, ise)); - assertSame(ise, e); + () -> Failable.apply(Testable::testAsInteger, testable, ILLEGAL_STATE_EXCEPTION)); + assertSame(ILLEGAL_STATE_EXCEPTION, e); - final Error error = new OutOfMemoryError(); - e = assertThrows(OutOfMemoryError.class, () -> Failable.apply(Testable::testAsInteger, testable, error)); - assertSame(error, e); + e = assertThrows(OutOfMemoryError.class, () -> Failable.apply(Testable::testAsInteger, testable, ERROR)); + assertSame(ERROR, e); final IOException ioe = new IOException("Unknown I/O error"); e = assertThrows(UncheckedIOException.class, () -> Failable.apply(Testable::testAsInteger, testable, ioe)); @@ -510,11 +495,10 @@ public void testApplyBiFunction() { @Test public void testApplyDoubleBinaryOperator() { - final IllegalStateException ise = new IllegalStateException(); - final Testable testable = new Testable<>(ise); + final Testable testable = new Testable<>(ILLEGAL_STATE_EXCEPTION); final Throwable e = assertThrows(IllegalStateException.class, () -> Failable.applyAsDouble(testable::testDoubleDouble, 1d, 2d)); - assertSame(ise, e); + assertSame(ILLEGAL_STATE_EXCEPTION, e); final Testable testable2 = new Testable<>(null); final double i = Failable.applyAsDouble(testable2::testDoubleDouble, 1d, 2d); @@ -523,16 +507,14 @@ public void testApplyDoubleBinaryOperator() { @Test public void testApplyFunction() { - final IllegalStateException ise = new IllegalStateException(); - final Testable testable = new Testable<>(ise); + final Testable testable = new Testable<>(ILLEGAL_STATE_EXCEPTION); Throwable e = assertThrows(IllegalStateException.class, () -> Failable.apply(Testable::testAsInteger, testable)); - assertSame(ise, e); + assertSame(ILLEGAL_STATE_EXCEPTION, e); - final Error error = new OutOfMemoryError(); - testable.setThrowable(error); + testable.setThrowable(ERROR); e = assertThrows(OutOfMemoryError.class, () -> Failable.apply(Testable::testAsInteger, testable)); - assertSame(error, e); + assertSame(ERROR, e); final IOException ioe = new IOException("Unknown I/O error"); testable.setThrowable(ioe); @@ -568,16 +550,14 @@ void testAsCallable() { @Test void testAsConsumer() { - final IllegalStateException ise = new IllegalStateException(); - final Testable testable = new Testable<>(ise); + final Testable testable = new Testable<>(ILLEGAL_STATE_EXCEPTION); final Consumer> consumer = Failable.asConsumer(Testable::test); Throwable e = assertThrows(IllegalStateException.class, () -> consumer.accept(testable)); - assertSame(ise, e); + assertSame(ILLEGAL_STATE_EXCEPTION, e); - final Error error = new OutOfMemoryError(); - testable.setThrowable(error); + testable.setThrowable(ERROR); e = assertThrows(OutOfMemoryError.class, () -> consumer.accept(testable)); - assertSame(error, e); + assertSame(ERROR, e); final IOException ioe = new IOException("Unknown I/O error"); testable.setThrowable(ioe); @@ -618,20 +598,22 @@ public void testAsSupplier() { } @Test - void testBiConsumer() { - final IllegalStateException ise = new IllegalStateException(); + void testBiConsumer() throws Throwable { final Testable testable = new Testable<>(null); final FailableBiConsumer, Throwable, Throwable> failableBiConsumer = (t, th) -> { t.setThrowable(th); t.test(); }; final BiConsumer, Throwable> consumer = Failable.asBiConsumer(failableBiConsumer); - Throwable e = assertThrows(IllegalStateException.class, () -> consumer.accept(testable, ise)); - assertSame(ise, e); + Throwable e = assertThrows(IllegalStateException.class, + () -> consumer.accept(testable, ILLEGAL_STATE_EXCEPTION)); + assertSame(ILLEGAL_STATE_EXCEPTION, e); + + e = assertThrows(OutOfMemoryError.class, () -> consumer.accept(testable, ERROR)); + assertSame(ERROR, e); - final Error error = new OutOfMemoryError(); - e = assertThrows(OutOfMemoryError.class, () -> consumer.accept(testable, error)); - assertSame(error, e); + e = assertThrows(OutOfMemoryError.class, () -> failableBiConsumer.accept(testable, ERROR)); + assertSame(ERROR, e); final IOException ioe = new IOException("Unknown I/O error"); testable.setThrowable(ioe); @@ -643,9 +625,27 @@ void testBiConsumer() { consumer.accept(testable, null); } + @Test + void testBiConsumerAndThen() throws Throwable { + final Testable testable = new Testable<>(null); + final FailableBiConsumer, Throwable, Throwable> failableBiConsumer = (t, th) -> { + t.setThrowable(th); + t.test(); + }; + Throwable e; + final FailableBiConsumer, Throwable, Throwable> nop = FailableBiConsumer.nop(); + e = assertThrows(OutOfMemoryError.class, () -> nop.andThen(failableBiConsumer).accept(testable, ERROR)); + assertSame(ERROR, e); + // Does not throw + nop.andThen(nop); + // Documented in Javadoc edge-case. + assertThrows(NullPointerException.class, () -> failableBiConsumer.andThen(null)); + + } + @Test public void testBiFunction() { - final IllegalStateException ise = new IllegalStateException(); + final IllegalStateException ise = ILLEGAL_STATE_EXCEPTION; final Testable testable = new Testable<>(ise); final FailableBiFunction, Throwable, Integer, Throwable> failableBiFunction = (t, th) -> { t.setThrowable(th); @@ -655,10 +655,9 @@ public void testBiFunction() { Throwable e = assertThrows(IllegalStateException.class, () -> biFunction.apply(testable, ise)); assertSame(ise, e); - final Error error = new OutOfMemoryError(); - testable.setThrowable(error); - e = assertThrows(OutOfMemoryError.class, () -> biFunction.apply(testable, error)); - assertSame(error, e); + testable.setThrowable(ERROR); + e = assertThrows(OutOfMemoryError.class, () -> biFunction.apply(testable, ERROR)); + assertSame(ERROR, e); final IOException ioe = new IOException("Unknown I/O error"); testable.setThrowable(ioe); @@ -674,8 +673,8 @@ public void testBiFunction() { @DisplayName("Test that asPredicate(FailableBiPredicate) is converted to -> BiPredicate ") public void testBiPredicate() { FailureOnOddInvocations.invocations = 0; - final FailableBiPredicate failableBiPredicate = (t1, - t2) -> FailureOnOddInvocations.failingBool(); + final FailableBiPredicate failableBiPredicate = (t1, t2) -> FailureOnOddInvocations + .failingBool(); final BiPredicate predicate = Failable.asBiPredicate(failableBiPredicate); final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, () -> predicate.test(null, null)); @@ -717,20 +716,18 @@ public void testDoublePredicate() throws Throwable { @Test public void testFunction() { - final IllegalStateException ise = new IllegalStateException(); - final Testable testable = new Testable<>(ise); + final Testable testable = new Testable<>(ILLEGAL_STATE_EXCEPTION); final FailableFunction failableFunction = th -> { testable.setThrowable(th); return Integer.valueOf(testable.testAsInteger()); }; final Function function = Failable.asFunction(failableFunction); - Throwable e = assertThrows(IllegalStateException.class, () -> function.apply(ise)); - assertSame(ise, e); + Throwable e = assertThrows(IllegalStateException.class, () -> function.apply(ILLEGAL_STATE_EXCEPTION)); + assertSame(ILLEGAL_STATE_EXCEPTION, e); - final Error error = new OutOfMemoryError(); - testable.setThrowable(error); - e = assertThrows(OutOfMemoryError.class, () -> function.apply(error)); - assertSame(error, e); + testable.setThrowable(ERROR); + e = assertThrows(OutOfMemoryError.class, () -> function.apply(ERROR)); + assertSame(ERROR, e); final IOException ioe = new IOException("Unknown I/O error"); testable.setThrowable(ioe); @@ -744,16 +741,14 @@ public void testFunction() { @Test public void testGetAsBooleanSupplier() { - final IllegalStateException ise = new IllegalStateException(); - final Testable testable = new Testable<>(ise); + final Testable testable = new Testable<>(ILLEGAL_STATE_EXCEPTION); Throwable e = assertThrows(IllegalStateException.class, () -> Failable.getAsBoolean(testable::testAsBooleanPrimitive)); - assertSame(ise, e); + assertSame(ILLEGAL_STATE_EXCEPTION, e); - final Error error = new OutOfMemoryError(); - testable.setThrowable(error); + testable.setThrowable(ERROR); e = assertThrows(OutOfMemoryError.class, () -> Failable.getAsBoolean(testable::testAsBooleanPrimitive)); - assertSame(error, e); + assertSame(ERROR, e); final IOException ioe = new IOException("Unknown I/O error"); testable.setThrowable(ioe); @@ -768,16 +763,14 @@ public void testGetAsBooleanSupplier() { @Test public void testGetAsDoubleSupplier() { - final IllegalStateException ise = new IllegalStateException(); - final Testable testable = new Testable<>(ise); + final Testable testable = new Testable<>(ILLEGAL_STATE_EXCEPTION); Throwable e = assertThrows(IllegalStateException.class, () -> Failable.getAsDouble(testable::testAsDoublePrimitive)); - assertSame(ise, e); + assertSame(ILLEGAL_STATE_EXCEPTION, e); - final Error error = new OutOfMemoryError(); - testable.setThrowable(error); + testable.setThrowable(ERROR); e = assertThrows(OutOfMemoryError.class, () -> Failable.getAsDouble(testable::testAsDoublePrimitive)); - assertSame(error, e); + assertSame(ERROR, e); final IOException ioe = new IOException("Unknown I/O error"); testable.setThrowable(ioe); @@ -792,15 +785,13 @@ public void testGetAsDoubleSupplier() { @Test public void testGetAsIntSupplier() { - final IllegalStateException ise = new IllegalStateException(); - final Testable testable = new Testable<>(ise); + final Testable testable = new Testable<>(ILLEGAL_STATE_EXCEPTION); Throwable e = assertThrows(IllegalStateException.class, () -> Failable.getAsInt(testable::testAsIntPrimitive)); - assertSame(ise, e); + assertSame(ILLEGAL_STATE_EXCEPTION, e); - final Error error = new OutOfMemoryError(); - testable.setThrowable(error); + testable.setThrowable(ERROR); e = assertThrows(OutOfMemoryError.class, () -> Failable.getAsInt(testable::testAsIntPrimitive)); - assertSame(error, e); + assertSame(ERROR, e); final IOException ioe = new IOException("Unknown I/O error"); testable.setThrowable(ioe); @@ -816,16 +807,14 @@ public void testGetAsIntSupplier() { @Test public void testGetAsLongSupplier() { - final IllegalStateException ise = new IllegalStateException(); - final Testable testable = new Testable<>(ise); + final Testable testable = new Testable<>(ILLEGAL_STATE_EXCEPTION); Throwable e = assertThrows(IllegalStateException.class, () -> Failable.getAsLong(testable::testAsLongPrimitive)); - assertSame(ise, e); + assertSame(ILLEGAL_STATE_EXCEPTION, e); - final Error error = new OutOfMemoryError(); - testable.setThrowable(error); + testable.setThrowable(ERROR); e = assertThrows(OutOfMemoryError.class, () -> Failable.getAsLong(testable::testAsLongPrimitive)); - assertSame(error, e); + assertSame(ERROR, e); final IOException ioe = new IOException("Unknown I/O error"); testable.setThrowable(ioe); @@ -854,15 +843,13 @@ public void testGetFromSupplier() { @Test public void testGetSupplier() { - final IllegalStateException ise = new IllegalStateException(); - final Testable testable = new Testable<>(ise); + final Testable testable = new Testable<>(ILLEGAL_STATE_EXCEPTION); Throwable e = assertThrows(IllegalStateException.class, () -> Failable.get(testable::testAsInteger)); - assertSame(ise, e); + assertSame(ILLEGAL_STATE_EXCEPTION, e); - final Error error = new OutOfMemoryError(); - testable.setThrowable(error); + testable.setThrowable(ERROR); e = assertThrows(OutOfMemoryError.class, () -> Failable.get(testable::testAsInteger)); - assertSame(error, e); + assertSame(ERROR, e); final IOException ioe = new IOException("Unknown I/O error"); testable.setThrowable(ioe); @@ -897,8 +884,7 @@ public void testLongPredicate() throws Throwable { @DisplayName("Test that asPredicate(FailablePredicate) is converted to -> Predicate ") public void testPredicate() { FailureOnOddInvocations.invocations = 0; - final FailablePredicate failablePredicate = t -> FailureOnOddInvocations - .failingBool(); + final FailablePredicate failablePredicate = t -> FailureOnOddInvocations.failingBool(); final Predicate predicate = Failable.asPredicate(failablePredicate); final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, () -> predicate.test(null)); @@ -1047,7 +1033,6 @@ public boolean getAsBoolean() throws IOException { /////////////////////////////////////////////// - /** * Tests that our failable interface is properly defined to throw any exception. using the top level generic types * Object and Throwable. @@ -2050,32 +2035,30 @@ public long applyAsLong(final String t) throws IOException { @Test public void testTryWithResources() { - final CloseableObject co = new CloseableObject(); - final FailableConsumer consumer = co::run; - final IllegalStateException ise = new IllegalStateException(); + final CloseableObject closeable = new CloseableObject(); + final FailableConsumer consumer = closeable::run; Throwable e = assertThrows(IllegalStateException.class, - () -> Failable.tryWithResources(() -> consumer.accept(ise), co::close)); - assertSame(ise, e); + () -> Failable.tryWithResources(() -> consumer.accept(ILLEGAL_STATE_EXCEPTION), closeable::close)); + assertSame(ILLEGAL_STATE_EXCEPTION, e); - assertTrue(co.isClosed()); - co.reset(); - final Error error = new OutOfMemoryError(); + assertTrue(closeable.isClosed()); + closeable.reset(); e = assertThrows(OutOfMemoryError.class, - () -> Failable.tryWithResources(() -> consumer.accept(error), co::close)); - assertSame(error, e); + () -> Failable.tryWithResources(() -> consumer.accept(ERROR), closeable::close)); + assertSame(ERROR, e); - assertTrue(co.isClosed()); - co.reset(); + assertTrue(closeable.isClosed()); + closeable.reset(); final IOException ioe = new IOException("Unknown I/O error"); final UncheckedIOException uioe = assertThrows(UncheckedIOException.class, - () -> Failable.tryWithResources(() -> consumer.accept(ioe), co::close)); + () -> Failable.tryWithResources(() -> consumer.accept(ioe), closeable::close)); final IOException cause = uioe.getCause(); assertSame(ioe, cause); - assertTrue(co.isClosed()); - co.reset(); - Failable.tryWithResources(() -> consumer.accept(null), co::close); - assertTrue(co.isClosed()); + assertTrue(closeable.isClosed()); + closeable.reset(); + Failable.tryWithResources(() -> consumer.accept(null), closeable::close); + assertTrue(closeable.isClosed()); } } From e7c421ff35958ce2df61de1091d355370ae28475 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Wed, 24 Jun 2020 17:02:35 -0400 Subject: [PATCH 0206/3230] [LANG-1568] org.apache.commons.lang3.function.FailableBiConsumer.andThen(FailableBiConsumer) --- .../org/apache/commons/lang3/function/FailableBiConsumer.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/function/FailableBiConsumer.java b/src/main/java/org/apache/commons/lang3/function/FailableBiConsumer.java index 34ace1b03a8..ec31596bd46 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableBiConsumer.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableBiConsumer.java @@ -57,10 +57,10 @@ static FailableBiConsumer nop() { void accept(T t, U u) throws E; /** - * Returns a composed {@code FailableBiConsumer} that performs like {@link BiConsumer#andThen(BiConsumer)}. + * Returns a composed {@code FailableBiConsumer} that like {@link BiConsumer#andThen(BiConsumer)}. * * @param after the operation to perform after this one. - * @return a composed {@code FailableBiConsumer} that performs like {@link BiConsumer#andThen(BiConsumer)}. + * @return a composed {@code FailableBiConsumer} that like {@link BiConsumer#andThen(BiConsumer)}. * @throws E Thrown when a consumer fails. * @throws NullPointerException if {@code after} is null */ From 4badcde7f7cfb7a295103b5b89d1e58a868e196b Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Wed, 24 Jun 2020 17:03:17 -0400 Subject: [PATCH 0207/3230] [LANG-1568] org.apache.commons.lang3.function.FailableBiConsumer.andThen(FailableBiConsumer) --- .../org/apache/commons/lang3/function/FailableBiConsumer.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/function/FailableBiConsumer.java b/src/main/java/org/apache/commons/lang3/function/FailableBiConsumer.java index ec31596bd46..5f56b06e91f 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableBiConsumer.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableBiConsumer.java @@ -57,10 +57,10 @@ static FailableBiConsumer nop() { void accept(T t, U u) throws E; /** - * Returns a composed {@code FailableBiConsumer} that like {@link BiConsumer#andThen(BiConsumer)}. + * Returns a composed {@code FailableBiConsumer} like {@link BiConsumer#andThen(BiConsumer)}. * * @param after the operation to perform after this one. - * @return a composed {@code FailableBiConsumer} that like {@link BiConsumer#andThen(BiConsumer)}. + * @return a composed {@code FailableBiConsumer} like {@link BiConsumer#andThen(BiConsumer)}. * @throws E Thrown when a consumer fails. * @throws NullPointerException if {@code after} is null */ From c7aea90a7a6e27d7159034cfbea64f796c6846af Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Wed, 24 Jun 2020 18:25:47 -0400 Subject: [PATCH 0208/3230] [LANG-1568] org.apache.commons.lang3.function.FailableBiFunction.andThen(FailableFunction) --- .../lang3/function/FailableBiConsumer.java | 6 +-- .../lang3/function/FailableBiFunction.java | 33 +++++++++++++ .../lang3/function/FailableFunction.java | 16 ++++++ .../lang3/function/FailableFunctionsTest.java | 49 ++++++++++++++----- 4 files changed, 88 insertions(+), 16 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/function/FailableBiConsumer.java b/src/main/java/org/apache/commons/lang3/function/FailableBiConsumer.java index 5f56b06e91f..6d5d99f5ffd 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableBiConsumer.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableBiConsumer.java @@ -37,7 +37,7 @@ public interface FailableBiConsumer { /** * Returns The NOP singleton. - * + * * @param Consumed type 1. * @param Consumed type 2. * @param Thrown exception. @@ -62,9 +62,9 @@ static FailableBiConsumer nop() { * @param after the operation to perform after this one. * @return a composed {@code FailableBiConsumer} like {@link BiConsumer#andThen(BiConsumer)}. * @throws E Thrown when a consumer fails. - * @throws NullPointerException if {@code after} is null + * @throws NullPointerException if {@code after} is null. */ - default FailableBiConsumer andThen(FailableBiConsumer after) throws E { + default FailableBiConsumer andThen(final FailableBiConsumer after) throws E { Objects.requireNonNull(after); return (t, u) -> { diff --git a/src/main/java/org/apache/commons/lang3/function/FailableBiFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableBiFunction.java index d112be8e981..be0e4704b34 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableBiFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableBiFunction.java @@ -17,7 +17,9 @@ package org.apache.commons.lang3.function; +import java.util.Objects; import java.util.function.BiFunction; +import java.util.function.Function; /** * A functional interface like {@link BiFunction} that declares a {@code Throwable}. @@ -31,6 +33,37 @@ @FunctionalInterface public interface FailableBiFunction { + /** NOP singleton */ + @SuppressWarnings("rawtypes") + final FailableBiFunction NOP = (t, u) -> null; + + /** + * Returns The NOP singleton. + * + * @param Consumed type 1. + * @param Consumed type 2. + * @param Return type. + * @param Thrown exception. + * @return The NOP singleton. + */ + static FailableBiFunction nop() { + return NOP; + } + + /** + * Returns a composed {@code FailableBiFunction} that like {@link BiFunction#andThen(Function)}. + * + * @param the type of output of the {@code after} function, and of the composed function + * @param after the operation to perform after this one. + * @return a composed {@code FailableBiFunction} that like {@link BiFunction#andThen(Function)}. + * @throws E Thrown when a consumer fails. + * @throws NullPointerException if after is null. + */ + default FailableBiFunction andThen(final FailableFunction after) throws E { + Objects.requireNonNull(after); + return (final T t, final U u) -> after.apply(apply(t, u)); + } + /** * Applies this function. * diff --git a/src/main/java/org/apache/commons/lang3/function/FailableFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableFunction.java index 7de44379660..3d4b905b630 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableFunction.java @@ -30,6 +30,22 @@ @FunctionalInterface public interface FailableFunction { + /** NOP singleton */ + @SuppressWarnings("rawtypes") + final FailableFunction NOP = t -> null; + + /** + * Returns The NOP singleton. + * + * @param Consumed type 1. + * @param Return type. + * @param Thrown exception. + * @return The NOP singleton. + */ + static FailableFunction nop() { + return NOP; + } + /** * Applies this function. * diff --git a/src/test/java/org/apache/commons/lang3/function/FailableFunctionsTest.java b/src/test/java/org/apache/commons/lang3/function/FailableFunctionsTest.java index 0560725945f..81da56e117a 100644 --- a/src/test/java/org/apache/commons/lang3/function/FailableFunctionsTest.java +++ b/src/test/java/org/apache/commons/lang3/function/FailableFunctionsTest.java @@ -45,9 +45,6 @@ */ public class FailableFunctionsTest { - private static final IllegalStateException ILLEGAL_STATE_EXCEPTION = new IllegalStateException(); - private static final OutOfMemoryError ERROR = new OutOfMemoryError(); - public static class CloseableObject { private boolean closed; @@ -69,7 +66,6 @@ public void run(final Throwable pTh) throws Throwable { } } } - public static class FailureOnOddInvocations { private static int invocations; @@ -268,10 +264,15 @@ public void testObjLong(final T object, final long i) throws Throwable { } } + private static final OutOfMemoryError ERROR = new OutOfMemoryError(); + + private static final IllegalStateException ILLEGAL_STATE_EXCEPTION = new IllegalStateException(); + @Test void testAcceptBiConsumer() { final Testable testable = new Testable<>(null); - Throwable e = assertThrows(IllegalStateException.class, () -> Failable.accept(Testable::test, testable, ILLEGAL_STATE_EXCEPTION)); + Throwable e = assertThrows(IllegalStateException.class, + () -> Failable.accept(Testable::test, testable, ILLEGAL_STATE_EXCEPTION)); assertSame(ILLEGAL_STATE_EXCEPTION, e); e = assertThrows(OutOfMemoryError.class, () -> Failable.accept(Testable::test, testable, ERROR)); @@ -632,28 +633,27 @@ void testBiConsumerAndThen() throws Throwable { t.setThrowable(th); t.test(); }; - Throwable e; final FailableBiConsumer, Throwable, Throwable> nop = FailableBiConsumer.nop(); - e = assertThrows(OutOfMemoryError.class, () -> nop.andThen(failableBiConsumer).accept(testable, ERROR)); + final Throwable e = assertThrows(OutOfMemoryError.class, + () -> nop.andThen(failableBiConsumer).accept(testable, ERROR)); assertSame(ERROR, e); // Does not throw nop.andThen(nop); // Documented in Javadoc edge-case. assertThrows(NullPointerException.class, () -> failableBiConsumer.andThen(null)); - } @Test public void testBiFunction() { - final IllegalStateException ise = ILLEGAL_STATE_EXCEPTION; - final Testable testable = new Testable<>(ise); + final Testable testable = new Testable<>(ILLEGAL_STATE_EXCEPTION); final FailableBiFunction, Throwable, Integer, Throwable> failableBiFunction = (t, th) -> { t.setThrowable(th); - return Integer.valueOf(t.testAsInteger()); + return t.testAsInteger(); }; final BiFunction, Throwable, Integer> biFunction = Failable.asBiFunction(failableBiFunction); - Throwable e = assertThrows(IllegalStateException.class, () -> biFunction.apply(testable, ise)); - assertSame(ise, e); + Throwable e = assertThrows(IllegalStateException.class, + () -> biFunction.apply(testable, ILLEGAL_STATE_EXCEPTION)); + assertSame(ILLEGAL_STATE_EXCEPTION, e); testable.setThrowable(ERROR); e = assertThrows(OutOfMemoryError.class, () -> biFunction.apply(testable, ERROR)); @@ -669,6 +669,29 @@ public void testBiFunction() { assertEquals(0, biFunction.apply(testable, null).intValue()); } + @Test + public void testBiFunctionAndThen() throws IOException { + // Unchecked usage pattern in JRE + final BiFunction nopBiFunction = (t, u) -> null; + final Function nopFunction = (t) -> null; + nopBiFunction.andThen(nopFunction); + // Checked usage pattern + final FailableBiFunction failingBiFunctionTest = (t, u) -> { + throw new IOException(); + }; + final FailableFunction failingFunction = (t) -> { throw new IOException(); }; + final FailableBiFunction nopFailableBiFunction = FailableBiFunction.nop(); + final FailableFunction nopFailableFunction = FailableFunction.nop(); + // + assertThrows(IOException.class, () -> failingBiFunctionTest.andThen(failingFunction).apply(null, null)); + assertThrows(IOException.class, () -> failingBiFunctionTest.andThen(nopFailableFunction).apply(null, null)); + // + assertThrows(IOException.class, () -> nopFailableBiFunction.andThen(failingFunction).apply(null, null)); + nopFailableBiFunction.andThen(nopFailableFunction).apply(null, null); + // Documented in Javadoc edge-case. + assertThrows(NullPointerException.class, () -> failingBiFunctionTest.andThen(null)); + } + @Test @DisplayName("Test that asPredicate(FailableBiPredicate) is converted to -> BiPredicate ") public void testBiPredicate() { From 47fb7767924e95157488d0816599e5d7c9cf40a9 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Wed, 24 Jun 2020 18:40:25 -0400 Subject: [PATCH 0209/3230] [LANG-1568] org.apache.commons.lang3.function.FailableConsumer.andThen(FailableConsumer) --- .../lang3/function/FailableBiFunction.java | 2 +- .../lang3/function/FailableConsumer.java | 38 ++++++++++- .../lang3/function/FailableFunctionsTest.java | 67 ++++++++++++------- 3 files changed, 78 insertions(+), 29 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/function/FailableBiFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableBiFunction.java index be0e4704b34..3173c73b781 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableBiFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableBiFunction.java @@ -57,7 +57,7 @@ static FailableBiFunction nop() { * @param after the operation to perform after this one. * @return a composed {@code FailableBiFunction} that like {@link BiFunction#andThen(Function)}. * @throws E Thrown when a consumer fails. - * @throws NullPointerException if after is null. + * @throws NullPointerException if {@code after} is null. */ default FailableBiFunction andThen(final FailableFunction after) throws E { Objects.requireNonNull(after); diff --git a/src/main/java/org/apache/commons/lang3/function/FailableConsumer.java b/src/main/java/org/apache/commons/lang3/function/FailableConsumer.java index acb73cc51ed..c2f2de8a909 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableConsumer.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableConsumer.java @@ -17,17 +17,33 @@ package org.apache.commons.lang3.function; +import java.util.Objects; import java.util.function.Consumer; /** * A functional interface like {@link Consumer} that declares a {@code Throwable}. * - * @param Consumed type 1. + * @param Consumed type 1. * @param Thrown exception. * @since 3.11 */ @FunctionalInterface -public interface FailableConsumer { +public interface FailableConsumer { + + /** NOP singleton */ + @SuppressWarnings("rawtypes") + final FailableConsumer NOP = t -> {/* NOP */}; + + /** + * Returns The NOP singleton. + * + * @param Consumed type 1. + * @param Thrown exception. + * @return The NOP singleton. + */ + static FailableConsumer nop() { + return NOP; + } /** * Accepts the consumer. @@ -35,5 +51,21 @@ public interface FailableConsumer { * @param object the parameter for the consumable to accept * @throws E Thrown when the consumer fails. */ - void accept(O object) throws E; + void accept(T object) throws E; + + /** + * Returns a composed {@code Consumer} like {@link Consumer#andThen(Consumer)}. + * + * @param after the operation to perform after this operation + * @return a composed {@code Consumer} like {@link Consumer#andThen(Consumer)}. + * @throws E Thrown when a consumer fails. + * @throws NullPointerException if {@code after} is null + */ + default FailableConsumer andThen(final FailableConsumer after) throws E { + Objects.requireNonNull(after); + return (final T t) -> { + accept(t); + after.accept(t); + }; + } } diff --git a/src/test/java/org/apache/commons/lang3/function/FailableFunctionsTest.java b/src/test/java/org/apache/commons/lang3/function/FailableFunctionsTest.java index 81da56e117a..24a1054cd01 100644 --- a/src/test/java/org/apache/commons/lang3/function/FailableFunctionsTest.java +++ b/src/test/java/org/apache/commons/lang3/function/FailableFunctionsTest.java @@ -269,7 +269,7 @@ public void testObjLong(final T object, final long i) throws Throwable { private static final IllegalStateException ILLEGAL_STATE_EXCEPTION = new IllegalStateException(); @Test - void testAcceptBiConsumer() { + public void testAcceptBiConsumer() { final Testable testable = new Testable<>(null); Throwable e = assertThrows(IllegalStateException.class, () -> Failable.accept(Testable::test, testable, ILLEGAL_STATE_EXCEPTION)); @@ -290,7 +290,7 @@ void testAcceptBiConsumer() { } @Test - void testAcceptConsumer() { + public void testAcceptConsumer() { final Testable testable = new Testable<>(ILLEGAL_STATE_EXCEPTION); Throwable e = assertThrows(IllegalStateException.class, () -> Failable.accept(Testable::test, testable)); assertSame(ILLEGAL_STATE_EXCEPTION, e); @@ -311,7 +311,7 @@ void testAcceptConsumer() { } @Test - void testAcceptDoubleConsumer() { + public void testAcceptDoubleConsumer() { final Testable testable = new Testable<>(ILLEGAL_STATE_EXCEPTION); Throwable e = assertThrows(IllegalStateException.class, () -> Failable.accept(testable::testDouble, 1d)); assertSame(ILLEGAL_STATE_EXCEPTION, e); @@ -336,7 +336,7 @@ void testAcceptDoubleConsumer() { } @Test - void testAcceptIntConsumer() { + public void testAcceptIntConsumer() { final Testable testable = new Testable<>(ILLEGAL_STATE_EXCEPTION); Throwable e = assertThrows(IllegalStateException.class, () -> Failable.accept(testable::testInt, 1)); assertSame(ILLEGAL_STATE_EXCEPTION, e); @@ -361,7 +361,7 @@ void testAcceptIntConsumer() { } @Test - void testAcceptLongConsumer() { + public void testAcceptLongConsumer() { final Testable testable = new Testable<>(ILLEGAL_STATE_EXCEPTION); Throwable e = assertThrows(IllegalStateException.class, () -> Failable.accept(testable::testLong, 1L)); assertSame(ILLEGAL_STATE_EXCEPTION, e); @@ -386,7 +386,7 @@ void testAcceptLongConsumer() { } @Test - void testAcceptObjDoubleConsumer() { + public void testAcceptObjDoubleConsumer() { final Testable testable = new Testable<>(ILLEGAL_STATE_EXCEPTION); Throwable e = assertThrows(IllegalStateException.class, () -> Failable.accept(testable::testObjDouble, "X", 1d)); @@ -416,7 +416,7 @@ void testAcceptObjDoubleConsumer() { } @Test - void testAcceptObjIntConsumer() { + public void testAcceptObjIntConsumer() { final Testable testable = new Testable<>(ILLEGAL_STATE_EXCEPTION); Throwable e = assertThrows(IllegalStateException.class, () -> Failable.accept(testable::testObjInt, "X", 1)); assertSame(ILLEGAL_STATE_EXCEPTION, e); @@ -445,7 +445,7 @@ void testAcceptObjIntConsumer() { } @Test - void testAcceptObjLongConsumer() { + public void testAcceptObjLongConsumer() { final Testable testable = new Testable<>(ILLEGAL_STATE_EXCEPTION); Throwable e = assertThrows(IllegalStateException.class, () -> Failable.accept(testable::testObjLong, "X", 1L)); assertSame(ILLEGAL_STATE_EXCEPTION, e); @@ -531,7 +531,7 @@ public void testApplyFunction() { } @Test - void testAsCallable() { + public void testAsCallable() { FailureOnOddInvocations.invocations = 0; final FailableCallable failableCallable = FailureOnOddInvocations::new; final Callable callable = Failable.asCallable(failableCallable); @@ -550,7 +550,7 @@ void testAsCallable() { } @Test - void testAsConsumer() { + public void testAsConsumer() { final Testable testable = new Testable<>(ILLEGAL_STATE_EXCEPTION); final Consumer> consumer = Failable.asConsumer(Testable::test); Throwable e = assertThrows(IllegalStateException.class, () -> consumer.accept(testable)); @@ -572,7 +572,7 @@ void testAsConsumer() { } @Test - void testAsRunnable() { + public void testAsRunnable() { FailureOnOddInvocations.invocations = 0; final Runnable runnable = Failable.asRunnable(FailureOnOddInvocations::new); final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, runnable::run); @@ -599,7 +599,7 @@ public void testAsSupplier() { } @Test - void testBiConsumer() throws Throwable { + public void testBiConsumer() throws Throwable { final Testable testable = new Testable<>(null); final FailableBiConsumer, Throwable, Throwable> failableBiConsumer = (t, th) -> { t.setThrowable(th); @@ -627,7 +627,7 @@ void testBiConsumer() throws Throwable { } @Test - void testBiConsumerAndThen() throws Throwable { + public void testBiConsumerAndThen() throws Throwable { final Testable testable = new Testable<>(null); final FailableBiConsumer, Throwable, Throwable> failableBiConsumer = (t, th) -> { t.setThrowable(th); @@ -710,7 +710,7 @@ public void testBiPredicate() { } @Test - void testCallable() { + public void testCallable() { FailureOnOddInvocations.invocations = 0; final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, () -> Failable.run(FailureOnOddInvocations::new)); @@ -729,6 +729,23 @@ public void testConstructor() { new Functions(); } + @Test + public void testConsumerAndThen() throws Throwable { + final Testable testable = new Testable<>(null); + final FailableConsumer failableConsumer = (th) -> { + testable.setThrowable(th); + testable.test(); + }; + final FailableConsumer nop = FailableConsumer.nop(); + final Throwable e = assertThrows(OutOfMemoryError.class, + () -> nop.andThen(failableConsumer).accept(ERROR)); + assertSame(ERROR, e); + // Does not throw + nop.andThen(nop); + // Documented in Javadoc edge-case. + assertThrows(NullPointerException.class, () -> failableConsumer.andThen(null)); + } + @Test public void testDoublePredicate() throws Throwable { FailureOnOddInvocations.invocations = 0; @@ -920,7 +937,7 @@ public void testPredicate() { } @Test - void testRunnable() { + public void testRunnable() { FailureOnOddInvocations.invocations = 0; final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, () -> Failable.run(FailureOnOddInvocations::new)); @@ -938,7 +955,7 @@ void testRunnable() { * Object and Throwable. */ @Test - void testThrows_FailableBiConsumer_Object_Throwable() { + public void testThrows_FailableBiConsumer_Object_Throwable() { new FailableBiConsumer() { @Override @@ -953,7 +970,7 @@ public void accept(final Object object1, final Object object2) throws Throwable * generic test types. */ @Test - void testThrows_FailableBiConsumer_String_IOException() { + public void testThrows_FailableBiConsumer_String_IOException() { new FailableBiConsumer() { @Override @@ -969,7 +986,7 @@ public void accept(final String object1, final String object2) throws IOExceptio * Object and Throwable. */ @Test - void testThrows_FailableBiFunction_Object_Throwable() { + public void testThrows_FailableBiFunction_Object_Throwable() { new FailableBiFunction() { @Override @@ -984,7 +1001,7 @@ public Object apply(final Object input1, final Object input2) throws Throwable { * generic test types. */ @Test - void testThrows_FailableBiFunction_String_IOException() { + public void testThrows_FailableBiFunction_String_IOException() { new FailableBiFunction() { @Override @@ -999,7 +1016,7 @@ public String apply(final String input1, final String input2) throws IOException * Object and Throwable. */ @Test - void testThrows_FailableBiPredicate_Object_Throwable() { + public void testThrows_FailableBiPredicate_Object_Throwable() { new FailableBiPredicate() { @Override @@ -1014,7 +1031,7 @@ public boolean test(final Object object1, final Object object2) throws Throwable * generic test types. */ @Test - void testThrows_FailableBiPredicate_String_IOException() { + public void testThrows_FailableBiPredicate_String_IOException() { new FailableBiPredicate() { @Override @@ -1061,7 +1078,7 @@ public boolean getAsBoolean() throws IOException { * Object and Throwable. */ @Test - void testThrows_FailableCallable_Object_Throwable() { + public void testThrows_FailableCallable_Object_Throwable() { new FailableCallable() { @Override @@ -1076,7 +1093,7 @@ public Object call() throws Throwable { * generic test types. */ @Test - void testThrows_FailableCallable_String_IOException() { + public void testThrows_FailableCallable_String_IOException() { new FailableCallable() { @Override @@ -1091,7 +1108,7 @@ public String call() throws IOException { * Object and Throwable. */ @Test - void testThrows_FailableConsumer_Object_Throwable() { + public void testThrows_FailableConsumer_Object_Throwable() { new FailableConsumer() { @Override @@ -1107,7 +1124,7 @@ public void accept(final Object object) throws Throwable { * generic test types. */ @Test - void testThrows_FailableConsumer_String_IOException() { + public void testThrows_FailableConsumer_String_IOException() { new FailableConsumer() { @Override From d4ccd259d95ed8f1e2a7c2526cdec64692ca0ac9 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Wed, 24 Jun 2020 20:10:46 -0400 Subject: [PATCH 0210/3230] [LANG-1568] More checked andThen() implementations to mirror the JRE functional interfaces. --- .../lang3/function/FailableBiConsumer.java | 2 +- .../lang3/function/FailableBiFunction.java | 4 +- .../lang3/function/FailableConsumer.java | 2 +- .../function/FailableDoubleConsumer.java | 31 +++++++ .../function/FailableDoubleFunction.java | 15 ++++ .../function/FailableDoubleToIntFunction.java | 14 +++ .../FailableDoubleToLongFunction.java | 14 +++ .../lang3/function/FailableFunction.java | 16 ++++ .../lang3/function/FailableIntConsumer.java | 32 +++++++ .../lang3/function/FailableIntFunction.java | 15 ++++ .../function/FailableIntToDoubleFunction.java | 14 +++ .../function/FailableIntToLongFunction.java | 14 +++ .../lang3/function/FailableLongConsumer.java | 31 +++++++ .../lang3/function/FailableLongFunction.java | 15 ++++ .../FailableLongToDoubleFunction.java | 14 +++ .../function/FailableLongToIntFunction.java | 14 +++ .../function/FailableObjDoubleConsumer.java | 16 +++- .../function/FailableObjIntConsumer.java | 14 +++ .../function/FailableObjLongConsumer.java | 14 +++ .../function/FailableToDoubleBiFunction.java | 16 ++++ .../function/FailableToDoubleFunction.java | 17 +++- .../function/FailableToIntBiFunction.java | 16 ++++ .../lang3/function/FailableToIntFunction.java | 17 +++- .../function/FailableToLongBiFunction.java | 16 ++++ .../function/FailableToLongFunction.java | 15 ++++ .../lang3/function/FailableFunctionsTest.java | 88 +++++++++++++++++-- 26 files changed, 462 insertions(+), 14 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/function/FailableBiConsumer.java b/src/main/java/org/apache/commons/lang3/function/FailableBiConsumer.java index 6d5d99f5ffd..10c6d808b34 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableBiConsumer.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableBiConsumer.java @@ -61,8 +61,8 @@ static FailableBiConsumer nop() { * * @param after the operation to perform after this one. * @return a composed {@code FailableBiConsumer} like {@link BiConsumer#andThen(BiConsumer)}. + * @throws NullPointerException when {@code after} is null. * @throws E Thrown when a consumer fails. - * @throws NullPointerException if {@code after} is null. */ default FailableBiConsumer andThen(final FailableBiConsumer after) throws E { Objects.requireNonNull(after); diff --git a/src/main/java/org/apache/commons/lang3/function/FailableBiFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableBiFunction.java index 3173c73b781..f6dc750d957 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableBiFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableBiFunction.java @@ -53,11 +53,11 @@ static FailableBiFunction nop() { /** * Returns a composed {@code FailableBiFunction} that like {@link BiFunction#andThen(Function)}. * - * @param the type of output of the {@code after} function, and of the composed function + * @param the output type of the {@code after} function, and of the composed function. * @param after the operation to perform after this one. * @return a composed {@code FailableBiFunction} that like {@link BiFunction#andThen(Function)}. + * @throws NullPointerException when {@code after} is null. * @throws E Thrown when a consumer fails. - * @throws NullPointerException if {@code after} is null. */ default FailableBiFunction andThen(final FailableFunction after) throws E { Objects.requireNonNull(after); diff --git a/src/main/java/org/apache/commons/lang3/function/FailableConsumer.java b/src/main/java/org/apache/commons/lang3/function/FailableConsumer.java index c2f2de8a909..97b7e4fdbaf 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableConsumer.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableConsumer.java @@ -58,8 +58,8 @@ static FailableConsumer nop() { * * @param after the operation to perform after this operation * @return a composed {@code Consumer} like {@link Consumer#andThen(Consumer)}. + * @throws NullPointerException when {@code after} is null * @throws E Thrown when a consumer fails. - * @throws NullPointerException if {@code after} is null */ default FailableConsumer andThen(final FailableConsumer after) throws E { Objects.requireNonNull(after); diff --git a/src/main/java/org/apache/commons/lang3/function/FailableDoubleConsumer.java b/src/main/java/org/apache/commons/lang3/function/FailableDoubleConsumer.java index 9b70da82a4c..f91a23bd7c1 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableDoubleConsumer.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableDoubleConsumer.java @@ -17,6 +17,7 @@ package org.apache.commons.lang3.function; +import java.util.Objects; import java.util.function.DoubleConsumer; /** @@ -28,6 +29,20 @@ @FunctionalInterface public interface FailableDoubleConsumer { + /** NOP singleton */ + @SuppressWarnings("rawtypes") + final FailableDoubleConsumer NOP = t -> {/* NOP */}; + + /** + * Returns The NOP singleton. + * + * @param Thrown exception. + * @return The NOP singleton. + */ + static FailableDoubleConsumer nop() { + return NOP; + } + /** * Accepts the consumer. * @@ -35,4 +50,20 @@ public interface FailableDoubleConsumer { * @throws E Thrown when the consumer fails. */ void accept(double value) throws E; + + /** + * Returns a composed {@code FailableDoubleConsumer} like {@link DoubleConsumer#andThen(DoubleConsumer)}. + * + * @param after the operation to perform after this one. + * @return a composed {@code FailableDoubleConsumer} like {@link DoubleConsumer#andThen(DoubleConsumer)}. + * @throws NullPointerException when {@code after} is null. + * @throws E Thrown when a consumer fails. + */ + default FailableDoubleConsumer andThen(final FailableDoubleConsumer after) throws E { + Objects.requireNonNull(after); + return (final double t) -> { + accept(t); + after.accept(t); + }; + } } diff --git a/src/main/java/org/apache/commons/lang3/function/FailableDoubleFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableDoubleFunction.java index 175a05e8530..6eea25f716d 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableDoubleFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableDoubleFunction.java @@ -29,6 +29,21 @@ @FunctionalInterface public interface FailableDoubleFunction { + /** NOP singleton */ + @SuppressWarnings("rawtypes") + final FailableDoubleFunction NOP = t -> null; + + /** + * Returns The NOP singleton. + * + * @param Return type. + * @param Thrown exception. + * @return The NOP singleton. + */ + static FailableDoubleFunction nop() { + return NOP; + } + /** * Applies this function. * diff --git a/src/main/java/org/apache/commons/lang3/function/FailableDoubleToIntFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableDoubleToIntFunction.java index eb9e9405fca..a8cef785b4a 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableDoubleToIntFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableDoubleToIntFunction.java @@ -28,6 +28,20 @@ @FunctionalInterface public interface FailableDoubleToIntFunction { + /** NOP singleton */ + @SuppressWarnings("rawtypes") + final FailableDoubleToIntFunction NOP = t -> 0; + + /** + * Returns The NOP singleton. + * + * @param Thrown exception. + * @return The NOP singleton. + */ + static FailableDoubleToIntFunction nop() { + return NOP; + } + /** * Applies this function to the given argument. * diff --git a/src/main/java/org/apache/commons/lang3/function/FailableDoubleToLongFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableDoubleToLongFunction.java index 2a5b0ff1566..003b2be655c 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableDoubleToLongFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableDoubleToLongFunction.java @@ -28,6 +28,20 @@ @FunctionalInterface public interface FailableDoubleToLongFunction { + /** NOP singleton */ + @SuppressWarnings("rawtypes") + final FailableDoubleToLongFunction NOP = t -> 0; + + /** + * Returns The NOP singleton. + * + * @param Thrown exception. + * @return The NOP singleton. + */ + static FailableDoubleToLongFunction nop() { + return NOP; + } + /** * Applies this function to the given argument. * diff --git a/src/main/java/org/apache/commons/lang3/function/FailableFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableFunction.java index 3d4b905b630..53e4314ca7c 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableFunction.java @@ -17,6 +17,7 @@ package org.apache.commons.lang3.function; +import java.util.Objects; import java.util.function.Function; /** @@ -46,6 +47,20 @@ static FailableFunction nop() { return NOP; } + /** + * Returns a composed {@code FailableFunction} like {@link Function#andThen(Function)}. + * + * @param the output type of the {@code after} function, and of the composed function. + * @return a composed {@code FailableFunction} like {@link Function#andThen(Function)}. + * @param after the operation to perform after this one. + * @throws NullPointerException when {@code after} is null. + * @throws E Thrown when a consumer fails. + */ + default FailableFunction andThen(final FailableFunction after) throws E { + Objects.requireNonNull(after); + return (final T t) -> after.apply(apply(t)); + } + /** * Applies this function. * @@ -54,4 +69,5 @@ static FailableFunction nop() { * @throws E Thrown when the function fails. */ R apply(T input) throws E; + } diff --git a/src/main/java/org/apache/commons/lang3/function/FailableIntConsumer.java b/src/main/java/org/apache/commons/lang3/function/FailableIntConsumer.java index 506cb67e60f..4f508b9c27d 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableIntConsumer.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableIntConsumer.java @@ -17,6 +17,7 @@ package org.apache.commons.lang3.function; +import java.util.Objects; import java.util.function.IntConsumer; /** @@ -28,6 +29,20 @@ @FunctionalInterface public interface FailableIntConsumer { + /** NOP singleton */ + @SuppressWarnings("rawtypes") + final FailableIntConsumer NOP = t -> {/* NOP */}; + + /** + * Returns The NOP singleton. + * + * @param Thrown exception. + * @return The NOP singleton. + */ + static FailableIntConsumer nop() { + return NOP; + } + /** * Accepts the consumer. * @@ -35,4 +50,21 @@ public interface FailableIntConsumer { * @throws E Thrown when the consumer fails. */ void accept(int value) throws E; + + /** + * Returns a composed {@code FailableIntConsumer} like {@link IntConsumer#andThen(IntConsumer)}. + * + * @param after the operation to perform after this one. + * @return a composed {@code FailableLongConsumer} like {@link IntConsumer#andThen(IntConsumer)}. + * @throws NullPointerException if {@code after} is null + * @throws E Thrown when a consumer fails. + */ + default FailableIntConsumer andThen(final FailableIntConsumer after) throws E { + Objects.requireNonNull(after); + return (final int t) -> { + accept(t); + after.accept(t); + }; + } + } diff --git a/src/main/java/org/apache/commons/lang3/function/FailableIntFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableIntFunction.java index 7c2d0bcabf5..a41bcbbd58f 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableIntFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableIntFunction.java @@ -29,6 +29,21 @@ @FunctionalInterface public interface FailableIntFunction { + /** NOP singleton */ + @SuppressWarnings("rawtypes") + final FailableIntFunction NOP = t -> null; + + /** + * Returns The NOP singleton. + * + * @param Return type. + * @param Thrown exception. + * @return The NOP singleton. + */ + static FailableIntFunction nop() { + return NOP; + } + /** * Applies this function. * diff --git a/src/main/java/org/apache/commons/lang3/function/FailableIntToDoubleFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableIntToDoubleFunction.java index 93afd897985..6f6c8f455ba 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableIntToDoubleFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableIntToDoubleFunction.java @@ -28,6 +28,20 @@ @FunctionalInterface public interface FailableIntToDoubleFunction { + /** NOP singleton */ + @SuppressWarnings("rawtypes") + final FailableIntToDoubleFunction NOP = t -> 0d; + + /** + * Returns The NOP singleton. + * + * @param Thrown exception. + * @return The NOP singleton. + */ + static FailableIntToDoubleFunction nop() { + return NOP; + } + /** * Applies this function to the given argument. * diff --git a/src/main/java/org/apache/commons/lang3/function/FailableIntToLongFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableIntToLongFunction.java index de23ae738d0..2afd4a2cebc 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableIntToLongFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableIntToLongFunction.java @@ -28,6 +28,20 @@ @FunctionalInterface public interface FailableIntToLongFunction { + /** NOP singleton */ + @SuppressWarnings("rawtypes") + final FailableIntToLongFunction NOP = t -> 0L; + + /** + * Returns The NOP singleton. + * + * @param Thrown exception. + * @return The NOP singleton. + */ + static FailableIntToLongFunction nop() { + return NOP; + } + /** * Applies this function to the given argument. * diff --git a/src/main/java/org/apache/commons/lang3/function/FailableLongConsumer.java b/src/main/java/org/apache/commons/lang3/function/FailableLongConsumer.java index 0565ff3b78d..a185ff6b5ff 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableLongConsumer.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableLongConsumer.java @@ -17,6 +17,7 @@ package org.apache.commons.lang3.function; +import java.util.Objects; import java.util.function.LongConsumer; /** @@ -28,6 +29,20 @@ @FunctionalInterface public interface FailableLongConsumer { + /** NOP singleton */ + @SuppressWarnings("rawtypes") + final FailableLongConsumer NOP = t -> {/* NOP */}; + + /** + * Returns The NOP singleton. + * + * @param Thrown exception. + * @return The NOP singleton. + */ + static FailableLongConsumer nop() { + return NOP; + } + /** * Accepts the consumer. * @@ -35,4 +50,20 @@ public interface FailableLongConsumer { * @throws E Thrown when the consumer fails. */ void accept(long object) throws E; + + /** + * Returns a composed {@code FailableLongConsumer} like {@link LongConsumer#andThen(LongConsumer)}. + * + * @param after the operation to perform after this one. + * @return a composed {@code FailableLongConsumer} like {@link LongConsumer#andThen(LongConsumer)}. + * @throws NullPointerException if {@code after} is null + * @throws E Thrown when a consumer fails. + */ + default FailableLongConsumer andThen(final FailableLongConsumer after) throws E { + Objects.requireNonNull(after); + return (final long t) -> { + accept(t); + after.accept(t); + }; + } } diff --git a/src/main/java/org/apache/commons/lang3/function/FailableLongFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableLongFunction.java index 2811e741197..2d3afae932a 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableLongFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableLongFunction.java @@ -29,6 +29,21 @@ @FunctionalInterface public interface FailableLongFunction { + /** NOP singleton */ + @SuppressWarnings("rawtypes") + final FailableLongFunction NOP = t -> null; + + /** + * Returns The NOP singleton. + * + * @param Return type. + * @param Thrown exception. + * @return The NOP singleton. + */ + static FailableLongFunction nop() { + return NOP; + } + /** * Applies this function. * diff --git a/src/main/java/org/apache/commons/lang3/function/FailableLongToDoubleFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableLongToDoubleFunction.java index b272c9d0a2f..13451fa09c6 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableLongToDoubleFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableLongToDoubleFunction.java @@ -28,6 +28,20 @@ @FunctionalInterface public interface FailableLongToDoubleFunction { + /** NOP singleton */ + @SuppressWarnings("rawtypes") + final FailableLongToDoubleFunction NOP = t -> 0d; + + /** + * Returns The NOP singleton. + * + * @param Thrown exception. + * @return The NOP singleton. + */ + static FailableLongToDoubleFunction nop() { + return NOP; + } + /** * Applies this function to the given argument. * diff --git a/src/main/java/org/apache/commons/lang3/function/FailableLongToIntFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableLongToIntFunction.java index 1066c3c2c6a..9c9b604185a 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableLongToIntFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableLongToIntFunction.java @@ -28,6 +28,20 @@ @FunctionalInterface public interface FailableLongToIntFunction { + /** NOP singleton */ + @SuppressWarnings("rawtypes") + final FailableLongToIntFunction NOP = t -> 0; + + /** + * Returns The NOP singleton. + * + * @param Thrown exception. + * @return The NOP singleton. + */ + static FailableLongToIntFunction nop() { + return NOP; + } + /** * Applies this function to the given argument. * diff --git a/src/main/java/org/apache/commons/lang3/function/FailableObjDoubleConsumer.java b/src/main/java/org/apache/commons/lang3/function/FailableObjDoubleConsumer.java index 105c8746280..866ed0ed4b8 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableObjDoubleConsumer.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableObjDoubleConsumer.java @@ -29,11 +29,25 @@ @FunctionalInterface public interface FailableObjDoubleConsumer { + /** NOP singleton */ + @SuppressWarnings("rawtypes") + final FailableObjDoubleConsumer NOP = (t, u) -> {/* NOP */}; + + /** + * Returns The NOP singleton. + * + * @param Thrown exception. + * @return The NOP singleton. + */ + static FailableObjDoubleConsumer nop() { + return NOP; + } + /** * Accepts the consumer. * * @param object the object parameter for the consumable to accept. - * @param value the double parameter for the consumable to accept. + * @param value the double parameter for the consumable to accept. * @throws E Thrown when the consumer fails. */ void accept(T object, double value) throws E; diff --git a/src/main/java/org/apache/commons/lang3/function/FailableObjIntConsumer.java b/src/main/java/org/apache/commons/lang3/function/FailableObjIntConsumer.java index 71c89252a34..c485c6cebc3 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableObjIntConsumer.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableObjIntConsumer.java @@ -29,6 +29,20 @@ @FunctionalInterface public interface FailableObjIntConsumer { + /** NOP singleton */ + @SuppressWarnings("rawtypes") + final FailableObjIntConsumer NOP = (t, u) -> {/* NOP */}; + + /** + * Returns The NOP singleton. + * + * @param Thrown exception. + * @return The NOP singleton. + */ + static FailableObjIntConsumer nop() { + return NOP; + } + /** * Accepts the consumer. * diff --git a/src/main/java/org/apache/commons/lang3/function/FailableObjLongConsumer.java b/src/main/java/org/apache/commons/lang3/function/FailableObjLongConsumer.java index b84b4d7a3ac..bbfa2f8eac3 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableObjLongConsumer.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableObjLongConsumer.java @@ -29,6 +29,20 @@ @FunctionalInterface public interface FailableObjLongConsumer { + /** NOP singleton */ + @SuppressWarnings("rawtypes") + final FailableObjLongConsumer NOP = (t, u) -> {/* NOP */}; + + /** + * Returns The NOP singleton. + * + * @param Thrown exception. + * @return The NOP singleton. + */ + static FailableObjLongConsumer nop() { + return NOP; + } + /** * Accepts the consumer. * diff --git a/src/main/java/org/apache/commons/lang3/function/FailableToDoubleBiFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableToDoubleBiFunction.java index 4ac14bd57e4..6da46b46c37 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableToDoubleBiFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableToDoubleBiFunction.java @@ -30,6 +30,22 @@ @FunctionalInterface public interface FailableToDoubleBiFunction { + /** NOP singleton */ + @SuppressWarnings("rawtypes") + final FailableToDoubleBiFunction NOP = (t, u) -> 0d; + + /** + * Returns The NOP singleton. + * + * @param the type of the first argument to the function + * @param the type of the second argument to the function + * @param Thrown exception. + * @return The NOP singleton. + */ + static FailableToDoubleBiFunction nop() { + return NOP; + } + /** * Applies this function to the given arguments. * diff --git a/src/main/java/org/apache/commons/lang3/function/FailableToDoubleFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableToDoubleFunction.java index 43feba59010..254842375df 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableToDoubleFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableToDoubleFunction.java @@ -22,13 +22,28 @@ /** * A functional interface like {@link ToDoubleFunction} that declares a {@code Throwable}. * - * @param the type of the first argument to the function + * @param the type of the argument to the function * @param Thrown exception. * @since 3.11 */ @FunctionalInterface public interface FailableToDoubleFunction { + /** NOP singleton */ + @SuppressWarnings("rawtypes") + final FailableToDoubleFunction NOP = t -> 0d; + + /** + * Returns The NOP singleton. + * + * @param the type of the argument to the function + * @param Thrown exception. + * @return The NOP singleton. + */ + static FailableToDoubleFunction nop() { + return NOP; + } + /** * Applies this function to the given arguments. * diff --git a/src/main/java/org/apache/commons/lang3/function/FailableToIntBiFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableToIntBiFunction.java index 1b7c3e2df51..650a7f6fea0 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableToIntBiFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableToIntBiFunction.java @@ -30,6 +30,22 @@ @FunctionalInterface public interface FailableToIntBiFunction { + /** NOP singleton */ + @SuppressWarnings("rawtypes") + final FailableToIntBiFunction NOP = (t, u) -> 0; + + /** + * Returns The NOP singleton. + * + * @param the type of the first argument to the function + * @param the type of the second argument to the function + * @param Thrown exception. + * @return The NOP singleton. + */ + static FailableToIntBiFunction nop() { + return NOP; + } + /** * Applies this function to the given arguments. * diff --git a/src/main/java/org/apache/commons/lang3/function/FailableToIntFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableToIntFunction.java index 1bba1c92225..1e51e45ae13 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableToIntFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableToIntFunction.java @@ -22,13 +22,28 @@ /** * A functional interface like {@link ToIntFunction} that declares a {@code Throwable}. * - * @param the type of the first argument to the function + * @param the type of the argument to the function * @param Thrown exception. * @since 3.11 */ @FunctionalInterface public interface FailableToIntFunction { + /** NOP singleton */ + @SuppressWarnings("rawtypes") + final FailableToIntFunction NOP = t -> 0; + + /** + * Returns The NOP singleton. + * + * @param the type of the argument to the function + * @param Thrown exception. + * @return The NOP singleton. + */ + static FailableToIntFunction nop() { + return NOP; + } + /** * Applies this function to the given arguments. * diff --git a/src/main/java/org/apache/commons/lang3/function/FailableToLongBiFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableToLongBiFunction.java index e49347ffc7a..62eca3c1627 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableToLongBiFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableToLongBiFunction.java @@ -30,6 +30,22 @@ @FunctionalInterface public interface FailableToLongBiFunction { + /** NOP singleton */ + @SuppressWarnings("rawtypes") + final FailableToLongBiFunction NOP = (t, u) -> 0; + + /** + * Returns The NOP singleton. + * + * @param the type of the first argument to the function + * @param the type of the second argument to the function + * @param Thrown exception. + * @return The NOP singleton. + */ + static FailableToLongBiFunction nop() { + return NOP; + } + /** * Applies this function to the given arguments. * diff --git a/src/main/java/org/apache/commons/lang3/function/FailableToLongFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableToLongFunction.java index 5b790af5b06..af90c937206 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableToLongFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableToLongFunction.java @@ -29,6 +29,21 @@ @FunctionalInterface public interface FailableToLongFunction { + /** NOP singleton */ + @SuppressWarnings("rawtypes") + final FailableToLongFunction NOP = t -> 0L; + + /** + * Returns The NOP singleton. + * + * @param the type of the argument to the function + * @param Thrown exception. + * @return The NOP singleton. + */ + static FailableToLongFunction nop() { + return NOP; + } + /** * Applies this function to the given arguments. * diff --git a/src/test/java/org/apache/commons/lang3/function/FailableFunctionsTest.java b/src/test/java/org/apache/commons/lang3/function/FailableFunctionsTest.java index 24a1054cd01..da36ebda7c6 100644 --- a/src/test/java/org/apache/commons/lang3/function/FailableFunctionsTest.java +++ b/src/test/java/org/apache/commons/lang3/function/FailableFunctionsTest.java @@ -66,6 +66,7 @@ public void run(final Throwable pTh) throws Throwable { } } } + public static class FailureOnOddInvocations { private static int invocations; @@ -629,18 +630,19 @@ public void testBiConsumer() throws Throwable { @Test public void testBiConsumerAndThen() throws Throwable { final Testable testable = new Testable<>(null); - final FailableBiConsumer, Throwable, Throwable> failableBiConsumer = (t, th) -> { + final FailableBiConsumer, Throwable, Throwable> failing = (t, th) -> { t.setThrowable(th); t.test(); }; final FailableBiConsumer, Throwable, Throwable> nop = FailableBiConsumer.nop(); - final Throwable e = assertThrows(OutOfMemoryError.class, - () -> nop.andThen(failableBiConsumer).accept(testable, ERROR)); + Throwable e = assertThrows(OutOfMemoryError.class, () -> nop.andThen(failing).accept(testable, ERROR)); + assertSame(ERROR, e); + e = assertThrows(OutOfMemoryError.class, () -> failing.andThen(nop).accept(testable, ERROR)); assertSame(ERROR, e); // Does not throw nop.andThen(nop); // Documented in Javadoc edge-case. - assertThrows(NullPointerException.class, () -> failableBiConsumer.andThen(null)); + assertThrows(NullPointerException.class, () -> failing.andThen(null)); } @Test @@ -680,7 +682,8 @@ public void testBiFunctionAndThen() throws IOException { throw new IOException(); }; final FailableFunction failingFunction = (t) -> { throw new IOException(); }; - final FailableBiFunction nopFailableBiFunction = FailableBiFunction.nop(); + final FailableBiFunction nopFailableBiFunction = FailableBiFunction + .nop(); final FailableFunction nopFailableFunction = FailableFunction.nop(); // assertThrows(IOException.class, () -> failingBiFunctionTest.andThen(failingFunction).apply(null, null)); @@ -737,8 +740,7 @@ public void testConsumerAndThen() throws Throwable { testable.test(); }; final FailableConsumer nop = FailableConsumer.nop(); - final Throwable e = assertThrows(OutOfMemoryError.class, - () -> nop.andThen(failableConsumer).accept(ERROR)); + final Throwable e = assertThrows(OutOfMemoryError.class, () -> nop.andThen(failableConsumer).accept(ERROR)); assertSame(ERROR, e); // Does not throw nop.andThen(nop); @@ -746,6 +748,24 @@ public void testConsumerAndThen() throws Throwable { assertThrows(NullPointerException.class, () -> failableConsumer.andThen(null)); } + @Test + public void testDoubleConsumerAndThen() throws Throwable { + final Testable testable = new Testable<>(null); + final FailableDoubleConsumer failing = t -> { + testable.setThrowable(ERROR); + testable.test(); + }; + final FailableDoubleConsumer nop = FailableDoubleConsumer.nop(); + Throwable e = assertThrows(OutOfMemoryError.class, () -> nop.andThen(failing).accept(0d)); + assertSame(ERROR, e); + e = assertThrows(OutOfMemoryError.class, () -> failing.andThen(nop).accept(0d)); + assertSame(ERROR, e); + // Does not throw + nop.andThen(nop); + // Documented in Javadoc edge-case. + assertThrows(NullPointerException.class, () -> failing.andThen(null)); + } + @Test public void testDoublePredicate() throws Throwable { FailureOnOddInvocations.invocations = 0; @@ -779,6 +799,24 @@ public void testFunction() { assertEquals(0, function.apply(null).intValue()); } + @Test + public void testFunctionAndThen() throws IOException { + // Unchecked usage pattern in JRE + final Function nopFunction = (t) -> null; + nopFunction.andThen(nopFunction); + // Checked usage pattern + final FailableFunction failingFunction = (t) -> { throw new IOException(); }; + final FailableFunction nopFailableFunction = FailableFunction.nop(); + // + assertThrows(IOException.class, () -> failingFunction.andThen(failingFunction).apply(null)); + assertThrows(IOException.class, () -> failingFunction.andThen(nopFailableFunction).apply(null)); + // + assertThrows(IOException.class, () -> nopFailableFunction.andThen(failingFunction).apply(null)); + nopFailableFunction.andThen(nopFailableFunction).apply(null); + // Documented in Javadoc edge-case. + assertThrows(NullPointerException.class, () -> failingFunction.andThen(null)); + } + @Test public void testGetAsBooleanSupplier() { final Testable testable = new Testable<>(ILLEGAL_STATE_EXCEPTION); @@ -904,6 +942,24 @@ public void testGetSupplier() { assertEquals(0, i.intValue()); } + @Test + public void testIntConsumerAndThen() throws Throwable { + final Testable testable = new Testable<>(null); + final FailableIntConsumer failing = t -> { + testable.setThrowable(ERROR); + testable.test(); + }; + final FailableIntConsumer nop = FailableIntConsumer.nop(); + Throwable e = assertThrows(OutOfMemoryError.class, () -> nop.andThen(failing).accept(0)); + assertSame(ERROR, e); + e = assertThrows(OutOfMemoryError.class, () -> failing.andThen(nop).accept(0)); + assertSame(ERROR, e); + // Does not throw + nop.andThen(nop); + // Documented in Javadoc edge-case. + assertThrows(NullPointerException.class, () -> failing.andThen(null)); + } + @Test public void testIntPredicate() throws Throwable { FailureOnOddInvocations.invocations = 0; @@ -912,6 +968,24 @@ public void testIntPredicate() throws Throwable { failablePredicate.test(1); } + @Test + public void testLongConsumerAndThen() throws Throwable { + final Testable testable = new Testable<>(null); + final FailableLongConsumer failing = t -> { + testable.setThrowable(ERROR); + testable.test(); + }; + final FailableLongConsumer nop = FailableLongConsumer.nop(); + Throwable e = assertThrows(OutOfMemoryError.class, () -> nop.andThen(failing).accept(0L)); + assertSame(ERROR, e); + e = assertThrows(OutOfMemoryError.class, () -> failing.andThen(nop).accept(0L)); + assertSame(ERROR, e); + // Does not throw + nop.andThen(nop); + // Documented in Javadoc edge-case. + assertThrows(NullPointerException.class, () -> failing.andThen(null)); + } + @Test public void testLongPredicate() throws Throwable { FailureOnOddInvocations.invocations = 0; From 97611fda5d134bc7f32533f7c11b9b2a3f4bf939 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Wed, 24 Jun 2020 20:28:44 -0400 Subject: [PATCH 0211/3230] [LANG-1568] Lambda clean ups. --- .../lang3/function/FailableFunctionsTest.java | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/test/java/org/apache/commons/lang3/function/FailableFunctionsTest.java b/src/test/java/org/apache/commons/lang3/function/FailableFunctionsTest.java index da36ebda7c6..3a123cf9074 100644 --- a/src/test/java/org/apache/commons/lang3/function/FailableFunctionsTest.java +++ b/src/test/java/org/apache/commons/lang3/function/FailableFunctionsTest.java @@ -675,13 +675,13 @@ public void testBiFunction() { public void testBiFunctionAndThen() throws IOException { // Unchecked usage pattern in JRE final BiFunction nopBiFunction = (t, u) -> null; - final Function nopFunction = (t) -> null; + final Function nopFunction = t -> null; nopBiFunction.andThen(nopFunction); // Checked usage pattern final FailableBiFunction failingBiFunctionTest = (t, u) -> { throw new IOException(); }; - final FailableFunction failingFunction = (t) -> { throw new IOException(); }; + final FailableFunction failingFunction = t -> { throw new IOException(); }; final FailableBiFunction nopFailableBiFunction = FailableBiFunction .nop(); final FailableFunction nopFailableFunction = FailableFunction.nop(); @@ -735,7 +735,7 @@ public void testConstructor() { @Test public void testConsumerAndThen() throws Throwable { final Testable testable = new Testable<>(null); - final FailableConsumer failableConsumer = (th) -> { + final FailableConsumer failableConsumer = th -> { testable.setThrowable(th); testable.test(); }; @@ -769,7 +769,7 @@ public void testDoubleConsumerAndThen() throws Throwable { @Test public void testDoublePredicate() throws Throwable { FailureOnOddInvocations.invocations = 0; - final FailableDoublePredicate failablePredicate = t1 -> FailureOnOddInvocations.testDouble(t1); + final FailableDoublePredicate failablePredicate = FailureOnOddInvocations::testDouble; assertThrows(SomeException.class, () -> failablePredicate.test(1d)); failablePredicate.test(1d); } @@ -802,10 +802,10 @@ public void testFunction() { @Test public void testFunctionAndThen() throws IOException { // Unchecked usage pattern in JRE - final Function nopFunction = (t) -> null; + final Function nopFunction = t -> null; nopFunction.andThen(nopFunction); // Checked usage pattern - final FailableFunction failingFunction = (t) -> { throw new IOException(); }; + final FailableFunction failingFunction = t -> { throw new IOException(); }; final FailableFunction nopFailableFunction = FailableFunction.nop(); // assertThrows(IOException.class, () -> failingFunction.andThen(failingFunction).apply(null)); @@ -963,7 +963,7 @@ public void testIntConsumerAndThen() throws Throwable { @Test public void testIntPredicate() throws Throwable { FailureOnOddInvocations.invocations = 0; - final FailableIntPredicate failablePredicate = t1 -> FailureOnOddInvocations.testInt(t1); + final FailableIntPredicate failablePredicate = FailureOnOddInvocations::testInt; assertThrows(SomeException.class, () -> failablePredicate.test(1)); failablePredicate.test(1); } @@ -989,7 +989,7 @@ public void testLongConsumerAndThen() throws Throwable { @Test public void testLongPredicate() throws Throwable { FailureOnOddInvocations.invocations = 0; - final FailableLongPredicate failablePredicate = t1 -> FailureOnOddInvocations.testLong(t1); + final FailableLongPredicate failablePredicate = FailureOnOddInvocations::testLong; assertThrows(SomeException.class, () -> failablePredicate.test(1L)); failablePredicate.test(1L); } From 5f2fa64137db3c492b97271e6aa42ffd5598c475 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Thu, 25 Jun 2020 08:46:50 -0400 Subject: [PATCH 0212/3230] Checktyle. --- .../org/apache/commons/lang3/function/FailableBiConsumer.java | 2 +- .../org/apache/commons/lang3/function/FailableBiFunction.java | 2 +- .../org/apache/commons/lang3/function/FailableConsumer.java | 2 +- .../apache/commons/lang3/function/FailableDoubleConsumer.java | 2 +- .../apache/commons/lang3/function/FailableDoubleFunction.java | 2 +- .../commons/lang3/function/FailableDoubleToIntFunction.java | 2 +- .../commons/lang3/function/FailableDoubleToLongFunction.java | 2 +- .../org/apache/commons/lang3/function/FailableFunction.java | 2 +- .../org/apache/commons/lang3/function/FailableIntConsumer.java | 2 +- .../org/apache/commons/lang3/function/FailableIntFunction.java | 2 +- .../commons/lang3/function/FailableIntToDoubleFunction.java | 2 +- .../commons/lang3/function/FailableIntToLongFunction.java | 2 +- .../org/apache/commons/lang3/function/FailableLongConsumer.java | 2 +- .../org/apache/commons/lang3/function/FailableLongFunction.java | 2 +- .../commons/lang3/function/FailableLongToDoubleFunction.java | 2 +- .../commons/lang3/function/FailableLongToIntFunction.java | 2 +- .../commons/lang3/function/FailableObjDoubleConsumer.java | 2 +- .../apache/commons/lang3/function/FailableObjIntConsumer.java | 2 +- .../apache/commons/lang3/function/FailableObjLongConsumer.java | 2 +- .../commons/lang3/function/FailableToDoubleBiFunction.java | 2 +- .../apache/commons/lang3/function/FailableToDoubleFunction.java | 2 +- .../apache/commons/lang3/function/FailableToIntBiFunction.java | 2 +- .../apache/commons/lang3/function/FailableToIntFunction.java | 2 +- .../apache/commons/lang3/function/FailableToLongBiFunction.java | 2 +- .../apache/commons/lang3/function/FailableToLongFunction.java | 2 +- 25 files changed, 25 insertions(+), 25 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/function/FailableBiConsumer.java b/src/main/java/org/apache/commons/lang3/function/FailableBiConsumer.java index 10c6d808b34..6589a4d7840 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableBiConsumer.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableBiConsumer.java @@ -33,7 +33,7 @@ public interface FailableBiConsumer { /** NOP singleton */ @SuppressWarnings("rawtypes") - final FailableBiConsumer NOP = (t, u) -> {/* NOP */}; + FailableBiConsumer NOP = (t, u) -> {/* NOP */}; /** * Returns The NOP singleton. diff --git a/src/main/java/org/apache/commons/lang3/function/FailableBiFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableBiFunction.java index f6dc750d957..15d1788f34e 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableBiFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableBiFunction.java @@ -35,7 +35,7 @@ public interface FailableBiFunction { /** NOP singleton */ @SuppressWarnings("rawtypes") - final FailableBiFunction NOP = (t, u) -> null; + FailableBiFunction NOP = (t, u) -> null; /** * Returns The NOP singleton. diff --git a/src/main/java/org/apache/commons/lang3/function/FailableConsumer.java b/src/main/java/org/apache/commons/lang3/function/FailableConsumer.java index 97b7e4fdbaf..3df422bf847 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableConsumer.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableConsumer.java @@ -32,7 +32,7 @@ public interface FailableConsumer { /** NOP singleton */ @SuppressWarnings("rawtypes") - final FailableConsumer NOP = t -> {/* NOP */}; + FailableConsumer NOP = t -> {/* NOP */}; /** * Returns The NOP singleton. diff --git a/src/main/java/org/apache/commons/lang3/function/FailableDoubleConsumer.java b/src/main/java/org/apache/commons/lang3/function/FailableDoubleConsumer.java index f91a23bd7c1..3b379198179 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableDoubleConsumer.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableDoubleConsumer.java @@ -31,7 +31,7 @@ public interface FailableDoubleConsumer { /** NOP singleton */ @SuppressWarnings("rawtypes") - final FailableDoubleConsumer NOP = t -> {/* NOP */}; + FailableDoubleConsumer NOP = t -> {/* NOP */}; /** * Returns The NOP singleton. diff --git a/src/main/java/org/apache/commons/lang3/function/FailableDoubleFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableDoubleFunction.java index 6eea25f716d..935c956f747 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableDoubleFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableDoubleFunction.java @@ -31,7 +31,7 @@ public interface FailableDoubleFunction { /** NOP singleton */ @SuppressWarnings("rawtypes") - final FailableDoubleFunction NOP = t -> null; + FailableDoubleFunction NOP = t -> null; /** * Returns The NOP singleton. diff --git a/src/main/java/org/apache/commons/lang3/function/FailableDoubleToIntFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableDoubleToIntFunction.java index a8cef785b4a..90f77b3e613 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableDoubleToIntFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableDoubleToIntFunction.java @@ -30,7 +30,7 @@ public interface FailableDoubleToIntFunction { /** NOP singleton */ @SuppressWarnings("rawtypes") - final FailableDoubleToIntFunction NOP = t -> 0; + FailableDoubleToIntFunction NOP = t -> 0; /** * Returns The NOP singleton. diff --git a/src/main/java/org/apache/commons/lang3/function/FailableDoubleToLongFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableDoubleToLongFunction.java index 003b2be655c..44120dccce0 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableDoubleToLongFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableDoubleToLongFunction.java @@ -30,7 +30,7 @@ public interface FailableDoubleToLongFunction { /** NOP singleton */ @SuppressWarnings("rawtypes") - final FailableDoubleToLongFunction NOP = t -> 0; + FailableDoubleToLongFunction NOP = t -> 0; /** * Returns The NOP singleton. diff --git a/src/main/java/org/apache/commons/lang3/function/FailableFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableFunction.java index 53e4314ca7c..cb100a4b22a 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableFunction.java @@ -33,7 +33,7 @@ public interface FailableFunction { /** NOP singleton */ @SuppressWarnings("rawtypes") - final FailableFunction NOP = t -> null; + FailableFunction NOP = t -> null; /** * Returns The NOP singleton. diff --git a/src/main/java/org/apache/commons/lang3/function/FailableIntConsumer.java b/src/main/java/org/apache/commons/lang3/function/FailableIntConsumer.java index 4f508b9c27d..64429df00ab 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableIntConsumer.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableIntConsumer.java @@ -31,7 +31,7 @@ public interface FailableIntConsumer { /** NOP singleton */ @SuppressWarnings("rawtypes") - final FailableIntConsumer NOP = t -> {/* NOP */}; + FailableIntConsumer NOP = t -> {/* NOP */}; /** * Returns The NOP singleton. diff --git a/src/main/java/org/apache/commons/lang3/function/FailableIntFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableIntFunction.java index a41bcbbd58f..9a39688b134 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableIntFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableIntFunction.java @@ -31,7 +31,7 @@ public interface FailableIntFunction { /** NOP singleton */ @SuppressWarnings("rawtypes") - final FailableIntFunction NOP = t -> null; + FailableIntFunction NOP = t -> null; /** * Returns The NOP singleton. diff --git a/src/main/java/org/apache/commons/lang3/function/FailableIntToDoubleFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableIntToDoubleFunction.java index 6f6c8f455ba..64e8c891465 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableIntToDoubleFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableIntToDoubleFunction.java @@ -30,7 +30,7 @@ public interface FailableIntToDoubleFunction { /** NOP singleton */ @SuppressWarnings("rawtypes") - final FailableIntToDoubleFunction NOP = t -> 0d; + FailableIntToDoubleFunction NOP = t -> 0d; /** * Returns The NOP singleton. diff --git a/src/main/java/org/apache/commons/lang3/function/FailableIntToLongFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableIntToLongFunction.java index 2afd4a2cebc..89eb311b9b1 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableIntToLongFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableIntToLongFunction.java @@ -30,7 +30,7 @@ public interface FailableIntToLongFunction { /** NOP singleton */ @SuppressWarnings("rawtypes") - final FailableIntToLongFunction NOP = t -> 0L; + FailableIntToLongFunction NOP = t -> 0L; /** * Returns The NOP singleton. diff --git a/src/main/java/org/apache/commons/lang3/function/FailableLongConsumer.java b/src/main/java/org/apache/commons/lang3/function/FailableLongConsumer.java index a185ff6b5ff..c2a0ca8a54f 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableLongConsumer.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableLongConsumer.java @@ -31,7 +31,7 @@ public interface FailableLongConsumer { /** NOP singleton */ @SuppressWarnings("rawtypes") - final FailableLongConsumer NOP = t -> {/* NOP */}; + FailableLongConsumer NOP = t -> {/* NOP */}; /** * Returns The NOP singleton. diff --git a/src/main/java/org/apache/commons/lang3/function/FailableLongFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableLongFunction.java index 2d3afae932a..a7501b45c93 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableLongFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableLongFunction.java @@ -31,7 +31,7 @@ public interface FailableLongFunction { /** NOP singleton */ @SuppressWarnings("rawtypes") - final FailableLongFunction NOP = t -> null; + FailableLongFunction NOP = t -> null; /** * Returns The NOP singleton. diff --git a/src/main/java/org/apache/commons/lang3/function/FailableLongToDoubleFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableLongToDoubleFunction.java index 13451fa09c6..9b7dc22b864 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableLongToDoubleFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableLongToDoubleFunction.java @@ -30,7 +30,7 @@ public interface FailableLongToDoubleFunction { /** NOP singleton */ @SuppressWarnings("rawtypes") - final FailableLongToDoubleFunction NOP = t -> 0d; + FailableLongToDoubleFunction NOP = t -> 0d; /** * Returns The NOP singleton. diff --git a/src/main/java/org/apache/commons/lang3/function/FailableLongToIntFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableLongToIntFunction.java index 9c9b604185a..a6866bbf455 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableLongToIntFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableLongToIntFunction.java @@ -30,7 +30,7 @@ public interface FailableLongToIntFunction { /** NOP singleton */ @SuppressWarnings("rawtypes") - final FailableLongToIntFunction NOP = t -> 0; + FailableLongToIntFunction NOP = t -> 0; /** * Returns The NOP singleton. diff --git a/src/main/java/org/apache/commons/lang3/function/FailableObjDoubleConsumer.java b/src/main/java/org/apache/commons/lang3/function/FailableObjDoubleConsumer.java index 866ed0ed4b8..4d9860ef556 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableObjDoubleConsumer.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableObjDoubleConsumer.java @@ -31,7 +31,7 @@ public interface FailableObjDoubleConsumer { /** NOP singleton */ @SuppressWarnings("rawtypes") - final FailableObjDoubleConsumer NOP = (t, u) -> {/* NOP */}; + FailableObjDoubleConsumer NOP = (t, u) -> {/* NOP */}; /** * Returns The NOP singleton. diff --git a/src/main/java/org/apache/commons/lang3/function/FailableObjIntConsumer.java b/src/main/java/org/apache/commons/lang3/function/FailableObjIntConsumer.java index c485c6cebc3..893d60cc389 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableObjIntConsumer.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableObjIntConsumer.java @@ -31,7 +31,7 @@ public interface FailableObjIntConsumer { /** NOP singleton */ @SuppressWarnings("rawtypes") - final FailableObjIntConsumer NOP = (t, u) -> {/* NOP */}; + FailableObjIntConsumer NOP = (t, u) -> {/* NOP */}; /** * Returns The NOP singleton. diff --git a/src/main/java/org/apache/commons/lang3/function/FailableObjLongConsumer.java b/src/main/java/org/apache/commons/lang3/function/FailableObjLongConsumer.java index bbfa2f8eac3..8b72626c34e 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableObjLongConsumer.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableObjLongConsumer.java @@ -31,7 +31,7 @@ public interface FailableObjLongConsumer { /** NOP singleton */ @SuppressWarnings("rawtypes") - final FailableObjLongConsumer NOP = (t, u) -> {/* NOP */}; + FailableObjLongConsumer NOP = (t, u) -> {/* NOP */}; /** * Returns The NOP singleton. diff --git a/src/main/java/org/apache/commons/lang3/function/FailableToDoubleBiFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableToDoubleBiFunction.java index 6da46b46c37..a3a23a4afec 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableToDoubleBiFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableToDoubleBiFunction.java @@ -32,7 +32,7 @@ public interface FailableToDoubleBiFunction { /** NOP singleton */ @SuppressWarnings("rawtypes") - final FailableToDoubleBiFunction NOP = (t, u) -> 0d; + FailableToDoubleBiFunction NOP = (t, u) -> 0d; /** * Returns The NOP singleton. diff --git a/src/main/java/org/apache/commons/lang3/function/FailableToDoubleFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableToDoubleFunction.java index 254842375df..73aa6cee669 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableToDoubleFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableToDoubleFunction.java @@ -31,7 +31,7 @@ public interface FailableToDoubleFunction { /** NOP singleton */ @SuppressWarnings("rawtypes") - final FailableToDoubleFunction NOP = t -> 0d; + FailableToDoubleFunction NOP = t -> 0d; /** * Returns The NOP singleton. diff --git a/src/main/java/org/apache/commons/lang3/function/FailableToIntBiFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableToIntBiFunction.java index 650a7f6fea0..9bb3901da27 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableToIntBiFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableToIntBiFunction.java @@ -32,7 +32,7 @@ public interface FailableToIntBiFunction { /** NOP singleton */ @SuppressWarnings("rawtypes") - final FailableToIntBiFunction NOP = (t, u) -> 0; + FailableToIntBiFunction NOP = (t, u) -> 0; /** * Returns The NOP singleton. diff --git a/src/main/java/org/apache/commons/lang3/function/FailableToIntFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableToIntFunction.java index 1e51e45ae13..d95cb33b964 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableToIntFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableToIntFunction.java @@ -31,7 +31,7 @@ public interface FailableToIntFunction { /** NOP singleton */ @SuppressWarnings("rawtypes") - final FailableToIntFunction NOP = t -> 0; + FailableToIntFunction NOP = t -> 0; /** * Returns The NOP singleton. diff --git a/src/main/java/org/apache/commons/lang3/function/FailableToLongBiFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableToLongBiFunction.java index 62eca3c1627..64e6c6b811f 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableToLongBiFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableToLongBiFunction.java @@ -32,7 +32,7 @@ public interface FailableToLongBiFunction { /** NOP singleton */ @SuppressWarnings("rawtypes") - final FailableToLongBiFunction NOP = (t, u) -> 0; + FailableToLongBiFunction NOP = (t, u) -> 0; /** * Returns The NOP singleton. diff --git a/src/main/java/org/apache/commons/lang3/function/FailableToLongFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableToLongFunction.java index af90c937206..f04b0295756 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableToLongFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableToLongFunction.java @@ -31,7 +31,7 @@ public interface FailableToLongFunction { /** NOP singleton */ @SuppressWarnings("rawtypes") - final FailableToLongFunction NOP = t -> 0L; + FailableToLongFunction NOP = t -> 0L; /** * Returns The NOP singleton. From e12eb5d4d79398f4d3dab7a593efd767c59b74c6 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Thu, 25 Jun 2020 09:01:13 -0400 Subject: [PATCH 0213/3230] [LANG-1568] FailableDoubleUnaryOperator, FailableIntUnaryOperator, FailableLongUnaryOperator. --- .../function/FailableDoubleUnaryOperator.java | 94 +++++++++++ .../function/FailableIntUnaryOperator.java | 90 ++++++++++ .../function/FailableLongUnaryOperator.java | 90 ++++++++++ .../lang3/function/FailableFunctionsTest.java | 154 ++++++++++++++++-- 4 files changed, 417 insertions(+), 11 deletions(-) create mode 100644 src/main/java/org/apache/commons/lang3/function/FailableDoubleUnaryOperator.java create mode 100644 src/main/java/org/apache/commons/lang3/function/FailableIntUnaryOperator.java create mode 100644 src/main/java/org/apache/commons/lang3/function/FailableLongUnaryOperator.java diff --git a/src/main/java/org/apache/commons/lang3/function/FailableDoubleUnaryOperator.java b/src/main/java/org/apache/commons/lang3/function/FailableDoubleUnaryOperator.java new file mode 100644 index 00000000000..13978d947ad --- /dev/null +++ b/src/main/java/org/apache/commons/lang3/function/FailableDoubleUnaryOperator.java @@ -0,0 +1,94 @@ +/* + * 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.function; + +import java.util.Objects; +import java.util.function.DoubleUnaryOperator; + +/** + * A functional interface like {@link DoubleUnaryOperator} that declares a {@code Throwable}. + * + * @param Thrown exception. + * @since 3.11 + */ +public interface FailableDoubleUnaryOperator { + + /** NOP singleton */ + @SuppressWarnings("rawtypes") + FailableDoubleUnaryOperator NOP = t -> 0d; + + /** + * Returns a unary operator that always returns its input argument. + * + * @return a unary operator that always returns its input argument + */ + static FailableDoubleUnaryOperator identity() { + return t -> t; + } + + /** + * Returns The NOP singleton. + * + * @param Thrown exception. + * @return The NOP singleton. + */ + static FailableDoubleUnaryOperator nop() { + return NOP; + } + + /** + * Returns a composed {@code FailableDoubleUnaryOperator} like + * {@link DoubleUnaryOperator#andThen(DoubleUnaryOperator)}. + * + * @param after the operator to apply after this one. + * @return a composed {@code FailableDoubleUnaryOperator} like + * {@link DoubleUnaryOperator#andThen(DoubleUnaryOperator)}. + * @throws NullPointerException if after is null. + * @throws E Thrown when a consumer fails. + * @see #compose(FailableDoubleUnaryOperator) + */ + default FailableDoubleUnaryOperator andThen(FailableDoubleUnaryOperator after) throws E { + Objects.requireNonNull(after); + return (double t) -> after.applyAsDouble(applyAsDouble(t)); + } + + /** + * Applies this operator to the given operand. + * + * @param operand the operand + * @return the operator result + * @throws E Thrown when a consumer fails. + */ + double applyAsDouble(double operand) throws E; + + /** + * Returns a composed {@code FailableDoubleUnaryOperator} like + * {@link DoubleUnaryOperator#compose(DoubleUnaryOperator)}. + * + * @param before the operator to apply before this one. + * @return a composed {@code FailableDoubleUnaryOperator} like + * {@link DoubleUnaryOperator#compose(DoubleUnaryOperator)}. + * @throws NullPointerException if before is null. + * @throws E Thrown when a consumer fails. + * @see #andThen(FailableDoubleUnaryOperator) + */ + default FailableDoubleUnaryOperator compose(FailableDoubleUnaryOperator before) throws E { + Objects.requireNonNull(before); + return (double v) -> applyAsDouble(before.applyAsDouble(v)); + } +} diff --git a/src/main/java/org/apache/commons/lang3/function/FailableIntUnaryOperator.java b/src/main/java/org/apache/commons/lang3/function/FailableIntUnaryOperator.java new file mode 100644 index 00000000000..2fe71f119f2 --- /dev/null +++ b/src/main/java/org/apache/commons/lang3/function/FailableIntUnaryOperator.java @@ -0,0 +1,90 @@ +/* + * 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.function; + +import java.util.Objects; +import java.util.function.IntUnaryOperator; + +/** + * A functional interface like {@link IntUnaryOperator} that declares a {@code Throwable}. + * + * @param Thrown exception. + * @since 3.11 + */ +public interface FailableIntUnaryOperator { + + /** NOP singleton */ + @SuppressWarnings("rawtypes") + FailableIntUnaryOperator NOP = t -> 0; + + /** + * Returns a unary operator that always returns its input argument. + * + * @return a unary operator that always returns its input argument + */ + static FailableIntUnaryOperator identity() { + return t -> t; + } + + /** + * Returns The NOP singleton. + * + * @param Thrown exception. + * @return The NOP singleton. + */ + static FailableIntUnaryOperator nop() { + return NOP; + } + + /** + * Returns a composed {@code FailableDoubleUnaryOperator} like {@link IntUnaryOperator#andThen(IntUnaryOperator)}. + * + * @param after the operator to apply after this one. + * @return a composed {@code FailableIntUnaryOperator} like {@link IntUnaryOperator#andThen(IntUnaryOperator)}. + * @throws NullPointerException if after is null. + * @throws E Thrown when a consumer fails. + * @see #compose(FailableIntUnaryOperator) + */ + default FailableIntUnaryOperator andThen(FailableIntUnaryOperator after) throws E { + Objects.requireNonNull(after); + return (int t) -> after.applyAsInt(applyAsInt(t)); + } + + /** + * Applies this operator to the given operand. + * + * @param operand the operand + * @return the operator result + * @throws E Thrown when a consumer fails. + */ + int applyAsInt(int operand) throws E; + + /** + * Returns a composed {@code FailableIntUnaryOperator} like {@link IntUnaryOperator#compose(IntUnaryOperator)}. + * + * @param before the operator to apply before this one. + * @return a composed {@code FailableIntUnaryOperator} like {@link IntUnaryOperator#compose(IntUnaryOperator)}. + * @throws NullPointerException if before is null. + * @throws E Thrown when a consumer fails. + * @see #andThen(FailableIntUnaryOperator) + */ + default FailableIntUnaryOperator compose(FailableIntUnaryOperator before) throws E { + Objects.requireNonNull(before); + return (int v) -> applyAsInt(before.applyAsInt(v)); + } +} diff --git a/src/main/java/org/apache/commons/lang3/function/FailableLongUnaryOperator.java b/src/main/java/org/apache/commons/lang3/function/FailableLongUnaryOperator.java new file mode 100644 index 00000000000..3248b02d33d --- /dev/null +++ b/src/main/java/org/apache/commons/lang3/function/FailableLongUnaryOperator.java @@ -0,0 +1,90 @@ +/* + * 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.function; + +import java.util.Objects; +import java.util.function.LongUnaryOperator; + +/** + * A functional interface like {@link LongUnaryOperator} that declares a {@code Throwable}. + * + * @param Thrown exception. + * @since 3.11 + */ +public interface FailableLongUnaryOperator { + + /** NOP singleton */ + @SuppressWarnings("rawtypes") + FailableLongUnaryOperator NOP = t -> 0L; + + /** + * Returns a unary operator that always returns its input argument. + * + * @return a unary operator that always returns its input argument + */ + static FailableLongUnaryOperator identity() { + return t -> t; + } + + /** + * Returns The NOP singleton. + * + * @param Thrown exception. + * @return The NOP singleton. + */ + static FailableLongUnaryOperator nop() { + return NOP; + } + + /** + * Returns a composed {@code FailableDoubleUnaryOperator} like {@link LongUnaryOperator#andThen(LongUnaryOperator)}. + * + * @param after the operator to apply after this one. + * @return a composed {@code FailableLongUnaryOperator} like {@link LongUnaryOperator#andThen(LongUnaryOperator)}. + * @throws NullPointerException if after is null. + * @throws E Thrown when a consumer fails. + * @see #compose(FailableLongUnaryOperator) + */ + default FailableLongUnaryOperator andThen(FailableLongUnaryOperator after) throws E { + Objects.requireNonNull(after); + return (long t) -> after.applyAsLong(applyAsLong(t)); + } + + /** + * Applies this operator to the given operand. + * + * @param operand the operand + * @return the operator result + * @throws E Thrown when a consumer fails. + */ + long applyAsLong(long operand) throws E; + + /** + * Returns a composed {@code FailableLongUnaryOperator} like {@link LongUnaryOperator#compose(LongUnaryOperator)}. + * + * @param before the operator to apply before this one. + * @return a composed {@code FailableLongUnaryOperator} like {@link LongUnaryOperator#compose(LongUnaryOperator)}. + * @throws NullPointerException if before is null. + * @throws E Thrown when a consumer fails. + * @see #andThen(FailableLongUnaryOperator) + */ + default FailableLongUnaryOperator compose(FailableLongUnaryOperator before) throws E { + Objects.requireNonNull(before); + return (long v) -> applyAsLong(before.applyAsLong(v)); + } +} diff --git a/src/test/java/org/apache/commons/lang3/function/FailableFunctionsTest.java b/src/test/java/org/apache/commons/lang3/function/FailableFunctionsTest.java index 3a123cf9074..9232762e413 100644 --- a/src/test/java/org/apache/commons/lang3/function/FailableFunctionsTest.java +++ b/src/test/java/org/apache/commons/lang3/function/FailableFunctionsTest.java @@ -36,7 +36,6 @@ import java.util.function.Predicate; import java.util.function.Supplier; -import org.apache.commons.lang3.Functions; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -708,8 +707,7 @@ public void testBiPredicate() { assertNotNull(cause); assertTrue(cause instanceof SomeException); assertEquals("Odd Invocation: 1", cause.getMessage()); - final boolean instance = predicate.test(null, null); - assertNotNull(instance); + assertTrue(predicate.test(null, null)); } @Test @@ -725,13 +723,6 @@ public void testCallable() { assertNotNull(instance); } - @Test - public void testConstructor() { - // We allow this, which must have been an omission to make the ctor private. - // We could make the ctor private in 4.0. - new Functions(); - } - @Test public void testConsumerAndThen() throws Throwable { final Testable testable = new Testable<>(null); @@ -774,12 +765,59 @@ public void testDoublePredicate() throws Throwable { failablePredicate.test(1d); } + @Test + public void testDoubleUnaryOperatorAndThen() throws Throwable { + final Testable testable = new Testable<>(null); + final FailableDoubleUnaryOperator failing = t -> { + testable.setThrowable(ERROR); + testable.test(); + return 0d; + }; + final FailableDoubleUnaryOperator nop = FailableDoubleUnaryOperator.nop(); + Throwable e = assertThrows(OutOfMemoryError.class, () -> nop.andThen(failing).applyAsDouble(0d)); + assertSame(ERROR, e); + e = assertThrows(OutOfMemoryError.class, () -> failing.andThen(nop).applyAsDouble(0d)); + assertSame(ERROR, e); + // Does not throw + nop.andThen(nop); + // Documented in Javadoc edge-case. + assertThrows(NullPointerException.class, () -> failing.andThen(null)); + } + + @Test + public void testDoubleUnaryOperatorCompose() throws Throwable { + final Testable testable = new Testable<>(null); + final FailableDoubleUnaryOperator failing = t -> { + testable.setThrowable(ERROR); + testable.test(); + return 0d; + }; + final FailableDoubleUnaryOperator nop = FailableDoubleUnaryOperator.nop(); + Throwable e = assertThrows(OutOfMemoryError.class, () -> nop.compose(failing).applyAsDouble(0d)); + assertSame(ERROR, e); + e = assertThrows(OutOfMemoryError.class, () -> failing.compose(nop).applyAsDouble(0d)); + assertSame(ERROR, e); + // Does not throw + nop.compose(nop); + // Documented in Javadoc edge-case. + assertThrows(NullPointerException.class, () -> failing.compose(null)); + } + + @Test + public void testDoubleUnaryOperatorIdentity() throws Throwable { + final FailableDoubleUnaryOperator nop = FailableDoubleUnaryOperator.identity(); + // Does not throw + nop.compose(nop); + // Documented in Javadoc edge-case. + assertThrows(NullPointerException.class, () -> nop.compose(null)); + } + @Test public void testFunction() { final Testable testable = new Testable<>(ILLEGAL_STATE_EXCEPTION); final FailableFunction failableFunction = th -> { testable.setThrowable(th); - return Integer.valueOf(testable.testAsInteger()); + return testable.testAsInteger(); }; final Function function = Failable.asFunction(failableFunction); Throwable e = assertThrows(IllegalStateException.class, () -> function.apply(ILLEGAL_STATE_EXCEPTION)); @@ -968,6 +1006,53 @@ public void testIntPredicate() throws Throwable { failablePredicate.test(1); } + @Test + public void testIntUnaryOperatorAndThen() throws Throwable { + final Testable testable = new Testable<>(null); + final FailableIntUnaryOperator failing = t -> { + testable.setThrowable(ERROR); + testable.test(); + return 0; + }; + final FailableIntUnaryOperator nop = FailableIntUnaryOperator.nop(); + Throwable e = assertThrows(OutOfMemoryError.class, () -> nop.andThen(failing).applyAsInt(0)); + assertSame(ERROR, e); + e = assertThrows(OutOfMemoryError.class, () -> failing.andThen(nop).applyAsInt(0)); + assertSame(ERROR, e); + // Does not throw + nop.andThen(nop); + // Documented in Javadoc edge-case. + assertThrows(NullPointerException.class, () -> failing.andThen(null)); + } + + @Test + public void testIntUnaryOperatorCompose() throws Throwable { + final Testable testable = new Testable<>(null); + final FailableIntUnaryOperator failing = t -> { + testable.setThrowable(ERROR); + testable.test(); + return 0; + }; + final FailableIntUnaryOperator nop = FailableIntUnaryOperator.nop(); + Throwable e = assertThrows(OutOfMemoryError.class, () -> nop.compose(failing).applyAsInt(0)); + assertSame(ERROR, e); + e = assertThrows(OutOfMemoryError.class, () -> failing.compose(nop).applyAsInt(0)); + assertSame(ERROR, e); + // Does not throw + nop.compose(nop); + // Documented in Javadoc edge-case. + assertThrows(NullPointerException.class, () -> failing.compose(null)); + } + + @Test + public void testIntUnaryOperatorIdentity() throws Throwable { + final FailableIntUnaryOperator nop = FailableIntUnaryOperator.identity(); + // Does not throw + nop.compose(nop); + // Documented in Javadoc edge-case. + assertThrows(NullPointerException.class, () -> nop.compose(null)); + } + @Test public void testLongConsumerAndThen() throws Throwable { final Testable testable = new Testable<>(null); @@ -994,6 +1079,53 @@ public void testLongPredicate() throws Throwable { failablePredicate.test(1L); } + @Test + public void testLongUnaryOperatorAndThen() throws Throwable { + final Testable testable = new Testable<>(null); + final FailableLongUnaryOperator failing = t -> { + testable.setThrowable(ERROR); + testable.test(); + return 0L; + }; + final FailableLongUnaryOperator nop = FailableLongUnaryOperator.nop(); + Throwable e = assertThrows(OutOfMemoryError.class, () -> nop.andThen(failing).applyAsLong(0L)); + assertSame(ERROR, e); + e = assertThrows(OutOfMemoryError.class, () -> failing.andThen(nop).applyAsLong(0L)); + assertSame(ERROR, e); + // Does not throw + nop.andThen(nop); + // Documented in Javadoc edge-case. + assertThrows(NullPointerException.class, () -> failing.andThen(null)); + } + + @Test + public void testLongUnaryOperatorCompose() throws Throwable { + final Testable testable = new Testable<>(null); + final FailableLongUnaryOperator failing = t -> { + testable.setThrowable(ERROR); + testable.test(); + return 0L; + }; + final FailableLongUnaryOperator nop = FailableLongUnaryOperator.nop(); + Throwable e = assertThrows(OutOfMemoryError.class, () -> nop.compose(failing).applyAsLong(0L)); + assertSame(ERROR, e); + e = assertThrows(OutOfMemoryError.class, () -> failing.compose(nop).applyAsLong(0L)); + assertSame(ERROR, e); + // Does not throw + nop.compose(nop); + // Documented in Javadoc edge-case. + assertThrows(NullPointerException.class, () -> failing.compose(null)); + } + + @Test + public void testLongUnaryOperatorIdentity() throws Throwable { + final FailableLongUnaryOperator nop = FailableLongUnaryOperator.identity(); + // Does not throw + nop.compose(nop); + // Documented in Javadoc edge-case. + assertThrows(NullPointerException.class, () -> nop.compose(null)); + } + @Test @DisplayName("Test that asPredicate(FailablePredicate) is converted to -> Predicate ") public void testPredicate() { From 487f5887bba4110cd2846e633ee546243a84c7d3 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Thu, 25 Jun 2020 09:17:49 -0400 Subject: [PATCH 0214/3230] [LANG-1568] Javadoc. --- .../commons/lang3/function/FailableDoubleUnaryOperator.java | 1 + .../apache/commons/lang3/function/FailableIntUnaryOperator.java | 1 + .../apache/commons/lang3/function/FailableLongUnaryOperator.java | 1 + .../apache/commons/lang3/function/FailableObjDoubleConsumer.java | 1 + .../apache/commons/lang3/function/FailableObjIntConsumer.java | 1 + .../apache/commons/lang3/function/FailableObjLongConsumer.java | 1 + 6 files changed, 6 insertions(+) diff --git a/src/main/java/org/apache/commons/lang3/function/FailableDoubleUnaryOperator.java b/src/main/java/org/apache/commons/lang3/function/FailableDoubleUnaryOperator.java index 13978d947ad..3fa2738f6b3 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableDoubleUnaryOperator.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableDoubleUnaryOperator.java @@ -35,6 +35,7 @@ public interface FailableDoubleUnaryOperator { /** * Returns a unary operator that always returns its input argument. * + * @param Thrown exception. * @return a unary operator that always returns its input argument */ static FailableDoubleUnaryOperator identity() { diff --git a/src/main/java/org/apache/commons/lang3/function/FailableIntUnaryOperator.java b/src/main/java/org/apache/commons/lang3/function/FailableIntUnaryOperator.java index 2fe71f119f2..9b6e1eb938e 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableIntUnaryOperator.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableIntUnaryOperator.java @@ -35,6 +35,7 @@ public interface FailableIntUnaryOperator { /** * Returns a unary operator that always returns its input argument. * + * @param Thrown exception. * @return a unary operator that always returns its input argument */ static FailableIntUnaryOperator identity() { diff --git a/src/main/java/org/apache/commons/lang3/function/FailableLongUnaryOperator.java b/src/main/java/org/apache/commons/lang3/function/FailableLongUnaryOperator.java index 3248b02d33d..9543ded771b 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableLongUnaryOperator.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableLongUnaryOperator.java @@ -35,6 +35,7 @@ public interface FailableLongUnaryOperator { /** * Returns a unary operator that always returns its input argument. * + * @param Thrown exception. * @return a unary operator that always returns its input argument */ static FailableLongUnaryOperator identity() { diff --git a/src/main/java/org/apache/commons/lang3/function/FailableObjDoubleConsumer.java b/src/main/java/org/apache/commons/lang3/function/FailableObjDoubleConsumer.java index 4d9860ef556..b81bf69e8af 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableObjDoubleConsumer.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableObjDoubleConsumer.java @@ -36,6 +36,7 @@ public interface FailableObjDoubleConsumer { /** * Returns The NOP singleton. * + * @param the type of the object argument to the operation. * @param Thrown exception. * @return The NOP singleton. */ diff --git a/src/main/java/org/apache/commons/lang3/function/FailableObjIntConsumer.java b/src/main/java/org/apache/commons/lang3/function/FailableObjIntConsumer.java index 893d60cc389..baa99b0b990 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableObjIntConsumer.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableObjIntConsumer.java @@ -36,6 +36,7 @@ public interface FailableObjIntConsumer { /** * Returns The NOP singleton. * + * @param the type of the object argument to the operation. * @param Thrown exception. * @return The NOP singleton. */ diff --git a/src/main/java/org/apache/commons/lang3/function/FailableObjLongConsumer.java b/src/main/java/org/apache/commons/lang3/function/FailableObjLongConsumer.java index 8b72626c34e..59790453ce2 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableObjLongConsumer.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableObjLongConsumer.java @@ -36,6 +36,7 @@ public interface FailableObjLongConsumer { /** * Returns The NOP singleton. * + * @param the type of the object argument to the operation. * @param Thrown exception. * @return The NOP singleton. */ From 9273b557b7d30cf52ebd09a98aa0f9e221d5b502 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Thu, 25 Jun 2020 09:32:14 -0400 Subject: [PATCH 0215/3230] [LANG-1568] Checktyle. --- .../commons/lang3/function/FailableFunctionsTest.java | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/test/java/org/apache/commons/lang3/function/FailableFunctionsTest.java b/src/test/java/org/apache/commons/lang3/function/FailableFunctionsTest.java index 9232762e413..ce8b5675958 100644 --- a/src/test/java/org/apache/commons/lang3/function/FailableFunctionsTest.java +++ b/src/test/java/org/apache/commons/lang3/function/FailableFunctionsTest.java @@ -680,7 +680,9 @@ public void testBiFunctionAndThen() throws IOException { final FailableBiFunction failingBiFunctionTest = (t, u) -> { throw new IOException(); }; - final FailableFunction failingFunction = t -> { throw new IOException(); }; + final FailableFunction failingFunction = t -> { + throw new IOException(); + }; final FailableBiFunction nopFailableBiFunction = FailableBiFunction .nop(); final FailableFunction nopFailableFunction = FailableFunction.nop(); @@ -843,7 +845,9 @@ public void testFunctionAndThen() throws IOException { final Function nopFunction = t -> null; nopFunction.andThen(nopFunction); // Checked usage pattern - final FailableFunction failingFunction = t -> { throw new IOException(); }; + final FailableFunction failingFunction = t -> { + throw new IOException(); + }; final FailableFunction nopFailableFunction = FailableFunction.nop(); // assertThrows(IOException.class, () -> failingFunction.andThen(failingFunction).apply(null)); From 00c8096cbf6ca89b17685488eddb5d0782fa18e4 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Thu, 25 Jun 2020 09:44:22 -0400 Subject: [PATCH 0216/3230] [LANG-1568] Complete FailableFunction. --- .../lang3/function/FailableFunction.java | 25 +++++++++++++++++ .../lang3/function/FailableFunctionsTest.java | 28 +++++++++++++++++++ 2 files changed, 53 insertions(+) diff --git a/src/main/java/org/apache/commons/lang3/function/FailableFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableFunction.java index cb100a4b22a..49af31c39f6 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableFunction.java @@ -35,6 +35,17 @@ public interface FailableFunction { @SuppressWarnings("rawtypes") FailableFunction NOP = t -> null; + /** + * Returns a function that always returns its input argument. + * + * @param the type of the input and output objects to the function + * @param Thrown exception. + * @return a function that always returns its input argument + */ + static FailableFunction identity() { + return t -> t; + } + /** * Returns The NOP singleton. * @@ -70,4 +81,18 @@ default FailableFunction andThen(final FailableFunction the input type to the {@code before} function, and to the composed function. + * @param before the operator to apply before this one. + * @return a a composed {@code FailableFunction} like {@link Function#compose(Function)}. + * @throws NullPointerException if before is null. + * @throws E Thrown when a consumer fails. + * @see #andThen(FailableFunction) + */ + default FailableFunction compose(final FailableFunction before) throws E { + Objects.requireNonNull(before); + return (final V v) -> apply(before.apply(v)); + } } diff --git a/src/test/java/org/apache/commons/lang3/function/FailableFunctionsTest.java b/src/test/java/org/apache/commons/lang3/function/FailableFunctionsTest.java index ce8b5675958..ca3ccd4a65b 100644 --- a/src/test/java/org/apache/commons/lang3/function/FailableFunctionsTest.java +++ b/src/test/java/org/apache/commons/lang3/function/FailableFunctionsTest.java @@ -859,6 +859,34 @@ public void testFunctionAndThen() throws IOException { assertThrows(NullPointerException.class, () -> failingFunction.andThen(null)); } + @Test + public void testFunctionCompose() throws Throwable { + final Testable testable = new Testable<>(null); + final FailableFunction failing = t -> { + testable.setThrowable(ERROR); + testable.test(); + return 0; + }; + final FailableFunction nop = FailableFunction.nop(); + Throwable e = assertThrows(OutOfMemoryError.class, () -> nop.compose(failing).apply(0)); + assertSame(ERROR, e); + e = assertThrows(OutOfMemoryError.class, () -> failing.compose(nop).apply(0)); + assertSame(ERROR, e); + // Does not throw + nop.compose(nop); + // Documented in Javadoc edge-case. + assertThrows(NullPointerException.class, () -> failing.compose(null)); + } + + @Test + public void testFunctionIdentity() throws Throwable { + final FailableFunction nop = FailableFunction.identity(); + // Does not throw + nop.compose(nop); + // Documented in Javadoc edge-case. + assertThrows(NullPointerException.class, () -> nop.compose(null)); + } + @Test public void testGetAsBooleanSupplier() { final Testable testable = new Testable<>(ILLEGAL_STATE_EXCEPTION); From a881c3e22665f65d974063d0536fdfd75f45d0d3 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Thu, 25 Jun 2020 10:19:10 -0400 Subject: [PATCH 0217/3230] [LANG-1568] Predicate negation. --- .../commons/lang3/function/Failable.java | 23 ++++++---- .../lang3/function/FailableBiFunction.java | 3 +- .../lang3/function/FailableBiPredicate.java | 44 ++++++++++++++++++- .../function/FailableDoublePredicate.java | 38 ++++++++++++++++ .../function/FailableDoubleUnaryOperator.java | 8 ++-- .../lang3/function/FailableIntPredicate.java | 38 ++++++++++++++++ .../function/FailableIntUnaryOperator.java | 8 ++-- .../lang3/function/FailableLongPredicate.java | 38 ++++++++++++++++ .../function/FailableLongUnaryOperator.java | 8 ++-- .../function/FailableObjIntConsumer.java | 2 +- .../function/FailableObjLongConsumer.java | 2 +- .../lang3/function/FailablePredicate.java | 42 +++++++++++++++++- .../commons/lang3/function/package-info.java | 12 ++--- .../lang3/function/FailableFunctionsTest.java | 35 +++++++++++++++ 14 files changed, 269 insertions(+), 32 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/function/Failable.java b/src/main/java/org/apache/commons/lang3/function/Failable.java index 7ff69bdb45d..d2a12a07d69 100644 --- a/src/main/java/org/apache/commons/lang3/function/Failable.java +++ b/src/main/java/org/apache/commons/lang3/function/Failable.java @@ -41,7 +41,8 @@ * constructs like: * *

      - * {@code
      + * {
      + *     @code
        *     Consumer consumer = (m) -> {
        *         try {
        *             m.invoke(o, args);
      @@ -49,7 +50,8 @@
        *             throw Failable.rethrow(t);
        *         }
        *     };
      - * }
      + * } + * * *

      * By replacing a {@link java.util.function.Consumer Consumer<O>} with a {@link FailableConsumer @@ -59,7 +61,8 @@ *

        * {@code
        *   Functions.accept((m) -> m.invoke(o,args));
      - * }
      + * } + * * *

      * Obviously, the second version is much more concise and the spirit of Lambda expressions is met better than the second @@ -80,8 +83,8 @@ public class Failable { * @param the type of the second argument the consumer accepts * @param the type of checked exception the consumer may throw */ - public static void accept(final FailableBiConsumer consumer, - final T object1, final U object2) { + public static void accept(final FailableBiConsumer consumer, final T object1, + final U object2) { run(() -> consumer.accept(object1, object2)); } @@ -142,8 +145,8 @@ public static void accept(final FailableLongConsumer co * @param the type of checked exception the function may throw * @return the value returned from the function */ - public static R apply(final FailableBiFunction function, - final T input1, final U input2) { + public static R apply(final FailableBiFunction function, final T input1, + final U input2) { return get(() -> function.apply(input1, input2)); } @@ -487,7 +490,8 @@ public static boolean test(final FailablePredicate - * {@code + * { + * @code * final FileInputStream fis = new FileInputStream("my.file"); * Functions.tryWithResources(useInputStream(fis), null, () -> fis.close()); * } @@ -549,7 +553,8 @@ public static void tryWithResources(final FailableRunnable * {@link Throwable} is rethrown. Example use: * *

      -     *     {@code
      +     * {
      +     *     @code
            *     final FileInputStream fis = new FileInputStream("my.file");
            *     Functions.tryWithResources(useInputStream(fis), () -> fis.close());
            * }
      diff --git a/src/main/java/org/apache/commons/lang3/function/FailableBiFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableBiFunction.java
      index 15d1788f34e..f7d63394396 100644
      --- a/src/main/java/org/apache/commons/lang3/function/FailableBiFunction.java
      +++ b/src/main/java/org/apache/commons/lang3/function/FailableBiFunction.java
      @@ -59,7 +59,8 @@ static  FailableBiFunction nop() {
            * @throws NullPointerException when {@code after} is null.
            * @throws E Thrown when a consumer fails.
            */
      -    default  FailableBiFunction andThen(final FailableFunction after) throws E {
      +    default  FailableBiFunction andThen(final FailableFunction after)
      +        throws E {
               Objects.requireNonNull(after);
               return (final T t, final U u) -> after.apply(apply(t, u));
           }
      diff --git a/src/main/java/org/apache/commons/lang3/function/FailableBiPredicate.java b/src/main/java/org/apache/commons/lang3/function/FailableBiPredicate.java
      index 22993572a77..75936c9e21d 100644
      --- a/src/main/java/org/apache/commons/lang3/function/FailableBiPredicate.java
      +++ b/src/main/java/org/apache/commons/lang3/function/FailableBiPredicate.java
      @@ -30,13 +30,55 @@
       @FunctionalInterface
       public interface FailableBiPredicate {
       
      +    /** FALSE singleton */
      +    @SuppressWarnings("rawtypes")
      +    FailableBiPredicate FALSE = (t, u) -> false;
      +
      +    /** TRUE singleton */
      +    @SuppressWarnings("rawtypes")
      +    FailableBiPredicate TRUE = (t, u) -> true;
      +
      +    /**
      +     * Returns The FALSE singleton.
      +     *
      +     * @param  Consumed type 1.
      +     * @param  Consumed type 2.
      +     * @param  Thrown exception.
      +     * @return The NOP singleton.
      +     */
      +    static  FailableBiPredicate falsePredicate() {
      +        return FALSE;
      +    }
      +
      +    /**
      +     * Returns The FALSE TRUE.
      +     *
      +     * @param  Consumed type 1.
      +     * @param  Consumed type 2.
      +     * @param  Thrown exception.
      +     * @return The NOP singleton.
      +     */
      +    static  FailableBiPredicate truePredicate() {
      +        return TRUE;
      +    }
      +
      +    /**
      +     * Returns a predicate that negates this predicate.
      +     *
      +     * @return a predicate that negates this predicate.
      +     * @throws E Thrown when this predicate fails.
      +     */
      +    default FailableBiPredicate negate() throws E {
      +        return (final T t, final U u) -> !test(t, u);
      +    }
      +
           /**
            * Tests the predicate.
            *
            * @param object1 the first object to test the predicate on
            * @param object2 the second object to test the predicate on
            * @return the predicate's evaluation
      -     * @throws E if the predicate fails
      +     * @throws E Thrown when this predicate fails.
            */
           boolean test(T object1, U object2) throws E;
       }
      diff --git a/src/main/java/org/apache/commons/lang3/function/FailableDoublePredicate.java b/src/main/java/org/apache/commons/lang3/function/FailableDoublePredicate.java
      index abdd2cb7ee8..db3fdacdd01 100644
      --- a/src/main/java/org/apache/commons/lang3/function/FailableDoublePredicate.java
      +++ b/src/main/java/org/apache/commons/lang3/function/FailableDoublePredicate.java
      @@ -28,6 +28,44 @@
       @FunctionalInterface
       public interface FailableDoublePredicate {
       
      +    /** FALSE singleton */
      +    @SuppressWarnings("rawtypes")
      +    FailableDoublePredicate FALSE = t -> false;
      +
      +    /** TRUE singleton */
      +    @SuppressWarnings("rawtypes")
      +    FailableDoublePredicate TRUE = t -> true;
      +
      +    /**
      +     * Returns The FALSE singleton.
      +     *
      +     * @param  Thrown exception.
      +     * @return The NOP singleton.
      +     */
      +    static  FailableDoublePredicate falsePredicate() {
      +        return FALSE;
      +    }
      +
      +    /**
      +     * Returns The FALSE TRUE.
      +     *
      +     * @param  Thrown exception.
      +     * @return The NOP singleton.
      +     */
      +    static  FailableDoublePredicate truePredicate() {
      +        return TRUE;
      +    }
      +
      +    /**
      +     * Returns a predicate that negates this predicate.
      +     *
      +     * @return a predicate that negates this predicate.
      +     * @throws E Thrown when this predicate fails.
      +     */
      +    default FailableDoublePredicate negate() throws E {
      +        return t -> !test(t);
      +    }
      +
           /**
            * Tests the predicate.
            *
      diff --git a/src/main/java/org/apache/commons/lang3/function/FailableDoubleUnaryOperator.java b/src/main/java/org/apache/commons/lang3/function/FailableDoubleUnaryOperator.java
      index 3fa2738f6b3..2674f1d863a 100644
      --- a/src/main/java/org/apache/commons/lang3/function/FailableDoubleUnaryOperator.java
      +++ b/src/main/java/org/apache/commons/lang3/function/FailableDoubleUnaryOperator.java
      @@ -63,9 +63,9 @@ static  FailableDoubleUnaryOperator nop() {
            * @throws E Thrown when a consumer fails.
            * @see #compose(FailableDoubleUnaryOperator)
            */
      -    default FailableDoubleUnaryOperator andThen(FailableDoubleUnaryOperator after) throws E {
      +    default FailableDoubleUnaryOperator andThen(final FailableDoubleUnaryOperator after) throws E {
               Objects.requireNonNull(after);
      -        return (double t) -> after.applyAsDouble(applyAsDouble(t));
      +        return (final double t) -> after.applyAsDouble(applyAsDouble(t));
           }
       
           /**
      @@ -88,8 +88,8 @@ default FailableDoubleUnaryOperator andThen(FailableDoubleUnaryOperator af
            * @throws E Thrown when a consumer fails.
            * @see #andThen(FailableDoubleUnaryOperator)
            */
      -    default FailableDoubleUnaryOperator compose(FailableDoubleUnaryOperator before) throws E {
      +    default FailableDoubleUnaryOperator compose(final FailableDoubleUnaryOperator before) throws E {
               Objects.requireNonNull(before);
      -        return (double v) -> applyAsDouble(before.applyAsDouble(v));
      +        return (final double v) -> applyAsDouble(before.applyAsDouble(v));
           }
       }
      diff --git a/src/main/java/org/apache/commons/lang3/function/FailableIntPredicate.java b/src/main/java/org/apache/commons/lang3/function/FailableIntPredicate.java
      index 837ba319c79..12bd5c0cc6d 100644
      --- a/src/main/java/org/apache/commons/lang3/function/FailableIntPredicate.java
      +++ b/src/main/java/org/apache/commons/lang3/function/FailableIntPredicate.java
      @@ -28,6 +28,44 @@
       @FunctionalInterface
       public interface FailableIntPredicate {
       
      +    /** FALSE singleton */
      +    @SuppressWarnings("rawtypes")
      +    FailableIntPredicate FALSE = t -> false;
      +
      +    /** TRUE singleton */
      +    @SuppressWarnings("rawtypes")
      +    FailableIntPredicate TRUE = t -> true;
      +
      +    /**
      +     * Returns The FALSE singleton.
      +     *
      +     * @param  Thrown exception.
      +     * @return The NOP singleton.
      +     */
      +    static  FailableIntPredicate falsePredicate() {
      +        return FALSE;
      +    }
      +
      +    /**
      +     * Returns The FALSE TRUE.
      +     *
      +     * @param  Thrown exception.
      +     * @return The NOP singleton.
      +     */
      +    static  FailableIntPredicate truePredicate() {
      +        return TRUE;
      +    }
      +
      +    /**
      +     * Returns a predicate that negates this predicate.
      +     *
      +     * @return a predicate that negates this predicate.
      +     * @throws E Thrown when this predicate fails.
      +     */
      +    default FailableIntPredicate negate() throws E {
      +        return t -> !test(t);
      +    }
      +
           /**
            * Tests the predicate.
            *
      diff --git a/src/main/java/org/apache/commons/lang3/function/FailableIntUnaryOperator.java b/src/main/java/org/apache/commons/lang3/function/FailableIntUnaryOperator.java
      index 9b6e1eb938e..b685885d936 100644
      --- a/src/main/java/org/apache/commons/lang3/function/FailableIntUnaryOperator.java
      +++ b/src/main/java/org/apache/commons/lang3/function/FailableIntUnaryOperator.java
      @@ -61,9 +61,9 @@ static  FailableIntUnaryOperator nop() {
            * @throws E Thrown when a consumer fails.
            * @see #compose(FailableIntUnaryOperator)
            */
      -    default FailableIntUnaryOperator andThen(FailableIntUnaryOperator after) throws E {
      +    default FailableIntUnaryOperator andThen(final FailableIntUnaryOperator after) throws E {
               Objects.requireNonNull(after);
      -        return (int t) -> after.applyAsInt(applyAsInt(t));
      +        return (final int t) -> after.applyAsInt(applyAsInt(t));
           }
       
           /**
      @@ -84,8 +84,8 @@ default FailableIntUnaryOperator andThen(FailableIntUnaryOperator after) t
            * @throws E Thrown when a consumer fails.
            * @see #andThen(FailableIntUnaryOperator)
            */
      -    default FailableIntUnaryOperator compose(FailableIntUnaryOperator before) throws E {
      +    default FailableIntUnaryOperator compose(final FailableIntUnaryOperator before) throws E {
               Objects.requireNonNull(before);
      -        return (int v) -> applyAsInt(before.applyAsInt(v));
      +        return (final int v) -> applyAsInt(before.applyAsInt(v));
           }
       }
      diff --git a/src/main/java/org/apache/commons/lang3/function/FailableLongPredicate.java b/src/main/java/org/apache/commons/lang3/function/FailableLongPredicate.java
      index 3c756ca9770..b267ead67fe 100644
      --- a/src/main/java/org/apache/commons/lang3/function/FailableLongPredicate.java
      +++ b/src/main/java/org/apache/commons/lang3/function/FailableLongPredicate.java
      @@ -28,6 +28,44 @@
       @FunctionalInterface
       public interface FailableLongPredicate {
       
      +    /** FALSE singleton */
      +    @SuppressWarnings("rawtypes")
      +    FailableLongPredicate FALSE = t -> false;
      +
      +    /** TRUE singleton */
      +    @SuppressWarnings("rawtypes")
      +    FailableLongPredicate TRUE = t -> true;
      +
      +    /**
      +     * Returns The FALSE singleton.
      +     *
      +     * @param  Thrown exception.
      +     * @return The NOP singleton.
      +     */
      +    static  FailableLongPredicate falsePredicate() {
      +        return FALSE;
      +    }
      +
      +    /**
      +     * Returns The FALSE TRUE.
      +     *
      +     * @param  Thrown exception.
      +     * @return The NOP singleton.
      +     */
      +    static  FailableLongPredicate truePredicate() {
      +        return TRUE;
      +    }
      +
      +    /**
      +     * Returns a predicate that negates this predicate.
      +     *
      +     * @return a predicate that negates this predicate.
      +     * @throws E Thrown when this predicate fails.
      +     */
      +    default FailableLongPredicate negate() throws E {
      +        return t -> !test(t);
      +    }
      +
           /**
            * Tests the predicate.
            *
      diff --git a/src/main/java/org/apache/commons/lang3/function/FailableLongUnaryOperator.java b/src/main/java/org/apache/commons/lang3/function/FailableLongUnaryOperator.java
      index 9543ded771b..6f980b7652b 100644
      --- a/src/main/java/org/apache/commons/lang3/function/FailableLongUnaryOperator.java
      +++ b/src/main/java/org/apache/commons/lang3/function/FailableLongUnaryOperator.java
      @@ -61,9 +61,9 @@ static  FailableLongUnaryOperator nop() {
            * @throws E Thrown when a consumer fails.
            * @see #compose(FailableLongUnaryOperator)
            */
      -    default FailableLongUnaryOperator andThen(FailableLongUnaryOperator after) throws E {
      +    default FailableLongUnaryOperator andThen(final FailableLongUnaryOperator after) throws E {
               Objects.requireNonNull(after);
      -        return (long t) -> after.applyAsLong(applyAsLong(t));
      +        return (final long t) -> after.applyAsLong(applyAsLong(t));
           }
       
           /**
      @@ -84,8 +84,8 @@ default FailableLongUnaryOperator andThen(FailableLongUnaryOperator after)
            * @throws E Thrown when a consumer fails.
            * @see #andThen(FailableLongUnaryOperator)
            */
      -    default FailableLongUnaryOperator compose(FailableLongUnaryOperator before) throws E {
      +    default FailableLongUnaryOperator compose(final FailableLongUnaryOperator before) throws E {
               Objects.requireNonNull(before);
      -        return (long v) -> applyAsLong(before.applyAsLong(v));
      +        return (final long v) -> applyAsLong(before.applyAsLong(v));
           }
       }
      diff --git a/src/main/java/org/apache/commons/lang3/function/FailableObjIntConsumer.java b/src/main/java/org/apache/commons/lang3/function/FailableObjIntConsumer.java
      index baa99b0b990..483f0f4b3e0 100644
      --- a/src/main/java/org/apache/commons/lang3/function/FailableObjIntConsumer.java
      +++ b/src/main/java/org/apache/commons/lang3/function/FailableObjIntConsumer.java
      @@ -48,7 +48,7 @@ static  FailableObjIntConsumer nop() {
            * Accepts the consumer.
            *
            * @param object the object parameter for the consumable to accept.
      -     * @param value  the int parameter for the consumable to accept.
      +     * @param value the int parameter for the consumable to accept.
            * @throws E Thrown when the consumer fails.
            */
           void accept(T object, int value) throws E;
      diff --git a/src/main/java/org/apache/commons/lang3/function/FailableObjLongConsumer.java b/src/main/java/org/apache/commons/lang3/function/FailableObjLongConsumer.java
      index 59790453ce2..378ff0f6457 100644
      --- a/src/main/java/org/apache/commons/lang3/function/FailableObjLongConsumer.java
      +++ b/src/main/java/org/apache/commons/lang3/function/FailableObjLongConsumer.java
      @@ -48,7 +48,7 @@ static  FailableObjLongConsumer nop() {
            * Accepts the consumer.
            *
            * @param object the object parameter for the consumable to accept.
      -     * @param value  the long parameter for the consumable to accept.
      +     * @param value the long parameter for the consumable to accept.
            * @throws E Thrown when the consumer fails.
            */
           void accept(T object, long value) throws E;
      diff --git a/src/main/java/org/apache/commons/lang3/function/FailablePredicate.java b/src/main/java/org/apache/commons/lang3/function/FailablePredicate.java
      index 999107a1526..ce49539b953 100644
      --- a/src/main/java/org/apache/commons/lang3/function/FailablePredicate.java
      +++ b/src/main/java/org/apache/commons/lang3/function/FailablePredicate.java
      @@ -22,13 +22,53 @@
       /**
        * A functional interface like {@link Predicate} that declares a {@code Throwable}.
        *
      - * @param  Predicate type 1.
      + * @param  Predicate type.
        * @param  Thrown exception.
        * @since 3.11
        */
       @FunctionalInterface
       public interface FailablePredicate {
       
      +    /** FALSE singleton */
      +    @SuppressWarnings("rawtypes")
      +    FailablePredicate FALSE = t -> false;
      +
      +    /** TRUE singleton */
      +    @SuppressWarnings("rawtypes")
      +    FailablePredicate TRUE = t -> true;
      +
      +    /**
      +     * Returns The FALSE singleton.
      +     *
      +     * @param  Predicate type.
      +     * @param  Thrown exception.
      +     * @return The NOP singleton.
      +     */
      +    static  FailablePredicate falsePredicate() {
      +        return FALSE;
      +    }
      +
      +    /**
      +     * Returns The FALSE TRUE.
      +     *
      +     * @param  Predicate type.
      +     * @param  Thrown exception.
      +     * @return The NOP singleton.
      +     */
      +    static  FailablePredicate truePredicate() {
      +        return TRUE;
      +    }
      +
      +    /**
      +     * Returns a predicate that negates this predicate.
      +     *
      +     * @return a predicate that negates this predicate.
      +     * @throws E Thrown when this predicate fails.
      +     */
      +    default FailablePredicate negate() throws E {
      +        return t -> !test(t);
      +    }
      +
           /**
            * Tests the predicate.
            *
      diff --git a/src/main/java/org/apache/commons/lang3/function/package-info.java b/src/main/java/org/apache/commons/lang3/function/package-info.java
      index 5cc1d9a63d6..4a0ccd91376 100644
      --- a/src/main/java/org/apache/commons/lang3/function/package-info.java
      +++ b/src/main/java/org/apache/commons/lang3/function/package-info.java
      @@ -15,13 +15,13 @@
        * limitations under the License.
        */
       /**
      - * Provides functional interfaces to complement those in {@code java.lang.function} and utilities
      - * for working with Java 8 lambdas.
      + * Provides functional interfaces to complement those in {@code java.lang.function} and utilities for working with Java
      + * 8 lambdas.
        *
      - * 

      Contains failable functional interfaces that address the fact that lambdas are supposed not to - * throw Exceptions, at least not checked Exceptions, A.K.A. instances of {@link java.lang.Exception}. - * A failable functional interface declares a type of Exception that may be raised if the function - * fails. + *

      + * Contains failable functional interfaces that address the fact that lambdas are supposed not to throw Exceptions, at + * least not checked Exceptions, A.K.A. instances of {@link java.lang.Exception}. A failable functional interface + * declares a type of Exception that may be raised if the function fails. * * @since 3.11 */ diff --git a/src/test/java/org/apache/commons/lang3/function/FailableFunctionsTest.java b/src/test/java/org/apache/commons/lang3/function/FailableFunctionsTest.java index ca3ccd4a65b..957225fcd60 100644 --- a/src/test/java/org/apache/commons/lang3/function/FailableFunctionsTest.java +++ b/src/test/java/org/apache/commons/lang3/function/FailableFunctionsTest.java @@ -712,6 +712,13 @@ public void testBiPredicate() { assertTrue(predicate.test(null, null)); } + public void testBiPredicateNegate() throws Throwable { + assertFalse(FailableBiPredicate.TRUE.negate().test(null, null)); + assertFalse(FailableBiPredicate.truePredicate().negate().test(null, null)); + assertTrue(FailableBiPredicate.FALSE.negate().test(null, null)); + assertTrue(FailableBiPredicate.falsePredicate().negate().test(null, null)); + } + @Test public void testCallable() { FailureOnOddInvocations.invocations = 0; @@ -767,6 +774,13 @@ public void testDoublePredicate() throws Throwable { failablePredicate.test(1d); } + public void testDoublePredicateNegate() throws Throwable { + assertFalse(FailableDoublePredicate.TRUE.negate().test(0d)); + assertFalse(FailableDoublePredicate.truePredicate().negate().test(0d)); + assertTrue(FailableDoublePredicate.FALSE.negate().test(0d)); + assertTrue(FailableDoublePredicate.falsePredicate().negate().test(0d)); + } + @Test public void testDoubleUnaryOperatorAndThen() throws Throwable { final Testable testable = new Testable<>(null); @@ -1038,6 +1052,13 @@ public void testIntPredicate() throws Throwable { failablePredicate.test(1); } + public void testIntPredicateNegate() throws Throwable { + assertFalse(FailableIntPredicate.TRUE.negate().test(0)); + assertFalse(FailableIntPredicate.truePredicate().negate().test(0)); + assertTrue(FailableIntPredicate.FALSE.negate().test(0)); + assertTrue(FailableIntPredicate.falsePredicate().negate().test(0)); + } + @Test public void testIntUnaryOperatorAndThen() throws Throwable { final Testable testable = new Testable<>(null); @@ -1111,6 +1132,13 @@ public void testLongPredicate() throws Throwable { failablePredicate.test(1L); } + public void testLongPredicateNegate() throws Throwable { + assertFalse(FailableLongPredicate.TRUE.negate().test(0L)); + assertFalse(FailableLongPredicate.truePredicate().negate().test(0L)); + assertTrue(FailableLongPredicate.FALSE.negate().test(0L)); + assertTrue(FailableLongPredicate.falsePredicate().negate().test(0L)); + } + @Test public void testLongUnaryOperatorAndThen() throws Throwable { final Testable testable = new Testable<>(null); @@ -1174,6 +1202,13 @@ public void testPredicate() { assertNotNull(instance); } + public void testPredicateNegate() throws Throwable { + assertFalse(FailablePredicate.TRUE.negate().test(null)); + assertFalse(FailablePredicate.truePredicate().negate().test(null)); + assertTrue(FailablePredicate.FALSE.negate().test(null)); + assertTrue(FailablePredicate.falsePredicate().negate().test(null)); + } + @Test public void testRunnable() { FailureOnOddInvocations.invocations = 0; From c7d709b22074a4f5f952cc2b71f9053a5a38b138 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Thu, 25 Jun 2020 10:29:57 -0400 Subject: [PATCH 0218/3230] [LANG-1568] Predicate negation and clean ups. --- .../lang3/function/FailableBiConsumer.java | 4 +--- .../lang3/function/FailableBiFunction.java | 4 +--- .../lang3/function/FailableBiPredicate.java | 16 ++++++++++++++-- .../lang3/function/FailableConsumer.java | 3 +-- .../lang3/function/FailableDoubleConsumer.java | 3 +-- .../lang3/function/FailableDoublePredicate.java | 17 +++++++++++++++-- .../function/FailableDoubleUnaryOperator.java | 6 ++---- .../lang3/function/FailableFunction.java | 6 ++---- .../lang3/function/FailableIntConsumer.java | 3 +-- .../lang3/function/FailableIntPredicate.java | 3 +-- .../function/FailableIntUnaryOperator.java | 6 ++---- .../lang3/function/FailableLongConsumer.java | 3 +-- .../lang3/function/FailableLongPredicate.java | 3 +-- .../function/FailableLongUnaryOperator.java | 6 ++---- .../lang3/function/FailablePredicate.java | 3 +-- 15 files changed, 46 insertions(+), 40 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/function/FailableBiConsumer.java b/src/main/java/org/apache/commons/lang3/function/FailableBiConsumer.java index 6589a4d7840..8bfe6d534a4 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableBiConsumer.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableBiConsumer.java @@ -62,11 +62,9 @@ static FailableBiConsumer nop() { * @param after the operation to perform after this one. * @return a composed {@code FailableBiConsumer} like {@link BiConsumer#andThen(BiConsumer)}. * @throws NullPointerException when {@code after} is null. - * @throws E Thrown when a consumer fails. */ - default FailableBiConsumer andThen(final FailableBiConsumer after) throws E { + default FailableBiConsumer andThen(final FailableBiConsumer after) { Objects.requireNonNull(after); - return (t, u) -> { accept(t, u); after.accept(t, u); diff --git a/src/main/java/org/apache/commons/lang3/function/FailableBiFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableBiFunction.java index f7d63394396..23af54fc0e5 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableBiFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableBiFunction.java @@ -57,10 +57,8 @@ static FailableBiFunction nop() { * @param after the operation to perform after this one. * @return a composed {@code FailableBiFunction} that like {@link BiFunction#andThen(Function)}. * @throws NullPointerException when {@code after} is null. - * @throws E Thrown when a consumer fails. */ - default FailableBiFunction andThen(final FailableFunction after) - throws E { + default FailableBiFunction andThen(final FailableFunction after) { Objects.requireNonNull(after); return (final T t, final U u) -> after.apply(apply(t, u)); } diff --git a/src/main/java/org/apache/commons/lang3/function/FailableBiPredicate.java b/src/main/java/org/apache/commons/lang3/function/FailableBiPredicate.java index 75936c9e21d..56c5028ec3e 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableBiPredicate.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableBiPredicate.java @@ -17,6 +17,7 @@ package org.apache.commons.lang3.function; +import java.util.Objects; import java.util.function.BiPredicate; /** @@ -62,13 +63,24 @@ static FailableBiPredicate truePredicate() return TRUE; } + /** + * Returns a composed {@code FailableBiPredicate} like {@link BiPredicate#and(BiPredicate)}. + * + * @param other a predicate that will be logically-ANDed with this predicate. + * @return a composed {@code FailableBiPredicate} like {@link BiPredicate#and(BiPredicate)}. + * @throws NullPointerException if other is null + */ + default FailableBiPredicate and(FailableBiPredicate other) { + Objects.requireNonNull(other); + return (T t, U u) -> test(t, u) && other.test(t, u); + } + /** * Returns a predicate that negates this predicate. * * @return a predicate that negates this predicate. - * @throws E Thrown when this predicate fails. */ - default FailableBiPredicate negate() throws E { + default FailableBiPredicate negate() { return (final T t, final U u) -> !test(t, u); } diff --git a/src/main/java/org/apache/commons/lang3/function/FailableConsumer.java b/src/main/java/org/apache/commons/lang3/function/FailableConsumer.java index 3df422bf847..aa7a8de69b4 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableConsumer.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableConsumer.java @@ -59,9 +59,8 @@ static FailableConsumer nop() { * @param after the operation to perform after this operation * @return a composed {@code Consumer} like {@link Consumer#andThen(Consumer)}. * @throws NullPointerException when {@code after} is null - * @throws E Thrown when a consumer fails. */ - default FailableConsumer andThen(final FailableConsumer after) throws E { + default FailableConsumer andThen(final FailableConsumer after) { Objects.requireNonNull(after); return (final T t) -> { accept(t); diff --git a/src/main/java/org/apache/commons/lang3/function/FailableDoubleConsumer.java b/src/main/java/org/apache/commons/lang3/function/FailableDoubleConsumer.java index 3b379198179..edd71fbcb76 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableDoubleConsumer.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableDoubleConsumer.java @@ -57,9 +57,8 @@ static FailableDoubleConsumer nop() { * @param after the operation to perform after this one. * @return a composed {@code FailableDoubleConsumer} like {@link DoubleConsumer#andThen(DoubleConsumer)}. * @throws NullPointerException when {@code after} is null. - * @throws E Thrown when a consumer fails. */ - default FailableDoubleConsumer andThen(final FailableDoubleConsumer after) throws E { + default FailableDoubleConsumer andThen(final FailableDoubleConsumer after) { Objects.requireNonNull(after); return (final double t) -> { accept(t); diff --git a/src/main/java/org/apache/commons/lang3/function/FailableDoublePredicate.java b/src/main/java/org/apache/commons/lang3/function/FailableDoublePredicate.java index db3fdacdd01..0c7def5aebc 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableDoublePredicate.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableDoublePredicate.java @@ -17,6 +17,8 @@ package org.apache.commons.lang3.function; +import java.util.Objects; +import java.util.function.BiPredicate; import java.util.function.DoublePredicate; /** @@ -28,6 +30,18 @@ @FunctionalInterface public interface FailableDoublePredicate { + /** + * Returns a composed {@code FailableBiPredicate} like {@link BiPredicate#and(BiPredicate)}. + * + * @param other a predicate that will be logically-ANDed with this predicate. + * @return a composed {@code FailableBiPredicate} like {@link BiPredicate#and(BiPredicate)}. + * @throws NullPointerException if other is null + */ + default FailableDoublePredicate and(FailableDoublePredicate other) { + Objects.requireNonNull(other); + return t -> test(t) && other.test(t); + } + /** FALSE singleton */ @SuppressWarnings("rawtypes") FailableDoublePredicate FALSE = t -> false; @@ -60,9 +74,8 @@ static FailableDoublePredicate truePredicate() { * Returns a predicate that negates this predicate. * * @return a predicate that negates this predicate. - * @throws E Thrown when this predicate fails. */ - default FailableDoublePredicate negate() throws E { + default FailableDoublePredicate negate() { return t -> !test(t); } diff --git a/src/main/java/org/apache/commons/lang3/function/FailableDoubleUnaryOperator.java b/src/main/java/org/apache/commons/lang3/function/FailableDoubleUnaryOperator.java index 2674f1d863a..9e542fd6e16 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableDoubleUnaryOperator.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableDoubleUnaryOperator.java @@ -60,10 +60,9 @@ static FailableDoubleUnaryOperator nop() { * @return a composed {@code FailableDoubleUnaryOperator} like * {@link DoubleUnaryOperator#andThen(DoubleUnaryOperator)}. * @throws NullPointerException if after is null. - * @throws E Thrown when a consumer fails. * @see #compose(FailableDoubleUnaryOperator) */ - default FailableDoubleUnaryOperator andThen(final FailableDoubleUnaryOperator after) throws E { + default FailableDoubleUnaryOperator andThen(final FailableDoubleUnaryOperator after) { Objects.requireNonNull(after); return (final double t) -> after.applyAsDouble(applyAsDouble(t)); } @@ -85,10 +84,9 @@ default FailableDoubleUnaryOperator andThen(final FailableDoubleUnaryOperator * @return a composed {@code FailableDoubleUnaryOperator} like * {@link DoubleUnaryOperator#compose(DoubleUnaryOperator)}. * @throws NullPointerException if before is null. - * @throws E Thrown when a consumer fails. * @see #andThen(FailableDoubleUnaryOperator) */ - default FailableDoubleUnaryOperator compose(final FailableDoubleUnaryOperator before) throws E { + default FailableDoubleUnaryOperator compose(final FailableDoubleUnaryOperator before) { Objects.requireNonNull(before); return (final double v) -> applyAsDouble(before.applyAsDouble(v)); } diff --git a/src/main/java/org/apache/commons/lang3/function/FailableFunction.java b/src/main/java/org/apache/commons/lang3/function/FailableFunction.java index 49af31c39f6..715e2650ed9 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableFunction.java @@ -65,9 +65,8 @@ static FailableFunction nop() { * @return a composed {@code FailableFunction} like {@link Function#andThen(Function)}. * @param after the operation to perform after this one. * @throws NullPointerException when {@code after} is null. - * @throws E Thrown when a consumer fails. */ - default FailableFunction andThen(final FailableFunction after) throws E { + default FailableFunction andThen(final FailableFunction after) { Objects.requireNonNull(after); return (final T t) -> after.apply(apply(t)); } @@ -88,10 +87,9 @@ default FailableFunction andThen(final FailableFunction FailableFunction compose(final FailableFunction before) throws E { + default FailableFunction compose(final FailableFunction before) { Objects.requireNonNull(before); return (final V v) -> apply(before.apply(v)); } diff --git a/src/main/java/org/apache/commons/lang3/function/FailableIntConsumer.java b/src/main/java/org/apache/commons/lang3/function/FailableIntConsumer.java index 64429df00ab..ee7a15f3aaf 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableIntConsumer.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableIntConsumer.java @@ -57,9 +57,8 @@ static FailableIntConsumer nop() { * @param after the operation to perform after this one. * @return a composed {@code FailableLongConsumer} like {@link IntConsumer#andThen(IntConsumer)}. * @throws NullPointerException if {@code after} is null - * @throws E Thrown when a consumer fails. */ - default FailableIntConsumer andThen(final FailableIntConsumer after) throws E { + default FailableIntConsumer andThen(final FailableIntConsumer after) { Objects.requireNonNull(after); return (final int t) -> { accept(t); diff --git a/src/main/java/org/apache/commons/lang3/function/FailableIntPredicate.java b/src/main/java/org/apache/commons/lang3/function/FailableIntPredicate.java index 12bd5c0cc6d..babfceb87ff 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableIntPredicate.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableIntPredicate.java @@ -60,9 +60,8 @@ static FailableIntPredicate truePredicate() { * Returns a predicate that negates this predicate. * * @return a predicate that negates this predicate. - * @throws E Thrown when this predicate fails. */ - default FailableIntPredicate negate() throws E { + default FailableIntPredicate negate() { return t -> !test(t); } diff --git a/src/main/java/org/apache/commons/lang3/function/FailableIntUnaryOperator.java b/src/main/java/org/apache/commons/lang3/function/FailableIntUnaryOperator.java index b685885d936..578e5322ad2 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableIntUnaryOperator.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableIntUnaryOperator.java @@ -58,10 +58,9 @@ static FailableIntUnaryOperator nop() { * @param after the operator to apply after this one. * @return a composed {@code FailableIntUnaryOperator} like {@link IntUnaryOperator#andThen(IntUnaryOperator)}. * @throws NullPointerException if after is null. - * @throws E Thrown when a consumer fails. * @see #compose(FailableIntUnaryOperator) */ - default FailableIntUnaryOperator andThen(final FailableIntUnaryOperator after) throws E { + default FailableIntUnaryOperator andThen(final FailableIntUnaryOperator after) { Objects.requireNonNull(after); return (final int t) -> after.applyAsInt(applyAsInt(t)); } @@ -81,10 +80,9 @@ default FailableIntUnaryOperator andThen(final FailableIntUnaryOperator af * @param before the operator to apply before this one. * @return a composed {@code FailableIntUnaryOperator} like {@link IntUnaryOperator#compose(IntUnaryOperator)}. * @throws NullPointerException if before is null. - * @throws E Thrown when a consumer fails. * @see #andThen(FailableIntUnaryOperator) */ - default FailableIntUnaryOperator compose(final FailableIntUnaryOperator before) throws E { + default FailableIntUnaryOperator compose(final FailableIntUnaryOperator before) { Objects.requireNonNull(before); return (final int v) -> applyAsInt(before.applyAsInt(v)); } diff --git a/src/main/java/org/apache/commons/lang3/function/FailableLongConsumer.java b/src/main/java/org/apache/commons/lang3/function/FailableLongConsumer.java index c2a0ca8a54f..de5bd4f4633 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableLongConsumer.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableLongConsumer.java @@ -57,9 +57,8 @@ static FailableLongConsumer nop() { * @param after the operation to perform after this one. * @return a composed {@code FailableLongConsumer} like {@link LongConsumer#andThen(LongConsumer)}. * @throws NullPointerException if {@code after} is null - * @throws E Thrown when a consumer fails. */ - default FailableLongConsumer andThen(final FailableLongConsumer after) throws E { + default FailableLongConsumer andThen(final FailableLongConsumer after) { Objects.requireNonNull(after); return (final long t) -> { accept(t); diff --git a/src/main/java/org/apache/commons/lang3/function/FailableLongPredicate.java b/src/main/java/org/apache/commons/lang3/function/FailableLongPredicate.java index b267ead67fe..33714aa31d7 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableLongPredicate.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableLongPredicate.java @@ -60,9 +60,8 @@ static FailableLongPredicate truePredicate() { * Returns a predicate that negates this predicate. * * @return a predicate that negates this predicate. - * @throws E Thrown when this predicate fails. */ - default FailableLongPredicate negate() throws E { + default FailableLongPredicate negate() { return t -> !test(t); } diff --git a/src/main/java/org/apache/commons/lang3/function/FailableLongUnaryOperator.java b/src/main/java/org/apache/commons/lang3/function/FailableLongUnaryOperator.java index 6f980b7652b..b997eb064e1 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableLongUnaryOperator.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableLongUnaryOperator.java @@ -58,10 +58,9 @@ static FailableLongUnaryOperator nop() { * @param after the operator to apply after this one. * @return a composed {@code FailableLongUnaryOperator} like {@link LongUnaryOperator#andThen(LongUnaryOperator)}. * @throws NullPointerException if after is null. - * @throws E Thrown when a consumer fails. * @see #compose(FailableLongUnaryOperator) */ - default FailableLongUnaryOperator andThen(final FailableLongUnaryOperator after) throws E { + default FailableLongUnaryOperator andThen(final FailableLongUnaryOperator after) { Objects.requireNonNull(after); return (final long t) -> after.applyAsLong(applyAsLong(t)); } @@ -81,10 +80,9 @@ default FailableLongUnaryOperator andThen(final FailableLongUnaryOperator * @param before the operator to apply before this one. * @return a composed {@code FailableLongUnaryOperator} like {@link LongUnaryOperator#compose(LongUnaryOperator)}. * @throws NullPointerException if before is null. - * @throws E Thrown when a consumer fails. * @see #andThen(FailableLongUnaryOperator) */ - default FailableLongUnaryOperator compose(final FailableLongUnaryOperator before) throws E { + default FailableLongUnaryOperator compose(final FailableLongUnaryOperator before) { Objects.requireNonNull(before); return (final long v) -> applyAsLong(before.applyAsLong(v)); } diff --git a/src/main/java/org/apache/commons/lang3/function/FailablePredicate.java b/src/main/java/org/apache/commons/lang3/function/FailablePredicate.java index ce49539b953..160f2f57195 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailablePredicate.java +++ b/src/main/java/org/apache/commons/lang3/function/FailablePredicate.java @@ -63,9 +63,8 @@ static FailablePredicate truePredicate() { * Returns a predicate that negates this predicate. * * @return a predicate that negates this predicate. - * @throws E Thrown when this predicate fails. */ - default FailablePredicate negate() throws E { + default FailablePredicate negate() { return t -> !test(t); } From 180d948d7f0cf73fd9a657ecbcb382b2e9b22cb7 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Thu, 25 Jun 2020 10:42:13 -0400 Subject: [PATCH 0219/3230] [LANG-1568] Predicate add. --- .../lang3/function/FailableBiPredicate.java | 4 +- .../function/FailableDoublePredicate.java | 25 ++++---- .../lang3/function/FailableIntPredicate.java | 13 ++++ .../lang3/function/FailableLongPredicate.java | 13 ++++ .../lang3/function/FailablePredicate.java | 13 ++++ .../lang3/function/FailableFunctionsTest.java | 60 +++++++++++++++++++ 6 files changed, 113 insertions(+), 15 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/function/FailableBiPredicate.java b/src/main/java/org/apache/commons/lang3/function/FailableBiPredicate.java index 56c5028ec3e..f5894b32be6 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableBiPredicate.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableBiPredicate.java @@ -70,9 +70,9 @@ static FailableBiPredicate truePredicate() * @return a composed {@code FailableBiPredicate} like {@link BiPredicate#and(BiPredicate)}. * @throws NullPointerException if other is null */ - default FailableBiPredicate and(FailableBiPredicate other) { + default FailableBiPredicate and(final FailableBiPredicate other) { Objects.requireNonNull(other); - return (T t, U u) -> test(t, u) && other.test(t, u); + return (final T t, final U u) -> test(t, u) && other.test(t, u); } /** diff --git a/src/main/java/org/apache/commons/lang3/function/FailableDoublePredicate.java b/src/main/java/org/apache/commons/lang3/function/FailableDoublePredicate.java index 0c7def5aebc..badc2a5891d 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableDoublePredicate.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableDoublePredicate.java @@ -18,7 +18,6 @@ package org.apache.commons.lang3.function; import java.util.Objects; -import java.util.function.BiPredicate; import java.util.function.DoublePredicate; /** @@ -30,18 +29,6 @@ @FunctionalInterface public interface FailableDoublePredicate { - /** - * Returns a composed {@code FailableBiPredicate} like {@link BiPredicate#and(BiPredicate)}. - * - * @param other a predicate that will be logically-ANDed with this predicate. - * @return a composed {@code FailableBiPredicate} like {@link BiPredicate#and(BiPredicate)}. - * @throws NullPointerException if other is null - */ - default FailableDoublePredicate and(FailableDoublePredicate other) { - Objects.requireNonNull(other); - return t -> test(t) && other.test(t); - } - /** FALSE singleton */ @SuppressWarnings("rawtypes") FailableDoublePredicate FALSE = t -> false; @@ -70,6 +57,18 @@ static FailableDoublePredicate truePredicate() { return TRUE; } + /** + * Returns a composed {@code FailableDoublePredicate} like {@link DoublePredicate#and(DoublePredicate)}. + * + * @param other a predicate that will be logically-ANDed with this predicate. + * @return a composed {@code FailableDoublePredicate} like {@link DoublePredicate#and(DoublePredicate)}. + * @throws NullPointerException if other is null + */ + default FailableDoublePredicate and(final FailableDoublePredicate other) { + Objects.requireNonNull(other); + return t -> test(t) && other.test(t); + } + /** * Returns a predicate that negates this predicate. * diff --git a/src/main/java/org/apache/commons/lang3/function/FailableIntPredicate.java b/src/main/java/org/apache/commons/lang3/function/FailableIntPredicate.java index babfceb87ff..57e0cb1d19e 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableIntPredicate.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableIntPredicate.java @@ -17,6 +17,7 @@ package org.apache.commons.lang3.function; +import java.util.Objects; import java.util.function.IntPredicate; /** @@ -56,6 +57,18 @@ static FailableIntPredicate truePredicate() { return TRUE; } + /** + * Returns a composed {@code FailableIntPredicate} like {@link IntPredicate#and(IntPredicate)}. + * + * @param other a predicate that will be logically-ANDed with this predicate. + * @return a composed {@code FailableIntPredicate} like {@link IntPredicate#and(IntPredicate)}. + * @throws NullPointerException if other is null + */ + default FailableIntPredicate and(final FailableIntPredicate other) { + Objects.requireNonNull(other); + return t -> test(t) && other.test(t); + } + /** * Returns a predicate that negates this predicate. * diff --git a/src/main/java/org/apache/commons/lang3/function/FailableLongPredicate.java b/src/main/java/org/apache/commons/lang3/function/FailableLongPredicate.java index 33714aa31d7..154b1dfcead 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableLongPredicate.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableLongPredicate.java @@ -17,6 +17,7 @@ package org.apache.commons.lang3.function; +import java.util.Objects; import java.util.function.LongPredicate; /** @@ -56,6 +57,18 @@ static FailableLongPredicate truePredicate() { return TRUE; } + /** + * Returns a composed {@code FailableLongPredicate} like {@link LongPredicate#and(LongPredicate)}. + * + * @param other a predicate that will be logically-ANDed with this predicate. + * @return a composed {@code FailableLongPredicate} like {@link LongPredicate#and(LongPredicate)}. + * @throws NullPointerException if other is null + */ + default FailableLongPredicate and(final FailableLongPredicate other) { + Objects.requireNonNull(other); + return t -> test(t) && other.test(t); + } + /** * Returns a predicate that negates this predicate. * diff --git a/src/main/java/org/apache/commons/lang3/function/FailablePredicate.java b/src/main/java/org/apache/commons/lang3/function/FailablePredicate.java index 160f2f57195..081464a6946 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailablePredicate.java +++ b/src/main/java/org/apache/commons/lang3/function/FailablePredicate.java @@ -17,6 +17,7 @@ package org.apache.commons.lang3.function; +import java.util.Objects; import java.util.function.Predicate; /** @@ -59,6 +60,18 @@ static FailablePredicate truePredicate() { return TRUE; } + /** + * Returns a composed {@code FailablePredicate} like {@link Predicate#and(Predicate)}. + * + * @param other a predicate that will be logically-ANDed with this predicate. + * @return a composed {@code FailablePredicate} like {@link Predicate#and(Predicate)}. + * @throws NullPointerException if other is null + */ + default FailablePredicate and(final FailablePredicate other) { + Objects.requireNonNull(other); + return t -> test(t) && other.test(t); + } + /** * Returns a predicate that negates this predicate. * diff --git a/src/test/java/org/apache/commons/lang3/function/FailableFunctionsTest.java b/src/test/java/org/apache/commons/lang3/function/FailableFunctionsTest.java index 957225fcd60..085d83995b5 100644 --- a/src/test/java/org/apache/commons/lang3/function/FailableFunctionsTest.java +++ b/src/test/java/org/apache/commons/lang3/function/FailableFunctionsTest.java @@ -712,6 +712,18 @@ public void testBiPredicate() { assertTrue(predicate.test(null, null)); } + @Test + public void testBiPredicateAnd() throws Throwable { + assertTrue(FailableBiPredicate.TRUE.and(FailableBiPredicate.TRUE).test(null, null)); + assertFalse(FailableBiPredicate.TRUE.and(FailableBiPredicate.FALSE).test(null, null)); + assertFalse(FailableBiPredicate.FALSE.and(FailableBiPredicate.TRUE).test(null, null)); + assertFalse(FailableBiPredicate.FALSE.and(FailableBiPredicate.FALSE).test(null, null)); + // null tests + assertThrows(NullPointerException.class, () -> assertFalse(FailableBiPredicate.FALSE.and(null).test(null, null))); + assertThrows(NullPointerException.class, () -> assertTrue(FailableBiPredicate.TRUE.and(null).test(null, null))); + } + + @Test public void testBiPredicateNegate() throws Throwable { assertFalse(FailableBiPredicate.TRUE.negate().test(null, null)); assertFalse(FailableBiPredicate.truePredicate().negate().test(null, null)); @@ -774,6 +786,18 @@ public void testDoublePredicate() throws Throwable { failablePredicate.test(1d); } + @Test + public void testDoublePredicateAnd() throws Throwable { + assertTrue(FailableDoublePredicate.TRUE.and(FailableDoublePredicate.TRUE).test(0)); + assertFalse(FailableDoublePredicate.TRUE.and(FailableDoublePredicate.FALSE).test(0)); + assertFalse(FailableDoublePredicate.FALSE.and(FailableDoublePredicate.TRUE).test(0)); + assertFalse(FailableDoublePredicate.FALSE.and(FailableDoublePredicate.FALSE).test(0)); + // null tests + assertThrows(NullPointerException.class, () -> assertFalse(FailableDoublePredicate.FALSE.and(null).test(0))); + assertThrows(NullPointerException.class, () -> assertTrue(FailableDoublePredicate.TRUE.and(null).test(0))); + } + + @Test public void testDoublePredicateNegate() throws Throwable { assertFalse(FailableDoublePredicate.TRUE.negate().test(0d)); assertFalse(FailableDoublePredicate.truePredicate().negate().test(0d)); @@ -1052,6 +1076,18 @@ public void testIntPredicate() throws Throwable { failablePredicate.test(1); } + @Test + public void testIntPredicateAnd() throws Throwable { + assertTrue(FailableIntPredicate.TRUE.and(FailableIntPredicate.TRUE).test(0)); + assertFalse(FailableIntPredicate.TRUE.and(FailableIntPredicate.FALSE).test(0)); + assertFalse(FailableIntPredicate.FALSE.and(FailableIntPredicate.TRUE).test(0)); + assertFalse(FailableIntPredicate.FALSE.and(FailableIntPredicate.FALSE).test(0)); + // null tests + assertThrows(NullPointerException.class, () -> assertFalse(FailableIntPredicate.FALSE.and(null).test(0))); + assertThrows(NullPointerException.class, () -> assertTrue(FailableIntPredicate.TRUE.and(null).test(0))); + } + + @Test public void testIntPredicateNegate() throws Throwable { assertFalse(FailableIntPredicate.TRUE.negate().test(0)); assertFalse(FailableIntPredicate.truePredicate().negate().test(0)); @@ -1132,6 +1168,18 @@ public void testLongPredicate() throws Throwable { failablePredicate.test(1L); } + @Test + public void testLongPredicateAnd() throws Throwable { + assertTrue(FailableLongPredicate.TRUE.and(FailableLongPredicate.TRUE).test(0)); + assertFalse(FailableLongPredicate.TRUE.and(FailableLongPredicate.FALSE).test(0)); + assertFalse(FailableLongPredicate.FALSE.and(FailableLongPredicate.TRUE).test(0)); + assertFalse(FailableLongPredicate.FALSE.and(FailableLongPredicate.FALSE).test(0)); + // null tests + assertThrows(NullPointerException.class, () -> assertFalse(FailableLongPredicate.FALSE.and(null).test(0))); + assertThrows(NullPointerException.class, () -> assertTrue(FailableLongPredicate.TRUE.and(null).test(0))); + } + + @Test public void testLongPredicateNegate() throws Throwable { assertFalse(FailableLongPredicate.TRUE.negate().test(0L)); assertFalse(FailableLongPredicate.truePredicate().negate().test(0L)); @@ -1202,6 +1250,18 @@ public void testPredicate() { assertNotNull(instance); } + @Test + public void testPredicateAnd() throws Throwable { + assertTrue(FailablePredicate.TRUE.and(FailablePredicate.TRUE).test(null)); + assertFalse(FailablePredicate.TRUE.and(FailablePredicate.FALSE).test(null)); + assertFalse(FailablePredicate.FALSE.and(FailablePredicate.TRUE).test(null)); + assertFalse(FailablePredicate.FALSE.and(FailablePredicate.FALSE).test(null)); + // null tests + assertThrows(NullPointerException.class, () -> assertFalse(FailablePredicate.FALSE.and(null).test(null))); + assertThrows(NullPointerException.class, () -> assertTrue(FailablePredicate.TRUE.and(null).test(null))); + } + + @Test public void testPredicateNegate() throws Throwable { assertFalse(FailablePredicate.TRUE.negate().test(null)); assertFalse(FailablePredicate.truePredicate().negate().test(null)); From 268d4936d4136ce35af688617bbd6874b0854f4c Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Thu, 25 Jun 2020 10:52:37 -0400 Subject: [PATCH 0220/3230] [LANG-1568] Predicate or. --- .../lang3/function/FailableBiPredicate.java | 12 ++++ .../function/FailableDoublePredicate.java | 12 ++++ .../lang3/function/FailableIntPredicate.java | 12 ++++ .../lang3/function/FailableLongPredicate.java | 12 ++++ .../lang3/function/FailablePredicate.java | 12 ++++ .../lang3/function/FailableFunctionsTest.java | 72 ++++++++++++++++--- 6 files changed, 124 insertions(+), 8 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/function/FailableBiPredicate.java b/src/main/java/org/apache/commons/lang3/function/FailableBiPredicate.java index f5894b32be6..5258daacad6 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableBiPredicate.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableBiPredicate.java @@ -84,6 +84,18 @@ default FailableBiPredicate negate() { return (final T t, final U u) -> !test(t, u); } + /** + * Returns a composed {@code FailableBiPredicate} like {@link BiPredicate#and(BiPredicate)}. + * + * @param other a predicate that will be logically-ORed with this predicate. + * @return a composed {@code FailableBiPredicate} like {@link BiPredicate#and(BiPredicate)}. + * @throws NullPointerException if other is null + */ + default FailableBiPredicate or(final FailableBiPredicate other) { + Objects.requireNonNull(other); + return (final T t, final U u) -> test(t, u) || other.test(t, u); + } + /** * Tests the predicate. * diff --git a/src/main/java/org/apache/commons/lang3/function/FailableDoublePredicate.java b/src/main/java/org/apache/commons/lang3/function/FailableDoublePredicate.java index badc2a5891d..ec6b2cc6b75 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableDoublePredicate.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableDoublePredicate.java @@ -78,6 +78,18 @@ default FailableDoublePredicate negate() { return t -> !test(t); } + /** + * Returns a composed {@code FailableDoublePredicate} like {@link DoublePredicate#and(DoublePredicate)}. + * + * @param other a predicate that will be logically-ORed with this predicate. + * @return a composed {@code FailableDoublePredicate} like {@link DoublePredicate#and(DoublePredicate)}. + * @throws NullPointerException if other is null + */ + default FailableDoublePredicate or(final FailableDoublePredicate other) { + Objects.requireNonNull(other); + return t -> test(t) || other.test(t); + } + /** * Tests the predicate. * diff --git a/src/main/java/org/apache/commons/lang3/function/FailableIntPredicate.java b/src/main/java/org/apache/commons/lang3/function/FailableIntPredicate.java index 57e0cb1d19e..724d6bf4e7d 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableIntPredicate.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableIntPredicate.java @@ -78,6 +78,18 @@ default FailableIntPredicate negate() { return t -> !test(t); } + /** + * Returns a composed {@code FailableIntPredicate} like {@link IntPredicate#and(IntPredicate)}. + * + * @param other a predicate that will be logically-ORed with this predicate. + * @return a composed {@code FailableIntPredicate} like {@link IntPredicate#and(IntPredicate)}. + * @throws NullPointerException if other is null + */ + default FailableIntPredicate or(final FailableIntPredicate other) { + Objects.requireNonNull(other); + return t -> test(t) || other.test(t); + } + /** * Tests the predicate. * diff --git a/src/main/java/org/apache/commons/lang3/function/FailableLongPredicate.java b/src/main/java/org/apache/commons/lang3/function/FailableLongPredicate.java index 154b1dfcead..be97ca9b429 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailableLongPredicate.java +++ b/src/main/java/org/apache/commons/lang3/function/FailableLongPredicate.java @@ -78,6 +78,18 @@ default FailableLongPredicate negate() { return t -> !test(t); } + /** + * Returns a composed {@code FailableLongPredicate} like {@link LongPredicate#and(LongPredicate)}. + * + * @param other a predicate that will be logically-ORed with this predicate. + * @return a composed {@code FailableLongPredicate} like {@link LongPredicate#and(LongPredicate)}. + * @throws NullPointerException if other is null + */ + default FailableLongPredicate or(final FailableLongPredicate other) { + Objects.requireNonNull(other); + return t -> test(t) || other.test(t); + } + /** * Tests the predicate. * diff --git a/src/main/java/org/apache/commons/lang3/function/FailablePredicate.java b/src/main/java/org/apache/commons/lang3/function/FailablePredicate.java index 081464a6946..d2ecbc5656d 100644 --- a/src/main/java/org/apache/commons/lang3/function/FailablePredicate.java +++ b/src/main/java/org/apache/commons/lang3/function/FailablePredicate.java @@ -81,6 +81,18 @@ default FailablePredicate negate() { return t -> !test(t); } + /** + * Returns a composed {@code FailablePredicate} like {@link Predicate#and(Predicate)}. + * + * @param other a predicate that will be logically-ORed with this predicate. + * @return a composed {@code FailablePredicate} like {@link Predicate#and(Predicate)}. + * @throws NullPointerException if other is null + */ + default FailablePredicate or(final FailablePredicate other) { + Objects.requireNonNull(other); + return t -> test(t) || other.test(t); + } + /** * Tests the predicate. * diff --git a/src/test/java/org/apache/commons/lang3/function/FailableFunctionsTest.java b/src/test/java/org/apache/commons/lang3/function/FailableFunctionsTest.java index 085d83995b5..cac514d9a24 100644 --- a/src/test/java/org/apache/commons/lang3/function/FailableFunctionsTest.java +++ b/src/test/java/org/apache/commons/lang3/function/FailableFunctionsTest.java @@ -719,8 +719,10 @@ public void testBiPredicateAnd() throws Throwable { assertFalse(FailableBiPredicate.FALSE.and(FailableBiPredicate.TRUE).test(null, null)); assertFalse(FailableBiPredicate.FALSE.and(FailableBiPredicate.FALSE).test(null, null)); // null tests - assertThrows(NullPointerException.class, () -> assertFalse(FailableBiPredicate.FALSE.and(null).test(null, null))); - assertThrows(NullPointerException.class, () -> assertTrue(FailableBiPredicate.TRUE.and(null).test(null, null))); + assertThrows(NullPointerException.class, + () -> assertFalse(FailableBiPredicate.falsePredicate().and(null).test(null, null))); + assertThrows(NullPointerException.class, + () -> assertTrue(FailableBiPredicate.truePredicate().and(null).test(null, null))); } @Test @@ -731,6 +733,19 @@ public void testBiPredicateNegate() throws Throwable { assertTrue(FailableBiPredicate.falsePredicate().negate().test(null, null)); } + @Test + public void testBiPredicateOr() throws Throwable { + assertTrue(FailableBiPredicate.TRUE.or(FailableBiPredicate.TRUE).test(null, null)); + assertTrue(FailableBiPredicate.TRUE.or(FailableBiPredicate.FALSE).test(null, null)); + assertTrue(FailableBiPredicate.FALSE.or(FailableBiPredicate.TRUE).test(null, null)); + assertFalse(FailableBiPredicate.FALSE.or(FailableBiPredicate.FALSE).test(null, null)); + // null tests + assertThrows(NullPointerException.class, + () -> assertFalse(FailableBiPredicate.falsePredicate().or(null).test(null, null))); + assertThrows(NullPointerException.class, + () -> assertTrue(FailableBiPredicate.truePredicate().or(null).test(null, null))); + } + @Test public void testCallable() { FailureOnOddInvocations.invocations = 0; @@ -793,8 +808,10 @@ public void testDoublePredicateAnd() throws Throwable { assertFalse(FailableDoublePredicate.FALSE.and(FailableDoublePredicate.TRUE).test(0)); assertFalse(FailableDoublePredicate.FALSE.and(FailableDoublePredicate.FALSE).test(0)); // null tests - assertThrows(NullPointerException.class, () -> assertFalse(FailableDoublePredicate.FALSE.and(null).test(0))); - assertThrows(NullPointerException.class, () -> assertTrue(FailableDoublePredicate.TRUE.and(null).test(0))); + assertThrows(NullPointerException.class, + () -> assertFalse(FailableDoublePredicate.falsePredicate().and(null).test(0))); + assertThrows(NullPointerException.class, + () -> assertTrue(FailableDoublePredicate.truePredicate().and(null).test(0))); } @Test @@ -805,6 +822,19 @@ public void testDoublePredicateNegate() throws Throwable { assertTrue(FailableDoublePredicate.falsePredicate().negate().test(0d)); } + @Test + public void testDoublePredicateOr() throws Throwable { + assertTrue(FailableDoublePredicate.TRUE.or(FailableDoublePredicate.TRUE).test(0)); + assertTrue(FailableDoublePredicate.TRUE.or(FailableDoublePredicate.FALSE).test(0)); + assertTrue(FailableDoublePredicate.FALSE.or(FailableDoublePredicate.TRUE).test(0)); + assertFalse(FailableDoublePredicate.FALSE.or(FailableDoublePredicate.FALSE).test(0)); + // null tests + assertThrows(NullPointerException.class, + () -> assertFalse(FailableDoublePredicate.falsePredicate().or(null).test(0))); + assertThrows(NullPointerException.class, + () -> assertTrue(FailableDoublePredicate.truePredicate().or(null).test(0))); + } + @Test public void testDoubleUnaryOperatorAndThen() throws Throwable { final Testable testable = new Testable<>(null); @@ -1083,8 +1113,10 @@ public void testIntPredicateAnd() throws Throwable { assertFalse(FailableIntPredicate.FALSE.and(FailableIntPredicate.TRUE).test(0)); assertFalse(FailableIntPredicate.FALSE.and(FailableIntPredicate.FALSE).test(0)); // null tests - assertThrows(NullPointerException.class, () -> assertFalse(FailableIntPredicate.FALSE.and(null).test(0))); - assertThrows(NullPointerException.class, () -> assertTrue(FailableIntPredicate.TRUE.and(null).test(0))); + assertThrows(NullPointerException.class, + () -> assertFalse(FailableIntPredicate.falsePredicate().and(null).test(0))); + assertThrows(NullPointerException.class, + () -> assertTrue(FailableIntPredicate.truePredicate().and(null).test(0))); } @Test @@ -1095,6 +1127,19 @@ public void testIntPredicateNegate() throws Throwable { assertTrue(FailableIntPredicate.falsePredicate().negate().test(0)); } + @Test + public void testIntPredicateOr() throws Throwable { + assertTrue(FailableIntPredicate.TRUE.or(FailableIntPredicate.TRUE).test(0)); + assertTrue(FailableIntPredicate.TRUE.or(FailableIntPredicate.FALSE).test(0)); + assertTrue(FailableIntPredicate.FALSE.or(FailableIntPredicate.TRUE).test(0)); + assertFalse(FailableIntPredicate.FALSE.or(FailableIntPredicate.FALSE).test(0)); + // null tests + assertThrows(NullPointerException.class, + () -> assertFalse(FailableIntPredicate.falsePredicate().or(null).test(0))); + assertThrows(NullPointerException.class, + () -> assertTrue(FailableIntPredicate.truePredicate().or(null).test(0))); + } + @Test public void testIntUnaryOperatorAndThen() throws Throwable { final Testable testable = new Testable<>(null); @@ -1175,8 +1220,8 @@ public void testLongPredicateAnd() throws Throwable { assertFalse(FailableLongPredicate.FALSE.and(FailableLongPredicate.TRUE).test(0)); assertFalse(FailableLongPredicate.FALSE.and(FailableLongPredicate.FALSE).test(0)); // null tests - assertThrows(NullPointerException.class, () -> assertFalse(FailableLongPredicate.FALSE.and(null).test(0))); - assertThrows(NullPointerException.class, () -> assertTrue(FailableLongPredicate.TRUE.and(null).test(0))); + assertThrows(NullPointerException.class, () -> assertFalse(FailableLongPredicate.falsePredicate().and(null).test(0))); + assertThrows(NullPointerException.class, () -> assertTrue(FailableLongPredicate.truePredicate().and(null).test(0))); } @Test @@ -1187,6 +1232,17 @@ public void testLongPredicateNegate() throws Throwable { assertTrue(FailableLongPredicate.falsePredicate().negate().test(0L)); } + @Test + public void testLongPredicateOr() throws Throwable { + assertTrue(FailableLongPredicate.TRUE.or(FailableLongPredicate.TRUE).test(0)); + assertTrue(FailableLongPredicate.TRUE.or(FailableLongPredicate.FALSE).test(0)); + assertTrue(FailableLongPredicate.FALSE.or(FailableLongPredicate.TRUE).test(0)); + assertFalse(FailableLongPredicate.FALSE.or(FailableLongPredicate.FALSE).test(0)); + // null tests + assertThrows(NullPointerException.class, () -> assertFalse(FailableLongPredicate.falsePredicate().or(null).test(0))); + assertThrows(NullPointerException.class, () -> assertTrue(FailableLongPredicate.truePredicate().or(null).test(0))); + } + @Test public void testLongUnaryOperatorAndThen() throws Throwable { final Testable testable = new Testable<>(null); From b69c4759ed286546ba5437d9fcb6d24a1e2d3f8d Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Thu, 25 Jun 2020 13:57:28 -0400 Subject: [PATCH 0221/3230] [LANG-1568] Javadoc. --- .../commons/lang3/function/Failable.java | 35 +++++++------------ 1 file changed, 12 insertions(+), 23 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/function/Failable.java b/src/main/java/org/apache/commons/lang3/function/Failable.java index d2a12a07d69..d4bf30d93e8 100644 --- a/src/main/java/org/apache/commons/lang3/function/Failable.java +++ b/src/main/java/org/apache/commons/lang3/function/Failable.java @@ -41,16 +41,13 @@ * constructs like: * *

      - * {
      - *     @code
      - *     Consumer consumer = (m) -> {
      - *         try {
      - *             m.invoke(o, args);
      - *         } catch (Throwable t) {
      - *             throw Failable.rethrow(t);
      - *         }
      - *     };
      - * }
      + * Consumer<java.lang.reflect.Method-> consumer = (m) -> {
      + *     try {
      + *         m.invoke(o, args);
      + *     } catch (Throwable t) {
      + *         throw Failable.rethrow(t);
      + *     }
      + * };
        * 
      * *

      @@ -59,9 +56,7 @@ *

      * *
      - * {@code
      - *   Functions.accept((m) -> m.invoke(o,args));
      - * }
      + * Functions.accept((m) -> m.invoke(o, args));
        * 
      * *

      @@ -490,11 +485,8 @@ public static boolean test(final FailablePredicate - * { - * @code - * final FileInputStream fis = new FileInputStream("my.file"); - * Functions.tryWithResources(useInputStream(fis), null, () -> fis.close()); - * } + * final FileInputStream fis = new FileInputStream("my.file"); + * Functions.tryWithResources(useInputStream(fis), null, () -> fis.close()); *

      * * @param action The action to execute. This object will always be invoked. @@ -553,11 +545,8 @@ public static void tryWithResources(final FailableRunnable * {@link Throwable} is rethrown. Example use: * *
      -     * {
      -     *     @code
      -     *     final FileInputStream fis = new FileInputStream("my.file");
      -     *     Functions.tryWithResources(useInputStream(fis), () -> fis.close());
      -     * }
      +     * final FileInputStream fis = new FileInputStream("my.file");
      +     * Functions.tryWithResources(useInputStream(fis), () -> fis.close());
            * 
      * * @param action The action to execute. This object will always be invoked. From dd5d284e86cc83b1ef8088fa8cba383d95957850 Mon Sep 17 00:00:00 2001 From: XenoAmess Date: Fri, 26 Jun 2020 16:54:16 +0800 Subject: [PATCH 0222/3230] refine tests --- .../commons/lang3/time/FastDateParserTest.java | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/src/test/java/org/apache/commons/lang3/time/FastDateParserTest.java b/src/test/java/org/apache/commons/lang3/time/FastDateParserTest.java index 6ede003eec8..001f47415c5 100644 --- a/src/test/java/org/apache/commons/lang3/time/FastDateParserTest.java +++ b/src/test/java/org/apache/commons/lang3/time/FastDateParserTest.java @@ -708,29 +708,37 @@ public void testLang1380() throws ParseException { assertEquals(expected.getTime(), fdp.parse("14 avr 2014")); } + @Test + public void java15BuggyLocaleTestAll() throws ParseException { + for (final Locale locale : Locale.getAvailableLocales()) { + testSingleLocale(locale); + } + } + @Test public void java15BuggyLocaleTest() throws ParseException { final String buggyLocaleName = "ff_LR_#Adlm"; Locale buggyLocale = null; - for (final Locale locale : Locale.getAvailableLocales()) { if (buggyLocaleName.equals(locale.toString())) { buggyLocale = locale; break; } } - if (buggyLocale == null) { return; } + testSingleLocale(buggyLocale); + } + private void testSingleLocale(Locale locale) throws ParseException { final Calendar cal = Calendar.getInstance(GMT); cal.clear(); cal.set(2003, Calendar.FEBRUARY, 10); - final SimpleDateFormat sdf = new SimpleDateFormat(LONG_FORMAT, buggyLocale); + final SimpleDateFormat sdf = new SimpleDateFormat(LONG_FORMAT, locale); final String formattedDate = sdf.format(cal.getTime()); sdf.parse(formattedDate); - sdf.parse(formattedDate.toUpperCase(buggyLocale)); - sdf.parse(formattedDate.toLowerCase(buggyLocale)); + sdf.parse(formattedDate.toUpperCase(locale)); + sdf.parse(formattedDate.toLowerCase(locale)); } } From d41660809d53b1679a6dd697e07679da5e543f4f Mon Sep 17 00:00:00 2001 From: Jochen Wiedmann Date: Fri, 26 Jun 2020 11:51:06 +0200 Subject: [PATCH 0223/3230] Adding Javadocs for the Locks.Lock class. Improvements in the test suite. --- .../commons/lang3/concurrent/Locks.java | 178 +++++++++++++++++- .../commons/lang3/concurrent/LocksTest.java | 37 ++++ 2 files changed, 213 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/concurrent/Locks.java b/src/main/java/org/apache/commons/lang3/concurrent/Locks.java index 28df9c0953a..48e16eb8d0a 100644 --- a/src/main/java/org/apache/commons/lang3/concurrent/Locks.java +++ b/src/main/java/org/apache/commons/lang3/concurrent/Locks.java @@ -70,31 +70,174 @@ */ public class Locks { + /** + * This class implements a wrapper for a locked (hidden) object, and + * provides the means to access it. The basic idea, is that the user + * code forsakes all references to the locked object, using only the + * wrapper object, and the accessor methods + * {@link #acceptReadLocked(FailableConsumer)}, + * {@link #acceptWriteLocked(FailableConsumer)}, + * {@link #applyReadLocked(FailableFunction)}, and + * {@link #applyWriteLocked(FailableFunction)}. By doing so, the + * necessary protections are guaranteed. + * @param The locked (hidden) objects type. + * + * @since 3.11 + */ public static class Lock { - private final StampedLock lock = new StampedLock(); private final O lockedObject; + /** + * Creates a new instance with the given locked object. This + * constructor is supposed to be used for subclassing only. + * In general, it is suggested to use {@link Locks#lock(Object)} + * instead. + * @param lockedObject The locked (hidden) object. The caller is + * supposed to drop all references to the locked object. + */ public Lock(final O lockedObject) { this.lockedObject = Objects.requireNonNull(lockedObject, "Locked Object"); } + /** + * Provides read (shared, non-exclusive) access to the locked (hidden) object. + * More precisely, what the method will do (in the given order): + *
        + *
      1. Obtain a read (shared) lock on the locked (hidden) object. + * The current thread may block, until such a lock is granted. + *
      2. + *
      3. Invokes the given {@link FailableConsumer consumer}, passing the + * locked object as the parameter.
      4. + *
      5. Release the lock, as soon as the consumers invocation is done. + * If the invocation results in an error, the lock will be released + * anyways. + *
      6. + *
      + * @param consumer The consumer, which is being invoked to use the + * hidden object, which will be passed as the consumers parameter. + * @see #acceptWriteLocked(FailableConsumer) + * @see #applyReadLocked(FailableFunction) + */ public void acceptReadLocked(final FailableConsumer consumer) { lockAcceptUnlock(() -> lock.readLock(), consumer); } + /** + * Provides write (exclusive) access to the locked (hidden) object. + * More precisely, what the method will do (in the given order): + *
        + *
      1. Obtain a write (shared) lock on the locked (hidden) object. + * The current thread may block, until such a lock is granted. + *
      2. + *
      3. Invokes the given {@link FailableConsumer consumer}, passing the + * locked object as the parameter.
      4. + *
      5. Release the lock, as soon as the consumers invocation is done. + * If the invocation results in an error, the lock will be released + * anyways. + *
      6. + *
      + * @param consumer The consumer, which is being invoked to use the + * hidden object, which will be passed as the consumers parameter. + * @see #acceptReadLocked(FailableConsumer) + * @see #applyWriteLocked(FailableFunction) + */ public void acceptWriteLocked(final FailableConsumer consumer) { lockAcceptUnlock(() -> lock.writeLock(), consumer); } + /** + * Provides read (shared, non-exclusive) access to the locked (hidden) + * object for the purpose of computing a result object. + * More precisely, what the method will do (in the given order): + *
        + *
      1. Obtain a read (shared) lock on the locked (hidden) object. + * The current thread may block, until such a lock is granted. + *
      2. + *
      3. Invokes the given {@link FailableFunction function}, passing the + * locked object as the parameter, receiving the functions result.
      4. + *
      5. Release the lock, as soon as the consumers invocation is done. + * If the invocation results in an error, the lock will be released + * anyways. + *
      6. + *
      7. + * Return the result object, that has been received from the + * functions invocation.
      8. + *
      + * + * Example: Suggest, that the hidden object is a list, and we + * wish to know the current size of the list. This might be achieved + * with the following: + * + *
      +         *   private Lock<List<Object>> listLock;
      +         *
      +         *   public int getCurrentListSize() {
      +         *       final Integer sizeInteger
      +         *           = listLock.applyReadLocked((list) -> Integer.valueOf(list.size));
      +         *       return sizeInteger.intValue();
      +         *   }
      +         * 
      + * @param The result type (both the functions, and this method's.) + * @param function The function, which is being invoked to compute the + * result. The function will receive the hidden object. + * @return The result object, which has been returned by the + * functions invocation. + * @throws IllegalStateException The result object would be, in fact, + * the hidden object. This would extend access to the hidden object + * beyond this methods lifetime and will therefore be prevented. + * @see #acceptReadLocked(FailableConsumer) + * @see #applyWriteLocked(FailableFunction) + */ public T applyReadLocked(final FailableFunction function) { return lockApplyUnlock(() -> lock.readLock(), function); } + /** + * Provides write (exclusive) access to the locked (hidden) + * object for the purpose of computing a result object. + * More precisely, what the method will do (in the given order): + *
        + *
      1. Obtain a read (shared) lock on the locked (hidden) object. + * The current thread may block, until such a lock is granted. + *
      2. + *
      3. Invokes the given {@link FailableFunction function}, passing the + * locked object as the parameter, receiving the functions result.
      4. + *
      5. Release the lock, as soon as the consumers invocation is done. + * If the invocation results in an error, the lock will be released + * anyways. + *
      6. + *
      7. + * Return the result object, that has been received from the + * functions invocation.
      8. + *
      + * @param The result type (both the functions, and this method's.) + * @param function The function, which is being invoked to compute the + * result. The function will receive the hidden object. + * @return The result object, which has been returned by the + * functions invocation. + * @throws IllegalStateException The result object would be, in fact, + * the hidden object. This would extend access to the hidden object + * beyond this methods lifetime and will therefore be prevented. + * @see #acceptReadLocked(FailableConsumer) + * @see #applyWriteLocked(FailableFunction) + */ public T applyWriteLocked(final FailableFunction function) { return lockApplyUnlock(() -> lock.writeLock(), function); } + /** + * This method provides the actual implementation for + * {@link #acceptReadLocked(FailableConsumer)}, and + * {@link #acceptWriteLocked(FailableConsumer)}. + * @param stampSupplier A supplier for the lock. (This provides, in + * fact, a long, because a {@link StampedLock} is used internally.) + * @param consumer The consumer, which is to be given access to the + * locked (hidden) object, which will be passed as a parameter. + * @see #acceptReadLocked(FailableConsumer) + * @see #acceptWriteLocked(FailableConsumer) + * @see #lockApplyUnlock(LongSupplier, FailableFunction) + */ protected void lockAcceptUnlock(final LongSupplier stampSupplier, final FailableConsumer consumer) { final long stamp = stampSupplier.getAsLong(); try { @@ -106,10 +249,33 @@ protected void lockAcceptUnlock(final LongSupplier stampSupplier, final Failable } } + /** + * This method provides the actual implementation for + * {@link #applyReadLocked(FailableFunction)}, and + * {@link #applyWriteLocked(FailableFunction)}. + * @param The result type (both the functions, and this method's.) + * @param stampSupplier A supplier for the lock. (This provides, in + * fact, a long, because a {@link StampedLock} is used internally.) + * @param function The function, which is being invoked to compute + * the result object. This function will receive the locked (hidden) + * object as a parameter. + * @return The result object, which has been returned by the + * functions invocation. + * @throws IllegalStateException The result object would be, in fact, + * the hidden object. This would extend access to the hidden object + * beyond this methods lifetime and will therefore be prevented. + * @see #applyReadLocked(FailableFunction) + * @see #applyWriteLocked(FailableFunction) + * @see #lockAcceptUnlock(LongSupplier, FailableConsumer) + */ protected T lockApplyUnlock(final LongSupplier stampSupplier, final FailableFunction function) { final long stamp = stampSupplier.getAsLong(); try { - return function.apply(lockedObject); + final T t = function.apply(lockedObject); + if (t == lockedObject) { + throw new IllegalStateException("The returned object is, in fact, the hidden object."); + } + return t; } catch (final Throwable t) { throw Failable.rethrow(t); } finally { @@ -118,6 +284,14 @@ protected T lockApplyUnlock(final LongSupplier stampSupplier, final Failable } } + /** + * Creates a new instance of {@link Lock} with the given locked + * (hidden) object. + * @param The locked objects type. + * @param object The locked (hidden) object. + * @return The created instance, a {@link Lock lock} for the + * given object. + */ public static Locks.Lock lock(final O object) { return new Locks.Lock<>(object); } diff --git a/src/test/java/org/apache/commons/lang3/concurrent/LocksTest.java b/src/test/java/org/apache/commons/lang3/concurrent/LocksTest.java index 2d577ecdb77..706281ec918 100644 --- a/src/test/java/org/apache/commons/lang3/concurrent/LocksTest.java +++ b/src/test/java/org/apache/commons/lang3/concurrent/LocksTest.java @@ -16,7 +16,11 @@ */ package org.apache.commons.lang3.concurrent; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotSame; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.util.function.LongConsumer; @@ -36,6 +40,7 @@ public void testReadLock() throws Exception { runTest(DELAY, false, l -> assertTrue(l < NUMBER_OF_THREADS*DELAY)); } + @Test public void testWriteLock() throws Exception { final long DELAY = 100; /** If our threads are running concurrently, then we expect to be no faster @@ -44,6 +49,38 @@ public void testWriteLock() throws Exception { runTest(DELAY, true, l -> assertTrue(l >= NUMBER_OF_THREADS*DELAY)); } + @Test + public void testResultValidation() { + final Object hidden = new Object(); + final Lock lock = Locks.lock(hidden); + final Object o1 = lock.applyReadLocked((h) -> { + return new Object(); + }); + assertNotNull(o1); + assertNotSame(hidden, o1); + final Object o2 = lock.applyWriteLocked((h) -> { + return new Object(); + }); + assertNotNull(o2); + assertNotSame(hidden, o2); + try { + lock.applyReadLocked((h) -> { + return hidden; + }); + fail("Expected Exception"); + } catch (IllegalStateException e) { + assertEquals("The returned object is, in fact, the hidden object.", e.getMessage()); + } + try { + lock.applyReadLocked((h) -> { + return hidden; + }); + fail("Expected Exception"); + } catch (IllegalStateException e) { + assertEquals("The returned object is, in fact, the hidden object.", e.getMessage()); + } + } + private void runTest(final long delay, final boolean exclusiveLock, final LongConsumer runTimeCheck) throws InterruptedException { final boolean[] booleanValues = new boolean[10]; final Lock lock = Locks.lock(booleanValues); From 567388428cab9b2aec090f4c1641a69feb6f5a5d Mon Sep 17 00:00:00 2001 From: XenoAmess Date: Mon, 1 Jun 2020 00:46:58 +0800 Subject: [PATCH 0224/3230] performance improve. --- .../apache/commons/lang3/CharSequenceUtils.java | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/src/main/java/org/apache/commons/lang3/CharSequenceUtils.java b/src/main/java/org/apache/commons/lang3/CharSequenceUtils.java index c6af33a068c..0d9db8e76ad 100644 --- a/src/main/java/org/apache/commons/lang3/CharSequenceUtils.java +++ b/src/main/java/org/apache/commons/lang3/CharSequenceUtils.java @@ -134,6 +134,13 @@ static int indexOf(final CharSequence cs, final int searchChar, int start) { * @return the index where the search sequence was found */ static int indexOf(final CharSequence cs, final CharSequence searchChar, final int start) { + if (cs instanceof String) { + return ((String) cs).indexOf(searchChar.toString(), start); + } else if (cs instanceof StringBuilder) { + return ((StringBuilder) cs).indexOf(searchChar.toString(), start); + } else if (cs instanceof StringBuffer) { + return ((StringBuffer) cs).indexOf(searchChar.toString(), start); + } return cs.toString().indexOf(searchChar.toString(), start); // if (cs instanceof String && searchChar instanceof String) { // // TODO: Do we assume searchChar is usually relatively small; @@ -218,6 +225,13 @@ static int lastIndexOf(final CharSequence cs, final int searchChar, int start) { * @return the index where the search sequence was found */ static int lastIndexOf(final CharSequence cs, final CharSequence searchChar, final int start) { + if (cs instanceof String) { + return ((String) cs).lastIndexOf((String) searchChar, start); + } else if (cs instanceof StringBuilder) { + return ((StringBuilder) cs).lastIndexOf((String) searchChar, start); + } else if (cs instanceof StringBuffer) { + return ((StringBuffer) cs).lastIndexOf((String) searchChar, start); + } return cs.toString().lastIndexOf(searchChar.toString(), start); // if (cs instanceof String && searchChar instanceof String) { // // TODO: Do we assume searchChar is usually relatively small; From 3ef823e8e1ff4f12636fc78ab84de6042f6efd9f Mon Sep 17 00:00:00 2001 From: XenoAmess Date: Mon, 1 Jun 2020 00:48:14 +0800 Subject: [PATCH 0225/3230] performance improve. --- .../org/apache/commons/lang3/CharSequenceUtils.java | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/CharSequenceUtils.java b/src/main/java/org/apache/commons/lang3/CharSequenceUtils.java index 0d9db8e76ad..012a16d7b48 100644 --- a/src/main/java/org/apache/commons/lang3/CharSequenceUtils.java +++ b/src/main/java/org/apache/commons/lang3/CharSequenceUtils.java @@ -251,15 +251,7 @@ static int lastIndexOf(final CharSequence cs, final CharSequence searchChar, fin * @return the resulting char array */ static char[] toCharArray(final CharSequence cs) { - if (cs instanceof String) { - return ((String) cs).toCharArray(); - } - final int sz = cs.length(); - final char[] array = new char[cs.length()]; - for (int i = 0; i < sz; i++) { - array[i] = cs.charAt(i); - } - return array; + return cs.toString().toCharArray(); } /** From 68cb8af7e402041e33e931f33bc60a32d7b9ce95 Mon Sep 17 00:00:00 2001 From: XenoAmess Date: Mon, 1 Jun 2020 01:16:19 +0800 Subject: [PATCH 0226/3230] Revert "performance improve." This reverts commit 3b05b95a --- .../org/apache/commons/lang3/CharSequenceUtils.java | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/apache/commons/lang3/CharSequenceUtils.java b/src/main/java/org/apache/commons/lang3/CharSequenceUtils.java index 012a16d7b48..0d9db8e76ad 100644 --- a/src/main/java/org/apache/commons/lang3/CharSequenceUtils.java +++ b/src/main/java/org/apache/commons/lang3/CharSequenceUtils.java @@ -251,7 +251,15 @@ static int lastIndexOf(final CharSequence cs, final CharSequence searchChar, fin * @return the resulting char array */ static char[] toCharArray(final CharSequence cs) { - return cs.toString().toCharArray(); + if (cs instanceof String) { + return ((String) cs).toCharArray(); + } + final int sz = cs.length(); + final char[] array = new char[cs.length()]; + for (int i = 0; i < sz; i++) { + array[i] = cs.charAt(i); + } + return array; } /** From dee8f6fb849fd3b7d928f13e273f8160f0a45f5b Mon Sep 17 00:00:00 2001 From: XenoAmess Date: Mon, 1 Jun 2020 01:51:43 +0800 Subject: [PATCH 0227/3230] implement lastIndexOf --- .../commons/lang3/CharSequenceUtils.java | 78 +++++++++++---- .../commons/lang3/CharSequenceUtilsTest.java | 95 +++++++++++++++++++ 2 files changed, 156 insertions(+), 17 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/CharSequenceUtils.java b/src/main/java/org/apache/commons/lang3/CharSequenceUtils.java index 0d9db8e76ad..4dab0637e4b 100644 --- a/src/main/java/org/apache/commons/lang3/CharSequenceUtils.java +++ b/src/main/java/org/apache/commons/lang3/CharSequenceUtils.java @@ -216,6 +216,8 @@ static int lastIndexOf(final CharSequence cs, final int searchChar, int start) { return NOT_FOUND; } + static final int TO_STRING_LIMIT = 16; + /** * Used by the lastIndexOf(CharSequence methods) as a green implementation of lastIndexOf * @@ -224,24 +226,66 @@ static int lastIndexOf(final CharSequence cs, final int searchChar, int start) { * @param start the start index * @return the index where the search sequence was found */ - static int lastIndexOf(final CharSequence cs, final CharSequence searchChar, final int start) { - if (cs instanceof String) { - return ((String) cs).lastIndexOf((String) searchChar, start); - } else if (cs instanceof StringBuilder) { - return ((StringBuilder) cs).lastIndexOf((String) searchChar, start); - } else if (cs instanceof StringBuffer) { - return ((StringBuffer) cs).lastIndexOf((String) searchChar, start); + static int lastIndexOf(final CharSequence cs, final CharSequence searchChar, int start) { + if (searchChar instanceof String) { + if (cs instanceof String) { + return ((String) cs).lastIndexOf((String) searchChar, start); + } else if (cs instanceof StringBuilder) { + return ((StringBuilder) cs).lastIndexOf((String) searchChar, start); + } else if (cs instanceof StringBuffer) { + return ((StringBuffer) cs).lastIndexOf((String) searchChar, start); + } } - return cs.toString().lastIndexOf(searchChar.toString(), start); -// if (cs instanceof String && searchChar instanceof String) { -// // TODO: Do we assume searchChar is usually relatively small; -// // If so then calling toString() on it is better than reverting to -// // the green implementation in the else block -// return ((String) cs).lastIndexOf((String) searchChar, start); -// } else { -// // TODO: Implement rather than convert to String -// return cs.toString().lastIndexOf(searchChar.toString(), start); -// } + + int len1 = cs.length(); + int len2 = searchChar.length(); + + if (start > len1) { + start = len1; + } + + if (start < 0 || len2 < 0 || len2 > len1) { + return -1; + } + + if (len2 == 0) { + return start; + } + + if (len2 <= TO_STRING_LIMIT) { + if (cs instanceof String) { + return ((String) cs).lastIndexOf(searchChar.toString(), start); + } else if (cs instanceof StringBuilder) { + return ((StringBuilder) cs).lastIndexOf(searchChar.toString(), start); + } else if (cs instanceof StringBuffer) { + return ((StringBuffer) cs).lastIndexOf(searchChar.toString(), start); + } + } + + if (start + len2 > len1) { + start = len1 - len2; + } + + if (check(cs, searchChar, len2, start)) { + return start; + } + + for (int i = start - 1; i >= 0; i--) { + if (check(cs, searchChar, len2, i)) { + return i; + } + } + + return -1; + } + + private static boolean check(final CharSequence cs, final CharSequence searchChar, int len2, int start1) { + for (int i = 0; i < len2; i++) { + if (cs.charAt(start1 + i) != searchChar.charAt(i)) { + return false; + } + } + return true; } /** diff --git a/src/test/java/org/apache/commons/lang3/CharSequenceUtilsTest.java b/src/test/java/org/apache/commons/lang3/CharSequenceUtilsTest.java index e7dd3b48d37..c230c4507be 100644 --- a/src/test/java/org/apache/commons/lang3/CharSequenceUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/CharSequenceUtilsTest.java @@ -16,6 +16,7 @@ */ package org.apache.commons.lang3; +import static java.nio.CharBuffer.wrap; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -26,7 +27,11 @@ import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; +import java.nio.CharBuffer; +import java.util.Random; +import java.util.stream.IntStream; +import org.apache.commons.lang3.text.StrBuilder; import org.junit.jupiter.api.Test; /** @@ -186,4 +191,94 @@ public void testToCharArray() { assertArrayEquals(expected, CharSequenceUtils.toCharArray(builder.toString())); } + static class WrapperString implements CharSequence { + CharSequence inner; + + public WrapperString(CharSequence inner) { + this.inner = inner; + } + + @Override + public int length() { + return inner.length(); + } + + @Override + public char charAt(int index) { + return inner.charAt(index); + } + + @Override + public CharSequence subSequence(int start, int end) { + return inner.subSequence(start, end); + } + + @Override + public String toString() { + return inner.toString(); + } + + @Override + public IntStream chars() { + return inner.chars(); + } + + @Override + public IntStream codePoints() { + return inner.codePoints(); + } + } + + @Test + public void testNewLastIndexOf() { + testNewLastIndexOfSingle("808087847-1321060740-635567660180086727-925755305", "-1321060740-635567660", 21); + testNewLastIndexOfSingle("", ""); + testNewLastIndexOfSingle("1", ""); + testNewLastIndexOfSingle("", "1"); + testNewLastIndexOfSingle("1", "1"); + testNewLastIndexOfSingle("11", "1"); + testNewLastIndexOfSingle("1", "11"); + + Random random = new Random(); + StringBuilder seg = new StringBuilder(); + while (seg.length() <= CharSequenceUtils.TO_STRING_LIMIT) { + seg.append(random.nextInt()); + } + StringBuilder original = new StringBuilder(seg); + testNewLastIndexOfSingle(original, seg); + for (int i = 0; i < 100; i++) { + if (random.nextDouble() < 0.5) { + original.append(random.nextInt() % 10); + } else { + original = new StringBuilder().append(String.valueOf(random.nextInt() % 100)).append(original); + } + testNewLastIndexOfSingle(original, seg); + } + } + + private void testNewLastIndexOfSingle(CharSequence a, CharSequence b) { + int maxa = Math.max(a.length(), b.length()); + for (int i = -maxa-10; i <= maxa+10; i++) { + testNewLastIndexOfSingle(a, b, i); + } + } + + private void testNewLastIndexOfSingle(CharSequence a, CharSequence b, int start) { + testNewLastIndexOfSingleSingle(a, b, start); + testNewLastIndexOfSingleSingle(b, a, start); + } + + private void testNewLastIndexOfSingleSingle(CharSequence a, CharSequence b, int start) { + int expected = a.toString().lastIndexOf(b.toString(), start); +// assertEquals( +// expected, +// lastIndexOf(new WrapperString(a), b, start), +// "testNewLastIndexOf fails! original : " + a + " seg : " + b + " start : " + start +// ); + assertEquals( + expected, + CharSequenceUtils.lastIndexOf(new WrapperString(a.toString()), b.toString(), start), + "testNewLastIndexOf fails! original : " + a + " seg : " + b + " start : " + start + ); + } } From 217da1e6aa2b2c9f626ed2efa42e3e3996175571 Mon Sep 17 00:00:00 2001 From: XenoAmess Date: Mon, 1 Jun 2020 02:26:14 +0800 Subject: [PATCH 0228/3230] implement lastIndexOf --- .../commons/lang3/CharSequenceUtils.java | 31 +++++++++++++------ .../commons/lang3/CharSequenceUtilsTest.java | 23 +++----------- 2 files changed, 25 insertions(+), 29 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/CharSequenceUtils.java b/src/main/java/org/apache/commons/lang3/CharSequenceUtils.java index 4dab0637e4b..01de17c2be6 100644 --- a/src/main/java/org/apache/commons/lang3/CharSequenceUtils.java +++ b/src/main/java/org/apache/commons/lang3/CharSequenceUtils.java @@ -266,22 +266,33 @@ static int lastIndexOf(final CharSequence cs, final CharSequence searchChar, int start = len1 - len2; } - if (check(cs, searchChar, len2, start)) { - return start; - } + char char0 = searchChar.charAt(0); - for (int i = start - 1; i >= 0; i--) { - if (check(cs, searchChar, len2, i)) { + int i = start; + while (true) { + while (cs.charAt(i) != char0) { + i--; + if (i < 0) { + return -1; + } + } + if (checkLaterThan1(cs, searchChar, len2, i)) { return i; + } else { + i--; + if (i < 0) { + return -1; + } } } - - return -1; } - private static boolean check(final CharSequence cs, final CharSequence searchChar, int len2, int start1) { - for (int i = 0; i < len2; i++) { - if (cs.charAt(start1 + i) != searchChar.charAt(i)) { + private static boolean checkLaterThan1(final CharSequence cs, final CharSequence searchChar, int len2, int start1) { + for (int i = 1, j = len2 - 1; i <= j; i++, j--) { + if (cs.charAt(start1 + i) != searchChar.charAt(i) + || + cs.charAt(start1 + j) != searchChar.charAt(j) + ) { return false; } } diff --git a/src/test/java/org/apache/commons/lang3/CharSequenceUtilsTest.java b/src/test/java/org/apache/commons/lang3/CharSequenceUtilsTest.java index c230c4507be..796e8f24e04 100644 --- a/src/test/java/org/apache/commons/lang3/CharSequenceUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/CharSequenceUtilsTest.java @@ -16,23 +16,14 @@ */ package org.apache.commons.lang3; -import static java.nio.CharBuffer.wrap; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Test; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; -import java.nio.CharBuffer; import java.util.Random; import java.util.stream.IntStream; -import org.apache.commons.lang3.text.StrBuilder; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; /** * Tests CharSequenceUtils @@ -258,7 +249,7 @@ public void testNewLastIndexOf() { private void testNewLastIndexOfSingle(CharSequence a, CharSequence b) { int maxa = Math.max(a.length(), b.length()); - for (int i = -maxa-10; i <= maxa+10; i++) { + for (int i = -maxa - 10; i <= maxa + 10; i++) { testNewLastIndexOfSingle(a, b, i); } } @@ -269,14 +260,8 @@ private void testNewLastIndexOfSingle(CharSequence a, CharSequence b, int start) } private void testNewLastIndexOfSingleSingle(CharSequence a, CharSequence b, int start) { - int expected = a.toString().lastIndexOf(b.toString(), start); -// assertEquals( -// expected, -// lastIndexOf(new WrapperString(a), b, start), -// "testNewLastIndexOf fails! original : " + a + " seg : " + b + " start : " + start -// ); assertEquals( - expected, + a.toString().lastIndexOf(b.toString(), start), CharSequenceUtils.lastIndexOf(new WrapperString(a.toString()), b.toString(), start), "testNewLastIndexOf fails! original : " + a + " seg : " + b + " start : " + start ); From 05724b2baa1d160f08132ff2038586e389048680 Mon Sep 17 00:00:00 2001 From: XenoAmess Date: Mon, 1 Jun 2020 02:30:19 +0800 Subject: [PATCH 0229/3230] reformat test --- .../apache/commons/lang3/CharSequenceUtilsTest.java | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/test/java/org/apache/commons/lang3/CharSequenceUtilsTest.java b/src/test/java/org/apache/commons/lang3/CharSequenceUtilsTest.java index 796e8f24e04..5eb1c7912f1 100644 --- a/src/test/java/org/apache/commons/lang3/CharSequenceUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/CharSequenceUtilsTest.java @@ -16,14 +16,20 @@ */ package org.apache.commons.lang3; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.util.Random; import java.util.stream.IntStream; -import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; /** * Tests CharSequenceUtils From 73438e431e9b4bd752ce901770499577d8f828f8 Mon Sep 17 00:00:00 2001 From: XenoAmess Date: Mon, 1 Jun 2020 05:53:04 +0800 Subject: [PATCH 0230/3230] fix checkstyle --- .../java/org/apache/commons/lang3/CharSequenceUtilsTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/org/apache/commons/lang3/CharSequenceUtilsTest.java b/src/test/java/org/apache/commons/lang3/CharSequenceUtilsTest.java index 5eb1c7912f1..147a8e53617 100644 --- a/src/test/java/org/apache/commons/lang3/CharSequenceUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/CharSequenceUtilsTest.java @@ -189,7 +189,7 @@ public void testToCharArray() { } static class WrapperString implements CharSequence { - CharSequence inner; + private CharSequence inner; public WrapperString(CharSequence inner) { this.inner = inner; From 00ecd339bdd8c977822d78c881667df3c211d146 Mon Sep 17 00:00:00 2001 From: XenoAmess Date: Mon, 1 Jun 2020 05:59:32 +0800 Subject: [PATCH 0231/3230] fix checkstyle --- .../java/org/apache/commons/lang3/CharSequenceUtilsTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/org/apache/commons/lang3/CharSequenceUtilsTest.java b/src/test/java/org/apache/commons/lang3/CharSequenceUtilsTest.java index 147a8e53617..82f5751ab03 100644 --- a/src/test/java/org/apache/commons/lang3/CharSequenceUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/CharSequenceUtilsTest.java @@ -191,7 +191,7 @@ public void testToCharArray() { static class WrapperString implements CharSequence { private CharSequence inner; - public WrapperString(CharSequence inner) { + WrapperString(CharSequence inner) { this.inner = inner; } From bbc2e7ee859287f84055b7637d92363cece9442c Mon Sep 17 00:00:00 2001 From: XenoAmess Date: Mon, 1 Jun 2020 17:17:52 +0800 Subject: [PATCH 0232/3230] refine tests --- .../commons/lang3/CharSequenceUtilsTest.java | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/src/test/java/org/apache/commons/lang3/CharSequenceUtilsTest.java b/src/test/java/org/apache/commons/lang3/CharSequenceUtilsTest.java index 82f5751ab03..b92780831b9 100644 --- a/src/test/java/org/apache/commons/lang3/CharSequenceUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/CharSequenceUtilsTest.java @@ -16,20 +16,14 @@ */ package org.apache.commons.lang3; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Test; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.util.Random; import java.util.stream.IntStream; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; /** * Tests CharSequenceUtils @@ -236,6 +230,13 @@ public void testNewLastIndexOf() { testNewLastIndexOfSingle("11", "1"); testNewLastIndexOfSingle("1", "11"); + testNewLastIndexOfSingle("apache", "a"); + testNewLastIndexOfSingle("apache", "p"); + testNewLastIndexOfSingle("apache", "e"); + testNewLastIndexOfSingle("apache", "x"); + testNewLastIndexOfSingle("oraoraoraora", "r"); + testNewLastIndexOfSingle("mudamudamudamuda", "d"); + Random random = new Random(); StringBuilder seg = new StringBuilder(); while (seg.length() <= CharSequenceUtils.TO_STRING_LIMIT) { @@ -258,6 +259,8 @@ private void testNewLastIndexOfSingle(CharSequence a, CharSequence b) { for (int i = -maxa - 10; i <= maxa + 10; i++) { testNewLastIndexOfSingle(a, b, i); } + testNewLastIndexOfSingle(a, b, Integer.MIN_VALUE); + testNewLastIndexOfSingle(a, b, Integer.MAX_VALUE); } private void testNewLastIndexOfSingle(CharSequence a, CharSequence b, int start) { From d02958ca097c65f73bd51adbe246ff4d3ec07ca0 Mon Sep 17 00:00:00 2001 From: XenoAmess Date: Mon, 1 Jun 2020 17:35:50 +0800 Subject: [PATCH 0233/3230] refine tests --- .../java/org/apache/commons/lang3/CharSequenceUtilsTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/org/apache/commons/lang3/CharSequenceUtilsTest.java b/src/test/java/org/apache/commons/lang3/CharSequenceUtilsTest.java index b92780831b9..32db044c5bb 100644 --- a/src/test/java/org/apache/commons/lang3/CharSequenceUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/CharSequenceUtilsTest.java @@ -271,7 +271,7 @@ private void testNewLastIndexOfSingle(CharSequence a, CharSequence b, int start) private void testNewLastIndexOfSingleSingle(CharSequence a, CharSequence b, int start) { assertEquals( a.toString().lastIndexOf(b.toString(), start), - CharSequenceUtils.lastIndexOf(new WrapperString(a.toString()), b.toString(), start), + CharSequenceUtils.lastIndexOf(new WrapperString(a.toString()), new WrapperString(b.toString()), start), "testNewLastIndexOf fails! original : " + a + " seg : " + b + " start : " + start ); } From a9dea5e5c4484c28ee68c002fede54a6c9fcf1bb Mon Sep 17 00:00:00 2001 From: XenoAmess Date: Mon, 1 Jun 2020 18:03:12 +0800 Subject: [PATCH 0234/3230] refine tests --- .../org/apache/commons/lang3/CharSequenceUtilsTest.java | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/test/java/org/apache/commons/lang3/CharSequenceUtilsTest.java b/src/test/java/org/apache/commons/lang3/CharSequenceUtilsTest.java index 32db044c5bb..e92fdda6b60 100644 --- a/src/test/java/org/apache/commons/lang3/CharSequenceUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/CharSequenceUtilsTest.java @@ -16,6 +16,14 @@ */ package org.apache.commons.lang3; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import org.junit.jupiter.api.Test; import java.lang.reflect.Constructor; From 249d9e474459ab060fe6b702d32dc5e2873c8ed5 Mon Sep 17 00:00:00 2001 From: XenoAmess Date: Mon, 1 Jun 2020 18:08:49 +0800 Subject: [PATCH 0235/3230] refine tests --- .../java/org/apache/commons/lang3/CharSequenceUtilsTest.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/test/java/org/apache/commons/lang3/CharSequenceUtilsTest.java b/src/test/java/org/apache/commons/lang3/CharSequenceUtilsTest.java index e92fdda6b60..fd0c8756ccf 100644 --- a/src/test/java/org/apache/commons/lang3/CharSequenceUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/CharSequenceUtilsTest.java @@ -31,8 +31,6 @@ import java.util.Random; import java.util.stream.IntStream; -import static org.junit.jupiter.api.Assertions.*; - /** * Tests CharSequenceUtils */ From e04966a6122ef94d295a070bf96774629e9f05a4 Mon Sep 17 00:00:00 2001 From: XenoAmess Date: Mon, 1 Jun 2020 20:10:07 +0800 Subject: [PATCH 0236/3230] refine tests --- .../java/org/apache/commons/lang3/CharSequenceUtilsTest.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/test/java/org/apache/commons/lang3/CharSequenceUtilsTest.java b/src/test/java/org/apache/commons/lang3/CharSequenceUtilsTest.java index fd0c8756ccf..fb9d568fac9 100644 --- a/src/test/java/org/apache/commons/lang3/CharSequenceUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/CharSequenceUtilsTest.java @@ -24,12 +24,11 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.jupiter.api.Test; - import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.util.Random; import java.util.stream.IntStream; +import org.junit.jupiter.api.Test; /** * Tests CharSequenceUtils From acaf4582781c17952b25fe86abafcefa0489c2a6 Mon Sep 17 00:00:00 2001 From: Rob Tompkins Date: Fri, 26 Jun 2020 05:49:12 -0400 Subject: [PATCH 0237/3230] LANG-1549: Thanks Jin --- pom.xml | 3 +++ src/changes/changes.xml | 1 + 2 files changed, 4 insertions(+) diff --git a/pom.xml b/pom.xml index c05b502cf23..ca9d7f4141d 100644 --- a/pom.xml +++ b/pom.xml @@ -508,6 +508,9 @@ Peter Verhas + + Jin Xu + diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 9c8259b45bc..429f608781a 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -46,6 +46,7 @@ The type attribute can be add,update,fix,remove. + CharSequenceUtils.lastIndexOf : remake it remove encoding and docEncoding and use inherited values from commons-parent Fix Javadoc for StringUtils.appendIfMissingIgnoreCase() #507. Simplify null checks in Pair.hashCode() using Objects.hashCode(). #517. From bf7aa89ca45706ad1f40cacdf7448626529dd6b0 Mon Sep 17 00:00:00 2001 From: Jochen Wiedmann Date: Fri, 26 Jun 2020 11:51:06 +0200 Subject: [PATCH 0238/3230] Adding Javadocs for the Locks.Lock class. Improvements in the test suite. --- .../commons/lang3/concurrent/Locks.java | 178 +++++++++++++++++- .../commons/lang3/concurrent/LocksTest.java | 37 ++++ 2 files changed, 213 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/concurrent/Locks.java b/src/main/java/org/apache/commons/lang3/concurrent/Locks.java index 28df9c0953a..48e16eb8d0a 100644 --- a/src/main/java/org/apache/commons/lang3/concurrent/Locks.java +++ b/src/main/java/org/apache/commons/lang3/concurrent/Locks.java @@ -70,31 +70,174 @@ */ public class Locks { + /** + * This class implements a wrapper for a locked (hidden) object, and + * provides the means to access it. The basic idea, is that the user + * code forsakes all references to the locked object, using only the + * wrapper object, and the accessor methods + * {@link #acceptReadLocked(FailableConsumer)}, + * {@link #acceptWriteLocked(FailableConsumer)}, + * {@link #applyReadLocked(FailableFunction)}, and + * {@link #applyWriteLocked(FailableFunction)}. By doing so, the + * necessary protections are guaranteed. + * @param The locked (hidden) objects type. + * + * @since 3.11 + */ public static class Lock { - private final StampedLock lock = new StampedLock(); private final O lockedObject; + /** + * Creates a new instance with the given locked object. This + * constructor is supposed to be used for subclassing only. + * In general, it is suggested to use {@link Locks#lock(Object)} + * instead. + * @param lockedObject The locked (hidden) object. The caller is + * supposed to drop all references to the locked object. + */ public Lock(final O lockedObject) { this.lockedObject = Objects.requireNonNull(lockedObject, "Locked Object"); } + /** + * Provides read (shared, non-exclusive) access to the locked (hidden) object. + * More precisely, what the method will do (in the given order): + *
        + *
      1. Obtain a read (shared) lock on the locked (hidden) object. + * The current thread may block, until such a lock is granted. + *
      2. + *
      3. Invokes the given {@link FailableConsumer consumer}, passing the + * locked object as the parameter.
      4. + *
      5. Release the lock, as soon as the consumers invocation is done. + * If the invocation results in an error, the lock will be released + * anyways. + *
      6. + *
      + * @param consumer The consumer, which is being invoked to use the + * hidden object, which will be passed as the consumers parameter. + * @see #acceptWriteLocked(FailableConsumer) + * @see #applyReadLocked(FailableFunction) + */ public void acceptReadLocked(final FailableConsumer consumer) { lockAcceptUnlock(() -> lock.readLock(), consumer); } + /** + * Provides write (exclusive) access to the locked (hidden) object. + * More precisely, what the method will do (in the given order): + *
        + *
      1. Obtain a write (shared) lock on the locked (hidden) object. + * The current thread may block, until such a lock is granted. + *
      2. + *
      3. Invokes the given {@link FailableConsumer consumer}, passing the + * locked object as the parameter.
      4. + *
      5. Release the lock, as soon as the consumers invocation is done. + * If the invocation results in an error, the lock will be released + * anyways. + *
      6. + *
      + * @param consumer The consumer, which is being invoked to use the + * hidden object, which will be passed as the consumers parameter. + * @see #acceptReadLocked(FailableConsumer) + * @see #applyWriteLocked(FailableFunction) + */ public void acceptWriteLocked(final FailableConsumer consumer) { lockAcceptUnlock(() -> lock.writeLock(), consumer); } + /** + * Provides read (shared, non-exclusive) access to the locked (hidden) + * object for the purpose of computing a result object. + * More precisely, what the method will do (in the given order): + *
        + *
      1. Obtain a read (shared) lock on the locked (hidden) object. + * The current thread may block, until such a lock is granted. + *
      2. + *
      3. Invokes the given {@link FailableFunction function}, passing the + * locked object as the parameter, receiving the functions result.
      4. + *
      5. Release the lock, as soon as the consumers invocation is done. + * If the invocation results in an error, the lock will be released + * anyways. + *
      6. + *
      7. + * Return the result object, that has been received from the + * functions invocation.
      8. + *
      + * + * Example: Suggest, that the hidden object is a list, and we + * wish to know the current size of the list. This might be achieved + * with the following: + * + *
      +         *   private Lock<List<Object>> listLock;
      +         *
      +         *   public int getCurrentListSize() {
      +         *       final Integer sizeInteger
      +         *           = listLock.applyReadLocked((list) -> Integer.valueOf(list.size));
      +         *       return sizeInteger.intValue();
      +         *   }
      +         * 
      + * @param The result type (both the functions, and this method's.) + * @param function The function, which is being invoked to compute the + * result. The function will receive the hidden object. + * @return The result object, which has been returned by the + * functions invocation. + * @throws IllegalStateException The result object would be, in fact, + * the hidden object. This would extend access to the hidden object + * beyond this methods lifetime and will therefore be prevented. + * @see #acceptReadLocked(FailableConsumer) + * @see #applyWriteLocked(FailableFunction) + */ public T applyReadLocked(final FailableFunction function) { return lockApplyUnlock(() -> lock.readLock(), function); } + /** + * Provides write (exclusive) access to the locked (hidden) + * object for the purpose of computing a result object. + * More precisely, what the method will do (in the given order): + *
        + *
      1. Obtain a read (shared) lock on the locked (hidden) object. + * The current thread may block, until such a lock is granted. + *
      2. + *
      3. Invokes the given {@link FailableFunction function}, passing the + * locked object as the parameter, receiving the functions result.
      4. + *
      5. Release the lock, as soon as the consumers invocation is done. + * If the invocation results in an error, the lock will be released + * anyways. + *
      6. + *
      7. + * Return the result object, that has been received from the + * functions invocation.
      8. + *
      + * @param The result type (both the functions, and this method's.) + * @param function The function, which is being invoked to compute the + * result. The function will receive the hidden object. + * @return The result object, which has been returned by the + * functions invocation. + * @throws IllegalStateException The result object would be, in fact, + * the hidden object. This would extend access to the hidden object + * beyond this methods lifetime and will therefore be prevented. + * @see #acceptReadLocked(FailableConsumer) + * @see #applyWriteLocked(FailableFunction) + */ public T applyWriteLocked(final FailableFunction function) { return lockApplyUnlock(() -> lock.writeLock(), function); } + /** + * This method provides the actual implementation for + * {@link #acceptReadLocked(FailableConsumer)}, and + * {@link #acceptWriteLocked(FailableConsumer)}. + * @param stampSupplier A supplier for the lock. (This provides, in + * fact, a long, because a {@link StampedLock} is used internally.) + * @param consumer The consumer, which is to be given access to the + * locked (hidden) object, which will be passed as a parameter. + * @see #acceptReadLocked(FailableConsumer) + * @see #acceptWriteLocked(FailableConsumer) + * @see #lockApplyUnlock(LongSupplier, FailableFunction) + */ protected void lockAcceptUnlock(final LongSupplier stampSupplier, final FailableConsumer consumer) { final long stamp = stampSupplier.getAsLong(); try { @@ -106,10 +249,33 @@ protected void lockAcceptUnlock(final LongSupplier stampSupplier, final Failable } } + /** + * This method provides the actual implementation for + * {@link #applyReadLocked(FailableFunction)}, and + * {@link #applyWriteLocked(FailableFunction)}. + * @param The result type (both the functions, and this method's.) + * @param stampSupplier A supplier for the lock. (This provides, in + * fact, a long, because a {@link StampedLock} is used internally.) + * @param function The function, which is being invoked to compute + * the result object. This function will receive the locked (hidden) + * object as a parameter. + * @return The result object, which has been returned by the + * functions invocation. + * @throws IllegalStateException The result object would be, in fact, + * the hidden object. This would extend access to the hidden object + * beyond this methods lifetime and will therefore be prevented. + * @see #applyReadLocked(FailableFunction) + * @see #applyWriteLocked(FailableFunction) + * @see #lockAcceptUnlock(LongSupplier, FailableConsumer) + */ protected T lockApplyUnlock(final LongSupplier stampSupplier, final FailableFunction function) { final long stamp = stampSupplier.getAsLong(); try { - return function.apply(lockedObject); + final T t = function.apply(lockedObject); + if (t == lockedObject) { + throw new IllegalStateException("The returned object is, in fact, the hidden object."); + } + return t; } catch (final Throwable t) { throw Failable.rethrow(t); } finally { @@ -118,6 +284,14 @@ protected T lockApplyUnlock(final LongSupplier stampSupplier, final Failable } } + /** + * Creates a new instance of {@link Lock} with the given locked + * (hidden) object. + * @param The locked objects type. + * @param object The locked (hidden) object. + * @return The created instance, a {@link Lock lock} for the + * given object. + */ public static Locks.Lock lock(final O object) { return new Locks.Lock<>(object); } diff --git a/src/test/java/org/apache/commons/lang3/concurrent/LocksTest.java b/src/test/java/org/apache/commons/lang3/concurrent/LocksTest.java index 2d577ecdb77..706281ec918 100644 --- a/src/test/java/org/apache/commons/lang3/concurrent/LocksTest.java +++ b/src/test/java/org/apache/commons/lang3/concurrent/LocksTest.java @@ -16,7 +16,11 @@ */ package org.apache.commons.lang3.concurrent; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotSame; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.util.function.LongConsumer; @@ -36,6 +40,7 @@ public void testReadLock() throws Exception { runTest(DELAY, false, l -> assertTrue(l < NUMBER_OF_THREADS*DELAY)); } + @Test public void testWriteLock() throws Exception { final long DELAY = 100; /** If our threads are running concurrently, then we expect to be no faster @@ -44,6 +49,38 @@ public void testWriteLock() throws Exception { runTest(DELAY, true, l -> assertTrue(l >= NUMBER_OF_THREADS*DELAY)); } + @Test + public void testResultValidation() { + final Object hidden = new Object(); + final Lock lock = Locks.lock(hidden); + final Object o1 = lock.applyReadLocked((h) -> { + return new Object(); + }); + assertNotNull(o1); + assertNotSame(hidden, o1); + final Object o2 = lock.applyWriteLocked((h) -> { + return new Object(); + }); + assertNotNull(o2); + assertNotSame(hidden, o2); + try { + lock.applyReadLocked((h) -> { + return hidden; + }); + fail("Expected Exception"); + } catch (IllegalStateException e) { + assertEquals("The returned object is, in fact, the hidden object.", e.getMessage()); + } + try { + lock.applyReadLocked((h) -> { + return hidden; + }); + fail("Expected Exception"); + } catch (IllegalStateException e) { + assertEquals("The returned object is, in fact, the hidden object.", e.getMessage()); + } + } + private void runTest(final long delay, final boolean exclusiveLock, final LongConsumer runTimeCheck) throws InterruptedException { final boolean[] booleanValues = new boolean[10]; final Lock lock = Locks.lock(booleanValues); From e5108df458e5bbfc35e55fee33ccb66cba254358 Mon Sep 17 00:00:00 2001 From: Rob Tompkins Date: Fri, 26 Jun 2020 06:12:51 -0400 Subject: [PATCH 0239/3230] Thanks Jin for refining the test output for FastDateParserTest Signed-off-by: Rob Tompkins --- src/changes/changes.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 429f608781a..21d266a5bf0 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -46,6 +46,7 @@ The type attribute can be add,update,fix,remove. + Refine test output for FastDateParserTest CharSequenceUtils.lastIndexOf : remake it remove encoding and docEncoding and use inherited values from commons-parent Fix Javadoc for StringUtils.appendIfMissingIgnoreCase() #507. From eee51821a8d70ed5f083956831056ae1ad634988 Mon Sep 17 00:00:00 2001 From: Rob Tompkins Date: Fri, 26 Jun 2020 06:15:23 -0400 Subject: [PATCH 0240/3230] fix: nit in my changes.xml formatting --- src/changes/changes.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 21d266a5bf0..ddc71f5c0b2 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -46,7 +46,7 @@ The type attribute can be add,update,fix,remove. - Refine test output for FastDateParserTest + Refine test output for FastDateParserTest CharSequenceUtils.lastIndexOf : remake it remove encoding and docEncoding and use inherited values from commons-parent Fix Javadoc for StringUtils.appendIfMissingIgnoreCase() #507. From d18fb1abdfaed0671a33753c7341d80b64a2c7bf Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Fri, 26 Jun 2020 09:04:17 -0400 Subject: [PATCH 0241/3230] JRE locks live in a ...concurrent.lock package so let's put our lock code in our own ...concurrent.lock --- .../apache/commons/lang3/concurrent/{ => lock}/Locks.java | 2 +- .../commons/lang3/concurrent/{ => lock}/LocksTest.java | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) rename src/main/java/org/apache/commons/lang3/concurrent/{ => lock}/Locks.java (99%) rename src/test/java/org/apache/commons/lang3/concurrent/{ => lock}/LocksTest.java (96%) diff --git a/src/main/java/org/apache/commons/lang3/concurrent/Locks.java b/src/main/java/org/apache/commons/lang3/concurrent/lock/Locks.java similarity index 99% rename from src/main/java/org/apache/commons/lang3/concurrent/Locks.java rename to src/main/java/org/apache/commons/lang3/concurrent/lock/Locks.java index 48e16eb8d0a..138226ead99 100644 --- a/src/main/java/org/apache/commons/lang3/concurrent/Locks.java +++ b/src/main/java/org/apache/commons/lang3/concurrent/lock/Locks.java @@ -14,7 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.commons.lang3.concurrent; +package org.apache.commons.lang3.concurrent.lock; import java.util.Objects; import java.util.concurrent.locks.StampedLock; diff --git a/src/test/java/org/apache/commons/lang3/concurrent/LocksTest.java b/src/test/java/org/apache/commons/lang3/concurrent/lock/LocksTest.java similarity index 96% rename from src/test/java/org/apache/commons/lang3/concurrent/LocksTest.java rename to src/test/java/org/apache/commons/lang3/concurrent/lock/LocksTest.java index 706281ec918..8e475fbcde1 100644 --- a/src/test/java/org/apache/commons/lang3/concurrent/LocksTest.java +++ b/src/test/java/org/apache/commons/lang3/concurrent/lock/LocksTest.java @@ -14,7 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.commons.lang3.concurrent; +package org.apache.commons.lang3.concurrent.lock; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; @@ -24,7 +24,8 @@ import java.util.function.LongConsumer; -import org.apache.commons.lang3.concurrent.Locks.Lock; +import org.apache.commons.lang3.concurrent.lock.Locks; +import org.apache.commons.lang3.concurrent.lock.Locks.Lock; import org.apache.commons.lang3.function.FailableConsumer; import org.junit.jupiter.api.Test; From 46a081d69c27f0c57ee633489baa62b01d9b3cc2 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Fri, 26 Jun 2020 10:33:37 -0400 Subject: [PATCH 0242/3230] Javadocs, imports. --- .../lang3/concurrent/lock/package-info.java | 24 +++++++++++++++++++ .../commons/lang3/function/package-info.java | 1 + .../lang3/concurrent/lock/LocksTest.java | 1 - 3 files changed, 25 insertions(+), 1 deletion(-) create mode 100644 src/main/java/org/apache/commons/lang3/concurrent/lock/package-info.java diff --git a/src/main/java/org/apache/commons/lang3/concurrent/lock/package-info.java b/src/main/java/org/apache/commons/lang3/concurrent/lock/package-info.java new file mode 100644 index 00000000000..4b6f9b8f81f --- /dev/null +++ b/src/main/java/org/apache/commons/lang3/concurrent/lock/package-info.java @@ -0,0 +1,24 @@ +/* + * 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. + */ +/** + *

      + * Provides support classes for multi-threaded programming. This package is intended to be an extension to + * {@link java.util.concurrent.lock}. + *

      + * @since 3.11 + */ +package org.apache.commons.lang3.concurrent.lock; diff --git a/src/main/java/org/apache/commons/lang3/function/package-info.java b/src/main/java/org/apache/commons/lang3/function/package-info.java index 4a0ccd91376..330e7c78d79 100644 --- a/src/main/java/org/apache/commons/lang3/function/package-info.java +++ b/src/main/java/org/apache/commons/lang3/function/package-info.java @@ -22,6 +22,7 @@ * Contains failable functional interfaces that address the fact that lambdas are supposed not to throw Exceptions, at * least not checked Exceptions, A.K.A. instances of {@link java.lang.Exception}. A failable functional interface * declares a type of Exception that may be raised if the function fails. + *

      * * @since 3.11 */ diff --git a/src/test/java/org/apache/commons/lang3/concurrent/lock/LocksTest.java b/src/test/java/org/apache/commons/lang3/concurrent/lock/LocksTest.java index 8e475fbcde1..2f15db40f91 100644 --- a/src/test/java/org/apache/commons/lang3/concurrent/lock/LocksTest.java +++ b/src/test/java/org/apache/commons/lang3/concurrent/lock/LocksTest.java @@ -24,7 +24,6 @@ import java.util.function.LongConsumer; -import org.apache.commons.lang3.concurrent.lock.Locks; import org.apache.commons.lang3.concurrent.lock.Locks.Lock; import org.apache.commons.lang3.function.FailableConsumer; import org.junit.jupiter.api.Test; From bb017e0d4d139ada3dc8cc3e6eccc0c34e0bbb9f Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Fri, 26 Jun 2020 14:35:14 -0400 Subject: [PATCH 0243/3230] JRE locks live in a ...concurrent.locks package so let's put our lock code in our own ...concurrent.locks. --- .../commons/lang3/concurrent/{lock => locks}/Locks.java | 2 +- .../lang3/concurrent/{lock => locks}/package-info.java | 4 ++-- .../java/org/apache/commons/lang3/CharSequenceUtilsTest.java | 1 + .../commons/lang3/concurrent/{lock => locks}/LocksTest.java | 4 ++-- 4 files changed, 6 insertions(+), 5 deletions(-) rename src/main/java/org/apache/commons/lang3/concurrent/{lock => locks}/Locks.java (99%) rename src/main/java/org/apache/commons/lang3/concurrent/{lock => locks}/package-info.java (91%) rename src/test/java/org/apache/commons/lang3/concurrent/{lock => locks}/LocksTest.java (97%) diff --git a/src/main/java/org/apache/commons/lang3/concurrent/lock/Locks.java b/src/main/java/org/apache/commons/lang3/concurrent/locks/Locks.java similarity index 99% rename from src/main/java/org/apache/commons/lang3/concurrent/lock/Locks.java rename to src/main/java/org/apache/commons/lang3/concurrent/locks/Locks.java index 138226ead99..23d12826d9a 100644 --- a/src/main/java/org/apache/commons/lang3/concurrent/lock/Locks.java +++ b/src/main/java/org/apache/commons/lang3/concurrent/locks/Locks.java @@ -14,7 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.commons.lang3.concurrent.lock; +package org.apache.commons.lang3.concurrent.locks; import java.util.Objects; import java.util.concurrent.locks.StampedLock; diff --git a/src/main/java/org/apache/commons/lang3/concurrent/lock/package-info.java b/src/main/java/org/apache/commons/lang3/concurrent/locks/package-info.java similarity index 91% rename from src/main/java/org/apache/commons/lang3/concurrent/lock/package-info.java rename to src/main/java/org/apache/commons/lang3/concurrent/locks/package-info.java index 4b6f9b8f81f..2b5fef7e082 100644 --- a/src/main/java/org/apache/commons/lang3/concurrent/lock/package-info.java +++ b/src/main/java/org/apache/commons/lang3/concurrent/locks/package-info.java @@ -17,8 +17,8 @@ /** *

      * Provides support classes for multi-threaded programming. This package is intended to be an extension to - * {@link java.util.concurrent.lock}. + * {@link java.util.concurrent.locks}. *

      * @since 3.11 */ -package org.apache.commons.lang3.concurrent.lock; +package org.apache.commons.lang3.concurrent.locks; diff --git a/src/test/java/org/apache/commons/lang3/CharSequenceUtilsTest.java b/src/test/java/org/apache/commons/lang3/CharSequenceUtilsTest.java index fb9d568fac9..dc0db4e8808 100644 --- a/src/test/java/org/apache/commons/lang3/CharSequenceUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/CharSequenceUtilsTest.java @@ -28,6 +28,7 @@ import java.lang.reflect.Modifier; import java.util.Random; import java.util.stream.IntStream; + import org.junit.jupiter.api.Test; /** diff --git a/src/test/java/org/apache/commons/lang3/concurrent/lock/LocksTest.java b/src/test/java/org/apache/commons/lang3/concurrent/locks/LocksTest.java similarity index 97% rename from src/test/java/org/apache/commons/lang3/concurrent/lock/LocksTest.java rename to src/test/java/org/apache/commons/lang3/concurrent/locks/LocksTest.java index 2f15db40f91..0f1f4730ad7 100644 --- a/src/test/java/org/apache/commons/lang3/concurrent/lock/LocksTest.java +++ b/src/test/java/org/apache/commons/lang3/concurrent/locks/LocksTest.java @@ -14,7 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.commons.lang3.concurrent.lock; +package org.apache.commons.lang3.concurrent.locks; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; @@ -24,7 +24,7 @@ import java.util.function.LongConsumer; -import org.apache.commons.lang3.concurrent.lock.Locks.Lock; +import org.apache.commons.lang3.concurrent.locks.Locks.Lock; import org.apache.commons.lang3.function.FailableConsumer; import org.junit.jupiter.api.Test; From 10f6a80c9674aca24c633d9816272430bff49425 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Fri, 26 Jun 2020 15:31:00 -0400 Subject: [PATCH 0244/3230] No need to nest. --- .../java/org/apache/commons/lang3/CharSequenceUtils.java | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/CharSequenceUtils.java b/src/main/java/org/apache/commons/lang3/CharSequenceUtils.java index 01de17c2be6..6d9aecbb9b4 100644 --- a/src/main/java/org/apache/commons/lang3/CharSequenceUtils.java +++ b/src/main/java/org/apache/commons/lang3/CharSequenceUtils.java @@ -278,11 +278,10 @@ static int lastIndexOf(final CharSequence cs, final CharSequence searchChar, int } if (checkLaterThan1(cs, searchChar, len2, i)) { return i; - } else { - i--; - if (i < 0) { - return -1; - } + } + i--; + if (i < 0) { + return -1; } } } From 1621a23d2bd99df845abae0beea0add84135a49d Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Fri, 26 Jun 2020 15:32:13 -0400 Subject: [PATCH 0245/3230] Make org.apache.commons.lang3.CharSequenceUtils.toCharArray(CharSequence) public. --- src/changes/changes.xml | 1 + src/main/java/org/apache/commons/lang3/CharSequenceUtils.java | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index ddc71f5c0b2..5c8b3e159c6 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -81,6 +81,7 @@ The type attribute can be add,update,fix,remove. Add ObjectUtils.toString(Object, Supplier<String>). Fixed Javadocs for setTestRecursive() #556. ToStringBuilder.reflectionToString - Wrong JSON format when object has a List of Enum. + Make org.apache.commons.lang3.CharSequenceUtils.toCharArray(CharSequence) public. org.apache.commons:commons-parent 50 -> 51. org.junit-pioneer:junit-pioneer 0.5.4 -> 0.6.0. org.junit.jupiter:junit-jupiter 5.6.0 -> 5.6.1. diff --git a/src/main/java/org/apache/commons/lang3/CharSequenceUtils.java b/src/main/java/org/apache/commons/lang3/CharSequenceUtils.java index 6d9aecbb9b4..494670bca92 100644 --- a/src/main/java/org/apache/commons/lang3/CharSequenceUtils.java +++ b/src/main/java/org/apache/commons/lang3/CharSequenceUtils.java @@ -303,8 +303,9 @@ private static boolean checkLaterThan1(final CharSequence cs, final CharSequence * * @param cs the {@code CharSequence} to be processed * @return the resulting char array + * @since 3.11 */ - static char[] toCharArray(final CharSequence cs) { + public static char[] toCharArray(final CharSequence cs) { if (cs instanceof String) { return ((String) cs).toCharArray(); } From d68a7a4189be8032045f952952c1aa9c764a3b9a Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sat, 27 Jun 2020 09:24:06 -0400 Subject: [PATCH 0246/3230] Add org.apache.commons.lang3.StringUtils.substringAfter(String, int). --- src/changes/changes.xml | 1 + .../org/apache/commons/lang3/StringUtils.java | 36 +++++++++++++++++++ .../lang3/StringUtilsSubstringTest.java | 15 ++++++++ 3 files changed, 52 insertions(+) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 5c8b3e159c6..61339233b39 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -82,6 +82,7 @@ The type attribute can be add,update,fix,remove. Fixed Javadocs for setTestRecursive() #556. ToStringBuilder.reflectionToString - Wrong JSON format when object has a List of Enum. Make org.apache.commons.lang3.CharSequenceUtils.toCharArray(CharSequence) public. + Add org.apache.commons.lang3.StringUtils.substringAfter(String, int). org.apache.commons:commons-parent 50 -> 51. org.junit-pioneer:junit-pioneer 0.5.4 -> 0.6.0. org.junit.jupiter:junit-jupiter 5.6.0 -> 5.6.1. diff --git a/src/main/java/org/apache/commons/lang3/StringUtils.java b/src/main/java/org/apache/commons/lang3/StringUtils.java index 5b872301622..36dc7ac1d10 100644 --- a/src/main/java/org/apache/commons/lang3/StringUtils.java +++ b/src/main/java/org/apache/commons/lang3/StringUtils.java @@ -8548,6 +8548,42 @@ public static String substring(final String str, int start, int end) { return str.substring(start, end); } + /** + *

      Gets the substring after the first occurrence of a separator. + * The separator is not returned.

      + * + *

      A {@code null} string input will return {@code null}. + * An empty ("") string input will return the empty string. + * + *

      If nothing is found, the empty string is returned.

      + * + *
      +     * StringUtils.substringAfter(null, *)      = null
      +     * StringUtils.substringAfter("", *)        = ""
      +     * StringUtils.substringAfter("abc", 'a')   = "bc"
      +     * StringUtils.substringAfter("abcba", 'b') = "cba"
      +     * StringUtils.substringAfter("abc", 'c')   = ""
      +     * StringUtils.substringAfter("abc", 'd')   = ""
      +     * StringUtils.substringAfter(" abc", 32)   = "abc"
      +     * 
      + * + * @param str the String to get a substring from, may be null + * @param separator the character to search. + * @return the substring after the first occurrence of the separator, + * {@code null} if null String input + * @since 3.11 + */ + public static String substringAfter(final String str, final int separator) { + if (isEmpty(str)) { + return str; + } + final int pos = str.indexOf(separator); + if (pos == INDEX_NOT_FOUND) { + return EMPTY; + } + return str.substring(pos + 1); + } + /** *

      Gets the substring after the first occurrence of a separator. * The separator is not returned.

      diff --git a/src/test/java/org/apache/commons/lang3/StringUtilsSubstringTest.java b/src/test/java/org/apache/commons/lang3/StringUtilsSubstringTest.java index 76bd2829081..a930e038487 100644 --- a/src/test/java/org/apache/commons/lang3/StringUtilsSubstringTest.java +++ b/src/test/java/org/apache/commons/lang3/StringUtilsSubstringTest.java @@ -168,6 +168,21 @@ public void testSubstringAfter_StringString() { assertEquals("", StringUtils.substringAfter("abc", "d")); } + @Test + public void testSubstringAfter_StringInt() { + assertNull(StringUtils.substringAfter(null, 0)); + assertNull(StringUtils.substringAfter(null, 'X')); + assertEquals("", StringUtils.substringAfter("", 0)); + assertEquals("", StringUtils.substringAfter("", 'X')); + + assertEquals("", StringUtils.substringAfter("foo", 0)); + assertEquals("ot", StringUtils.substringAfter("foot", 'o')); + assertEquals("bc", StringUtils.substringAfter("abc", 'a')); + assertEquals("cba", StringUtils.substringAfter("abcba", 'b')); + assertEquals("", StringUtils.substringAfter("abc", 'c')); + assertEquals("", StringUtils.substringAfter("abc", 'd')); + } + @Test public void testSubstringBeforeLast_StringString() { assertEquals("fooXXbar", StringUtils.substringBeforeLast("fooXXbarXXbaz", "XX")); From 75fa90e96c3ea16f92e1a178b257534990ac1616 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sat, 27 Jun 2020 09:24:58 -0400 Subject: [PATCH 0247/3230] Use final. --- .../commons/lang3/CharSequenceUtils.java | 8 ++++---- .../commons/lang3/CharSequenceUtilsTest.java | 20 +++++++++---------- .../lang3/time/FastDateParserTest.java | 2 +- 3 files changed, 15 insertions(+), 15 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/CharSequenceUtils.java b/src/main/java/org/apache/commons/lang3/CharSequenceUtils.java index 494670bca92..fc5350f52c3 100644 --- a/src/main/java/org/apache/commons/lang3/CharSequenceUtils.java +++ b/src/main/java/org/apache/commons/lang3/CharSequenceUtils.java @@ -237,8 +237,8 @@ static int lastIndexOf(final CharSequence cs, final CharSequence searchChar, int } } - int len1 = cs.length(); - int len2 = searchChar.length(); + final int len1 = cs.length(); + final int len2 = searchChar.length(); if (start > len1) { start = len1; @@ -266,7 +266,7 @@ static int lastIndexOf(final CharSequence cs, final CharSequence searchChar, int start = len1 - len2; } - char char0 = searchChar.charAt(0); + final char char0 = searchChar.charAt(0); int i = start; while (true) { @@ -286,7 +286,7 @@ static int lastIndexOf(final CharSequence cs, final CharSequence searchChar, int } } - private static boolean checkLaterThan1(final CharSequence cs, final CharSequence searchChar, int len2, int start1) { + private static boolean checkLaterThan1(final CharSequence cs, final CharSequence searchChar, final int len2, final int start1) { for (int i = 1, j = len2 - 1; i <= j; i++, j--) { if (cs.charAt(start1 + i) != searchChar.charAt(i) || diff --git a/src/test/java/org/apache/commons/lang3/CharSequenceUtilsTest.java b/src/test/java/org/apache/commons/lang3/CharSequenceUtilsTest.java index dc0db4e8808..b21144c1c4f 100644 --- a/src/test/java/org/apache/commons/lang3/CharSequenceUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/CharSequenceUtilsTest.java @@ -189,9 +189,9 @@ public void testToCharArray() { } static class WrapperString implements CharSequence { - private CharSequence inner; + private final CharSequence inner; - WrapperString(CharSequence inner) { + WrapperString(final CharSequence inner) { this.inner = inner; } @@ -201,12 +201,12 @@ public int length() { } @Override - public char charAt(int index) { + public char charAt(final int index) { return inner.charAt(index); } @Override - public CharSequence subSequence(int start, int end) { + public CharSequence subSequence(final int start, final int end) { return inner.subSequence(start, end); } @@ -243,8 +243,8 @@ public void testNewLastIndexOf() { testNewLastIndexOfSingle("oraoraoraora", "r"); testNewLastIndexOfSingle("mudamudamudamuda", "d"); - Random random = new Random(); - StringBuilder seg = new StringBuilder(); + final Random random = new Random(); + final StringBuilder seg = new StringBuilder(); while (seg.length() <= CharSequenceUtils.TO_STRING_LIMIT) { seg.append(random.nextInt()); } @@ -260,8 +260,8 @@ public void testNewLastIndexOf() { } } - private void testNewLastIndexOfSingle(CharSequence a, CharSequence b) { - int maxa = Math.max(a.length(), b.length()); + private void testNewLastIndexOfSingle(final CharSequence a, final CharSequence b) { + final int maxa = Math.max(a.length(), b.length()); for (int i = -maxa - 10; i <= maxa + 10; i++) { testNewLastIndexOfSingle(a, b, i); } @@ -269,12 +269,12 @@ private void testNewLastIndexOfSingle(CharSequence a, CharSequence b) { testNewLastIndexOfSingle(a, b, Integer.MAX_VALUE); } - private void testNewLastIndexOfSingle(CharSequence a, CharSequence b, int start) { + private void testNewLastIndexOfSingle(final CharSequence a, final CharSequence b, final int start) { testNewLastIndexOfSingleSingle(a, b, start); testNewLastIndexOfSingleSingle(b, a, start); } - private void testNewLastIndexOfSingleSingle(CharSequence a, CharSequence b, int start) { + private void testNewLastIndexOfSingleSingle(final CharSequence a, final CharSequence b, final int start) { assertEquals( a.toString().lastIndexOf(b.toString(), start), CharSequenceUtils.lastIndexOf(new WrapperString(a.toString()), new WrapperString(b.toString()), start), diff --git a/src/test/java/org/apache/commons/lang3/time/FastDateParserTest.java b/src/test/java/org/apache/commons/lang3/time/FastDateParserTest.java index eb0234041f6..5a15ea3c9be 100644 --- a/src/test/java/org/apache/commons/lang3/time/FastDateParserTest.java +++ b/src/test/java/org/apache/commons/lang3/time/FastDateParserTest.java @@ -732,7 +732,7 @@ public void java15BuggyLocaleTest() throws ParseException { testSingleLocale(buggyLocale); } - private void testSingleLocale(Locale locale) throws ParseException { + private void testSingleLocale(final Locale locale) throws ParseException { final Calendar cal = Calendar.getInstance(GMT); cal.clear(); cal.set(2003, Calendar.FEBRUARY, 10); From 062bc6fe7d48d4eb4cdf3abec09e7547a0a9aed7 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sat, 27 Jun 2020 09:32:30 -0400 Subject: [PATCH 0248/3230] Add Add org.apache.commons.lang3.StringUtils.substringAfterLast(String, int). --- src/changes/changes.xml | 3 +- .../org/apache/commons/lang3/StringUtils.java | 37 +++++++++++++++++++ .../lang3/StringUtilsSubstringTest.java | 16 ++++++++ 3 files changed, 55 insertions(+), 1 deletion(-) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 61339233b39..2506d0c9602 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -82,7 +82,8 @@ The type attribute can be add,update,fix,remove. Fixed Javadocs for setTestRecursive() #556. ToStringBuilder.reflectionToString - Wrong JSON format when object has a List of Enum. Make org.apache.commons.lang3.CharSequenceUtils.toCharArray(CharSequence) public. - Add org.apache.commons.lang3.StringUtils.substringAfter(String, int). + Add org.apache.commons.lang3.StringUtils.substringAfter(String, int). + Add org.apache.commons.lang3.StringUtils.substringAfterLast(String, int). org.apache.commons:commons-parent 50 -> 51. org.junit-pioneer:junit-pioneer 0.5.4 -> 0.6.0. org.junit.jupiter:junit-jupiter 5.6.0 -> 5.6.1. diff --git a/src/main/java/org/apache/commons/lang3/StringUtils.java b/src/main/java/org/apache/commons/lang3/StringUtils.java index 36dc7ac1d10..67787200d86 100644 --- a/src/main/java/org/apache/commons/lang3/StringUtils.java +++ b/src/main/java/org/apache/commons/lang3/StringUtils.java @@ -8672,6 +8672,43 @@ public static String substringAfterLast(final String str, final String separator return str.substring(pos + separator.length()); } + /** + *

      Gets the substring after the last occurrence of a separator. + * The separator is not returned.

      + * + *

      A {@code null} string input will return {@code null}. + * An empty ("") string input will return the empty string. + * + *

      If nothing is found, the empty string is returned.

      + * + *
      +     * StringUtils.substringAfterLast(null, *)      = null
      +     * StringUtils.substringAfterLast("", *)        = ""
      +     * StringUtils.substringAfterLast("abc", 'a')   = "bc"
      +     * StringUtils.substringAfterLast(" bc", 32)    = "bc"
      +     * StringUtils.substringAfterLast("abcba", 'b') = "a"
      +     * StringUtils.substringAfterLast("abc", 'c')   = ""
      +     * StringUtils.substringAfterLast("a", 'a')     = ""
      +     * StringUtils.substringAfterLast("a", 'z')     = ""
      +     * 
      + * + * @param str the String to get a substring from, may be null + * @param separator the String to search for, may be null + * @return the substring after the last occurrence of the separator, + * {@code null} if null String input + * @since 3.11 + */ + public static String substringAfterLast(final String str, final int separator) { + if (isEmpty(str)) { + return str; + } + final int pos = str.lastIndexOf(separator); + if (pos == INDEX_NOT_FOUND || pos == str.length() - 1) { + return EMPTY; + } + return str.substring(pos + 1); + } + // SubStringAfter/SubStringBefore //----------------------------------------------------------------------- /** diff --git a/src/test/java/org/apache/commons/lang3/StringUtilsSubstringTest.java b/src/test/java/org/apache/commons/lang3/StringUtilsSubstringTest.java index a930e038487..9a1c014fe61 100644 --- a/src/test/java/org/apache/commons/lang3/StringUtilsSubstringTest.java +++ b/src/test/java/org/apache/commons/lang3/StringUtilsSubstringTest.java @@ -228,6 +228,22 @@ public void testSubstringAfterLast_StringString() { assertEquals("", StringUtils.substringAfterLast("abc", "")); } + @Test + public void testSubstringAfterLast_StringInt() { + assertNull(StringUtils.substringAfterLast(null, 0)); + assertNull(StringUtils.substringAfterLast(null, 'X')); + assertEquals("", StringUtils.substringAfterLast("", 0)); + assertEquals("", StringUtils.substringAfterLast("", 'a')); + + assertEquals("", StringUtils.substringAfterLast("foo", 0)); + assertEquals("", StringUtils.substringAfterLast("foo", 'b')); + assertEquals("t", StringUtils.substringAfterLast("foot", 'o')); + assertEquals("bc", StringUtils.substringAfterLast("abc", 'a')); + assertEquals("a", StringUtils.substringAfterLast("abcba", 'b')); + assertEquals("", StringUtils.substringAfterLast("abc", 'c')); + assertEquals("", StringUtils.substringAfterLast("", 'd')); + } + //----------------------------------------------------------------------- @Test public void testSubstringBetween_StringString() { From 4063df71c300b399fac4b2dced18ec0beb4556f7 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sun, 28 Jun 2020 09:38:52 -0400 Subject: [PATCH 0249/3230] [LANG-1543] [JSON string for maps] ToStringBuilder.reflectionToString doesnt render nested maps correctly. Apply a different version of the PR https://github.com/apache/commons-lang/pull/561 Closes #561. --- src/changes/changes.xml | 1 + .../commons/lang3/builder/ToStringStyle.java | 34 ++++++++ .../lang3/builder/JsonToStringStyleTest.java | 82 +++++++++++++++++++ 3 files changed, 117 insertions(+) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 2506d0c9602..b8f42198cd3 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -81,6 +81,7 @@ The type attribute can be add,update,fix,remove. Add ObjectUtils.toString(Object, Supplier<String>). Fixed Javadocs for setTestRecursive() #556. ToStringBuilder.reflectionToString - Wrong JSON format when object has a List of Enum. + [JSON string for maps] ToStringBuilder.reflectionToString doesnt render nested maps correctly. Make org.apache.commons.lang3.CharSequenceUtils.toCharArray(CharSequence) public. Add org.apache.commons.lang3.StringUtils.substringAfter(String, int). Add org.apache.commons.lang3.StringUtils.substringAfterLast(String, int). diff --git a/src/main/java/org/apache/commons/lang3/builder/ToStringStyle.java b/src/main/java/org/apache/commons/lang3/builder/ToStringStyle.java index 56fda5556ab..1c339103000 100644 --- a/src/main/java/org/apache/commons/lang3/builder/ToStringStyle.java +++ b/src/main/java/org/apache/commons/lang3/builder/ToStringStyle.java @@ -19,7 +19,10 @@ import java.io.Serializable; import java.lang.reflect.Array; import java.util.Collection; +import java.util.Iterator; import java.util.Map; +import java.util.Objects; +import java.util.Map.Entry; import java.util.WeakHashMap; import org.apache.commons.lang3.ClassUtils; @@ -2595,6 +2598,37 @@ protected void appendDetail(final StringBuffer buffer, final String fieldName, f appendDetail(buffer, fieldName, valueAsString); } + @Override + protected void appendDetail(final StringBuffer buffer, final String fieldName, final Map map) { + if (map != null && !map.isEmpty()) { + buffer.append(getContentStart()); + + boolean firstItem = true; + for (final Entry entry : map.entrySet()) { + final String keyStr = Objects.toString(entry.getKey(), null); + if (keyStr != null) { + if (firstItem) { + firstItem = false; + } else { + appendFieldEnd(buffer, keyStr); + } + appendFieldStart(buffer, keyStr); + final Object value = entry.getValue(); + if (value == null) { + appendNullText(buffer, keyStr); + } else { + appendInternal(buffer, keyStr, value, true); + } + } + } + + buffer.append(getContentEnd()); + return; + } + + buffer.append(map); + } + private boolean isJsonArray(final String valueAsString) { return valueAsString.startsWith(getArrayStart()) && valueAsString.endsWith(getArrayEnd()); diff --git a/src/test/java/org/apache/commons/lang3/builder/JsonToStringStyleTest.java b/src/test/java/org/apache/commons/lang3/builder/JsonToStringStyleTest.java index 23895118a8f..b8d9f6e701d 100644 --- a/src/test/java/org/apache/commons/lang3/builder/JsonToStringStyleTest.java +++ b/src/test/java/org/apache/commons/lang3/builder/JsonToStringStyleTest.java @@ -26,6 +26,8 @@ import java.util.HashMap; import java.util.List; +import java.util.LinkedHashMap; +import java.util.Map; import org.apache.commons.lang3.builder.ToStringStyleTest.Person; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; @@ -532,6 +534,70 @@ public void testLANG1396() { assertEquals("{\"Let's \\\"quote\\\" this\":\"value\"}", new ToStringBuilder(base).append("Let's \"quote\" this", "value").toString()); } + @Test + public void testRootMap() { + final Map map = new LinkedHashMap<>(); + map.put("k1", "v1"); + map.put("k2", 2); + + assertEquals("{\"map\":{\"k1\":\"v1\",\"k2\":2}}", + new ToStringBuilder(base).append("map", map).toString()); + } + + @Test + public void testObjectWithInnerMap() { + final Map map = new LinkedHashMap<>(); + map.put("k1", "value1"); + map.put("k2", 2); + + final InnerMapObject object = new InnerMapObject(){ + @Override + public String toString() { + return new ToStringBuilder(this).append("pid", this.pid) + .append("map", this.map).toString(); + } + }; + object.pid = "dummy-text"; + object.map = map; + + assertEquals("{\"object\":{\"pid\":\"dummy-text\",\"map\":{\"k1\":\"value1\",\"k2\":2}}}", + new ToStringBuilder(base).append("object", object).toString()); + } + + @Test + public void testNestedMaps() { + final Map innerMap = new LinkedHashMap<>(); + innerMap.put("k2.1", "v2.1"); + innerMap.put("k2.2", "v2.2"); + final Map baseMap = new LinkedHashMap<>(); + baseMap.put("k1", "v1"); + baseMap.put("k2", innerMap); + + final InnerMapObject object = new InnerMapObject(){ + @Override + public String toString() { + return new ToStringBuilder(this).append("pid", this.pid) + .append("map", this.map).toString(); + } + }; + object.pid = "dummy-text"; + object.map = baseMap; + + assertEquals("{\"object\":{\"pid\":\"dummy-text\",\"map\":{\"k1\":\"v1\"," + + "\"k2\":{\"k2.1\":\"v2.1\",\"k2.2\":\"v2.2\"}}}}", + new ToStringBuilder(base).append("object", object).toString()); + } + + @Test + public void testMapSkipNullKey() { + final Map map = new LinkedHashMap<>(); + map.put("k1", "v1"); + map.put(null, "v2"); + + assertEquals("{\"map\":{\"k1\":\"v1\"}}", + new ToStringBuilder(base).append("map", map).toString()); + } + /** * An object with nested object structures used to test {@link ToStringStyle.JsonToStringStyle}. * @@ -616,4 +682,20 @@ public String toString() { return ToStringBuilder.reflectionToString(this); } } + + /** + * An object with a Map field used to test {@link ToStringStyle.JsonToStringStyle}. + * + */ + static class InnerMapObject { + /** + * Test String field. + */ + String pid; + + /** + * Test inner map field. + */ + Map map; + } } From 5e71a4add54e626975a3bd797b0a618ae51a084d Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sun, 28 Jun 2020 09:40:45 -0400 Subject: [PATCH 0250/3230] [LANG-1543] [JSON string for maps] ToStringBuilder.reflectionToString doesnt render nested maps correctly. Apply a different version of the PR https://github.com/apache/commons-lang/pull/561 Closes #561. --- src/changes/changes.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index b8f42198cd3..0a48dd39b49 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -81,7 +81,7 @@ The type attribute can be add,update,fix,remove. Add ObjectUtils.toString(Object, Supplier<String>). Fixed Javadocs for setTestRecursive() #556. ToStringBuilder.reflectionToString - Wrong JSON format when object has a List of Enum. - [JSON string for maps] ToStringBuilder.reflectionToString doesnt render nested maps correctly. + [JSON string for maps] ToStringBuilder.reflectionToString doesnt render nested maps correctly. Make org.apache.commons.lang3.CharSequenceUtils.toCharArray(CharSequence) public. Add org.apache.commons.lang3.StringUtils.substringAfter(String, int). Add org.apache.commons.lang3.StringUtils.substringAfterLast(String, int). From f89a85b051c6e81bb4dafe12414f105ea69ef413 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sun, 28 Jun 2020 09:49:12 -0400 Subject: [PATCH 0251/3230] [LANG-1543] [JSON string for maps] ToStringBuilder.reflectionToString doesnt render nested maps correctly. --- .../java/org/apache/commons/lang3/builder/ToStringStyle.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/builder/ToStringStyle.java b/src/main/java/org/apache/commons/lang3/builder/ToStringStyle.java index 1c339103000..02c4231e609 100644 --- a/src/main/java/org/apache/commons/lang3/builder/ToStringStyle.java +++ b/src/main/java/org/apache/commons/lang3/builder/ToStringStyle.java @@ -19,10 +19,9 @@ import java.io.Serializable; import java.lang.reflect.Array; import java.util.Collection; -import java.util.Iterator; import java.util.Map; -import java.util.Objects; import java.util.Map.Entry; +import java.util.Objects; import java.util.WeakHashMap; import org.apache.commons.lang3.ClassUtils; From da0f6a8051cc60d1bebe703b4e390ce3035497db Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sun, 28 Jun 2020 15:45:50 -0400 Subject: [PATCH 0252/3230] Refactor SpotBugs implementation version into spotbugs.impl.version. --- pom.xml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index ca9d7f4141d..0e539ad98e5 100644 --- a/pom.xml +++ b/pom.xml @@ -607,6 +607,7 @@ src/site/resources/checkstyle 4.0.0 + 4.0.6 false true @@ -767,7 +768,7 @@ com.github.spotbugs spotbugs - 4.0.6 + ${spotbugs.impl.version} From 954338a1522aa32b869966be63ef833d10cdd79e Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Wed, 1 Jul 2020 17:07:09 -0400 Subject: [PATCH 0253/3230] Sort 2 methods. --- .../org/apache/commons/lang3/StringUtils.java | 52 +++++++++---------- 1 file changed, 26 insertions(+), 26 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/StringUtils.java b/src/main/java/org/apache/commons/lang3/StringUtils.java index 67787200d86..0cb10e6753c 100644 --- a/src/main/java/org/apache/commons/lang3/StringUtils.java +++ b/src/main/java/org/apache/commons/lang3/StringUtils.java @@ -8635,41 +8635,35 @@ public static String substringAfter(final String str, final String separator) { * *

      A {@code null} string input will return {@code null}. * An empty ("") string input will return the empty string. - * An empty or {@code null} separator will return the empty string if - * the input string is not {@code null}.

      * *

      If nothing is found, the empty string is returned.

      * *
            * StringUtils.substringAfterLast(null, *)      = null
            * StringUtils.substringAfterLast("", *)        = ""
      -     * StringUtils.substringAfterLast(*, "")        = ""
      -     * StringUtils.substringAfterLast(*, null)      = ""
      -     * StringUtils.substringAfterLast("abc", "a")   = "bc"
      -     * StringUtils.substringAfterLast("abcba", "b") = "a"
      -     * StringUtils.substringAfterLast("abc", "c")   = ""
      -     * StringUtils.substringAfterLast("a", "a")     = ""
      -     * StringUtils.substringAfterLast("a", "z")     = ""
      +     * StringUtils.substringAfterLast("abc", 'a')   = "bc"
      +     * StringUtils.substringAfterLast(" bc", 32)    = "bc"
      +     * StringUtils.substringAfterLast("abcba", 'b') = "a"
      +     * StringUtils.substringAfterLast("abc", 'c')   = ""
      +     * StringUtils.substringAfterLast("a", 'a')     = ""
      +     * StringUtils.substringAfterLast("a", 'z')     = ""
            * 
      * * @param str the String to get a substring from, may be null * @param separator the String to search for, may be null * @return the substring after the last occurrence of the separator, * {@code null} if null String input - * @since 2.0 + * @since 3.11 */ - public static String substringAfterLast(final String str, final String separator) { + public static String substringAfterLast(final String str, final int separator) { if (isEmpty(str)) { return str; } - if (isEmpty(separator)) { - return EMPTY; - } final int pos = str.lastIndexOf(separator); - if (pos == INDEX_NOT_FOUND || pos == str.length() - separator.length()) { + if (pos == INDEX_NOT_FOUND || pos == str.length() - 1) { return EMPTY; } - return str.substring(pos + separator.length()); + return str.substring(pos + 1); } /** @@ -8678,35 +8672,41 @@ public static String substringAfterLast(final String str, final String separator * *

      A {@code null} string input will return {@code null}. * An empty ("") string input will return the empty string. + * An empty or {@code null} separator will return the empty string if + * the input string is not {@code null}.

      * *

      If nothing is found, the empty string is returned.

      * *
            * StringUtils.substringAfterLast(null, *)      = null
            * StringUtils.substringAfterLast("", *)        = ""
      -     * StringUtils.substringAfterLast("abc", 'a')   = "bc"
      -     * StringUtils.substringAfterLast(" bc", 32)    = "bc"
      -     * StringUtils.substringAfterLast("abcba", 'b') = "a"
      -     * StringUtils.substringAfterLast("abc", 'c')   = ""
      -     * StringUtils.substringAfterLast("a", 'a')     = ""
      -     * StringUtils.substringAfterLast("a", 'z')     = ""
      +     * StringUtils.substringAfterLast(*, "")        = ""
      +     * StringUtils.substringAfterLast(*, null)      = ""
      +     * StringUtils.substringAfterLast("abc", "a")   = "bc"
      +     * StringUtils.substringAfterLast("abcba", "b") = "a"
      +     * StringUtils.substringAfterLast("abc", "c")   = ""
      +     * StringUtils.substringAfterLast("a", "a")     = ""
      +     * StringUtils.substringAfterLast("a", "z")     = ""
            * 
      * * @param str the String to get a substring from, may be null * @param separator the String to search for, may be null * @return the substring after the last occurrence of the separator, * {@code null} if null String input - * @since 3.11 + * @since 2.0 */ - public static String substringAfterLast(final String str, final int separator) { + public static String substringAfterLast(final String str, final String separator) { if (isEmpty(str)) { return str; } + if (isEmpty(separator)) { + return EMPTY; + } final int pos = str.lastIndexOf(separator); - if (pos == INDEX_NOT_FOUND || pos == str.length() - 1) { + if (pos == INDEX_NOT_FOUND || pos == str.length() - separator.length()) { return EMPTY; } - return str.substring(pos + 1); + return str.substring(pos + separator.length()); } // SubStringAfter/SubStringBefore From ad433ecc1684683e3eba11dc198cc0d853299410 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Wed, 1 Jul 2020 17:21:55 -0400 Subject: [PATCH 0254/3230] Make internal API null-safe and Javadoc. --- .../commons/lang3/CharSequenceUtils.java | 23 +++++++++++-------- .../commons/lang3/CharSequenceUtilsTest.java | 1 + 2 files changed, 14 insertions(+), 10 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/CharSequenceUtils.java b/src/main/java/org/apache/commons/lang3/CharSequenceUtils.java index fc5350f52c3..ad12d9938e8 100644 --- a/src/main/java/org/apache/commons/lang3/CharSequenceUtils.java +++ b/src/main/java/org/apache/commons/lang3/CharSequenceUtils.java @@ -299,20 +299,23 @@ private static boolean checkLaterThan1(final CharSequence cs, final CharSequence } /** - * Green implementation of toCharArray. + * Converts the given CharSequence to a char[]. * - * @param cs the {@code CharSequence} to be processed - * @return the resulting char array + * @param source the {@code CharSequence} to be processed. + * @return the resulting char array, never null. * @since 3.11 */ - public static char[] toCharArray(final CharSequence cs) { - if (cs instanceof String) { - return ((String) cs).toCharArray(); + public static char[] toCharArray(final CharSequence source) { + final int len = StringUtils.length(source); + if (len == 0) { + return ArrayUtils.EMPTY_CHAR_ARRAY; } - final int sz = cs.length(); - final char[] array = new char[cs.length()]; - for (int i = 0; i < sz; i++) { - array[i] = cs.charAt(i); + if (source instanceof String) { + return ((String) source).toCharArray(); + } + final char[] array = new char[len]; + for (int i = 0; i < len; i++) { + array[i] = source.charAt(i); } return array; } diff --git a/src/test/java/org/apache/commons/lang3/CharSequenceUtilsTest.java b/src/test/java/org/apache/commons/lang3/CharSequenceUtilsTest.java index b21144c1c4f..7e2f4d16451 100644 --- a/src/test/java/org/apache/commons/lang3/CharSequenceUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/CharSequenceUtilsTest.java @@ -186,6 +186,7 @@ public void testToCharArray() { final char[] expected = builder.toString().toCharArray(); assertArrayEquals(expected, CharSequenceUtils.toCharArray(builder)); assertArrayEquals(expected, CharSequenceUtils.toCharArray(builder.toString())); + assertArrayEquals(ArrayUtils.EMPTY_CHAR_ARRAY, CharSequenceUtils.toCharArray(null)); } static class WrapperString implements CharSequence { From 065662fcf35087fd9100ee0e8827c11e309937c3 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sat, 4 Jul 2020 09:42:32 -0400 Subject: [PATCH 0255/3230] com.puppycrawl.tools:checkstyle 8.33 -> 8.34. --- pom.xml | 2 +- src/changes/changes.xml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 0e539ad98e5..433975f8f69 100644 --- a/pom.xml +++ b/pom.xml @@ -603,7 +603,7 @@ utf-8 3.1.1 - 8.33 + 8.34 src/site/resources/checkstyle 4.0.0 diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 0a48dd39b49..545e7139db0 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -89,7 +89,7 @@ The type attribute can be add,update,fix,remove. org.junit-pioneer:junit-pioneer 0.5.4 -> 0.6.0. org.junit.jupiter:junit-jupiter 5.6.0 -> 5.6.1. com.github.spotbugs:spotbugs 4.0.0 -> 4.0.6. - com.puppycrawl.tools:checkstyle 8.29 -> 8.33. + com.puppycrawl.tools:checkstyle 8.29 -> 8.34. commons.surefire.version 3.0.0-M4 -> 3.0.0-M5..
      From 32a9a350c67f1418784fff266d7e7881ca6346ad Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sat, 4 Jul 2020 09:45:02 -0400 Subject: [PATCH 0256/3230] org.junit.jupiter:junit-jupiter 5.6.1 -> 5.6.2. --- pom.xml | 2 +- src/changes/changes.xml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 433975f8f69..692bcd893a7 100644 --- a/pom.xml +++ b/pom.xml @@ -519,7 +519,7 @@ org.junit.jupiter junit-jupiter - 5.6.1 + 5.6.2 test diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 545e7139db0..c32c403348c 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -87,7 +87,7 @@ The type attribute can be add,update,fix,remove. Add org.apache.commons.lang3.StringUtils.substringAfterLast(String, int). org.apache.commons:commons-parent 50 -> 51. org.junit-pioneer:junit-pioneer 0.5.4 -> 0.6.0. - org.junit.jupiter:junit-jupiter 5.6.0 -> 5.6.1. + org.junit.jupiter:junit-jupiter 5.6.0 -> 5.6.2. com.github.spotbugs:spotbugs 4.0.0 -> 4.0.6. com.puppycrawl.tools:checkstyle 8.29 -> 8.34. commons.surefire.version 3.0.0-M4 -> 3.0.0-M5.. From 324363816774a1f9bca998950081130be6756611 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Thu, 9 Jul 2020 08:28:25 -0400 Subject: [PATCH 0257/3230] Stamped lock visitor (#559) Co-authored-by: Gary Gregory --- .../concurrent/locks/LockingVisitors.java | 575 ++++++++++++++++++ .../concurrent/locks/LockingVisitorsTest.java | 143 +++++ 2 files changed, 718 insertions(+) create mode 100644 src/main/java/org/apache/commons/lang3/concurrent/locks/LockingVisitors.java create mode 100644 src/test/java/org/apache/commons/lang3/concurrent/locks/LockingVisitorsTest.java diff --git a/src/main/java/org/apache/commons/lang3/concurrent/locks/LockingVisitors.java b/src/main/java/org/apache/commons/lang3/concurrent/locks/LockingVisitors.java new file mode 100644 index 00000000000..feccb423f73 --- /dev/null +++ b/src/main/java/org/apache/commons/lang3/concurrent/locks/LockingVisitors.java @@ -0,0 +1,575 @@ +/* + * 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.concurrent.locks; + +import java.util.Objects; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReadWriteLock; +import java.util.concurrent.locks.ReentrantReadWriteLock; +import java.util.concurrent.locks.StampedLock; +import java.util.function.LongSupplier; +import java.util.function.Supplier; + +import org.apache.commons.lang3.function.Failable; +import org.apache.commons.lang3.function.FailableConsumer; +import org.apache.commons.lang3.function.FailableFunction; + +/** + * Combines the monitor and visitor pattern to work with {@link java.util.concurrent.locks.Lock locked objects}. Locked + * objects are an alternative to synchronization. + * + * Locking is preferable, if there is a distinction between read access (multiple threads may have read access + * concurrently), and write access (only one thread may have write access at any given time. In comparison, + * synchronization doesn't support read access, because synchronized access is exclusive. + * + * Using this class is fairly straightforward: + *
        + *
      1. While still in single thread mode, create an instance of {@link LockingVisitors.StampedLockVisitor} by calling + * {@link #stampedLockVisitor(Object)}, passing the object, which needs to be locked. Discard all references to the + * locked object. Instead, use references to the lock.
      2. + *
      3. If you want to access the locked object, create a {@link FailableConsumer}. The consumer will receive the locked + * object as a parameter. For convenience, the consumer may be implemented as a Lambda. Then invoke + * {@link LockingVisitors.StampedLockVisitor#acceptReadLocked(FailableConsumer)}, or + * {@link LockingVisitors.StampedLockVisitor#acceptWriteLocked(FailableConsumer)}, passing the consumer.
      4. + *
      5. As an alternative, if you need to produce a result object, you may use a {@link FailableFunction}. This function + * may also be implemented as a Lambda. To have the function executed, invoke + * {@link LockingVisitors.StampedLockVisitor#applyReadLocked(FailableFunction)}, or + * {@link LockingVisitors.StampedLockVisitor#applyWriteLocked(FailableFunction)}.
      6. + *
      + * + * Example: A thread safe logger class. + * + *
      + *   public class SimpleLogger {
      + *
      + *     private final StampedLockVisitor<PrintStream> lock;
      + *
      + *     public SimpleLogger(OutputStream out) {
      + *         lock = LockingVisitors.stampedLockVisitor(new PrintStream(out));
      + *     }
      + *
      + *     public void log(String message) {
      + *         lock.acceptWriteLocked((ps) -> ps.println(message));
      + *     }
      + *
      + *     public void log(byte[] buffer) {
      + *         lock.acceptWriteLocked((ps) -> { ps.write(buffer); ps.println(); });
      + *     }
      + * 
      + * + * @since 3.11 + */ +public class LockingVisitors { + + /** + * Wraps a domain object for access by lambdas. + * + * @param the wrapped object type. + */ + public abstract static class AbstractLockVisitor { + protected AbstractLockVisitor(final O object) { + super(); + this.object = Objects.requireNonNull(object, "object"); + } + + protected final O object; + + /** + * Provides read (shared, non-exclusive) access to the locked (hidden) object. More precisely, what the method + * will do (in the given order): + *
        + *
      1. Obtain a read (shared) lock on the locked (hidden) object. The current thread may block, until such a + * lock is granted.
      2. + *
      3. Invokes the given {@link FailableConsumer consumer}, passing the locked object as the parameter.
      4. + *
      5. Release the lock, as soon as the consumers invocation is done. If the invocation results in an error, the + * lock will be released anyways.
      6. + *
      + * + * @param consumer The consumer, which is being invoked to use the hidden object, which will be passed as the + * consumers parameter. + * @see #acceptWriteLocked(FailableConsumer) + * @see #applyReadLocked(FailableFunction) + */ + public abstract void acceptReadLocked(FailableConsumer consumer); + + /** + * Provides write (exclusive) access to the locked (hidden) object. More precisely, what the method will do (in + * the given order): + *
        + *
      1. Obtain a write (shared) lock on the locked (hidden) object. The current thread may block, until such a + * lock is granted.
      2. + *
      3. Invokes the given {@link FailableConsumer consumer}, passing the locked object as the parameter.
      4. + *
      5. Release the lock, as soon as the consumers invocation is done. If the invocation results in an error, the + * lock will be released anyways.
      6. + *
      + * + * @param consumer The consumer, which is being invoked to use the hidden object, which will be passed as the + * consumers parameter. + * @see #acceptReadLocked(FailableConsumer) + * @see #applyWriteLocked(FailableFunction) + */ + public abstract void acceptWriteLocked(FailableConsumer consumer); + + /** + * Provides read (shared, non-exclusive) access to the locked (hidden) object for the purpose of computing a + * result object. More precisely, what the method will do (in the given order): + *
        + *
      1. Obtain a read (shared) lock on the locked (hidden) object. The current thread may block, until such a + * lock is granted.
      2. + *
      3. Invokes the given {@link FailableFunction function}, passing the locked object as the parameter, + * receiving the functions result.
      4. + *
      5. Release the lock, as soon as the consumers invocation is done. If the invocation results in an error, the + * lock will be released anyways.
      6. + *
      7. Return the result object, that has been received from the functions invocation.
      8. + *
      + * + * Example: Suggest, that the hidden object is a list, and we wish to know the current size of the + * list. This might be achieved with the following: + * + *
      +         * private Lock<List<Object>> listLock;
      +         *
      +         * public int getCurrentListSize() {
      +         *     final Integer sizeInteger = listLock.applyReadLocked((list) -> Integer.valueOf(list.size));
      +         *     return sizeInteger.intValue();
      +         * }
      +         * 
      + * + * @param The result type (both the functions, and this method's.) + * @param function The function, which is being invoked to compute the result. The function will receive the + * hidden object. + * @return The result object, which has been returned by the functions invocation. + * @throws IllegalStateException The result object would be, in fact, the hidden object. This would extend + * access to the hidden object beyond this methods lifetime and will therefore be prevented. + * @see #acceptReadLocked(FailableConsumer) + * @see #applyWriteLocked(FailableFunction) + */ + public abstract T applyReadLocked(FailableFunction function); + + /** + * Provides write (exclusive) access to the locked (hidden) object for the purpose of computing a result object. + * More precisely, what the method will do (in the given order): + *
        + *
      1. Obtain a read (shared) lock on the locked (hidden) object. The current thread may block, until such a + * lock is granted.
      2. + *
      3. Invokes the given {@link FailableFunction function}, passing the locked object as the parameter, + * receiving the functions result.
      4. + *
      5. Release the lock, as soon as the consumers invocation is done. If the invocation results in an error, the + * lock will be released anyways.
      6. + *
      7. Return the result object, that has been received from the functions invocation.
      8. + *
      + * + * @param The result type (both the functions, and this method's.) + * @param function The function, which is being invoked to compute the result. The function will receive the + * hidden object. + * @return The result object, which has been returned by the functions invocation. + * @throws IllegalStateException The result object would be, in fact, the hidden object. This would extend + * access to the hidden object beyond this methods lifetime and will therefore be prevented. + * @see #acceptReadLocked(FailableConsumer) + * @see #applyWriteLocked(FailableFunction) + */ + public abstract T applyWriteLocked(FailableFunction function); + + } + + /** + * This class implements a wrapper for a locked (hidden) object, and provides the means to access it. The basic + * idea, is that the user code forsakes all references to the locked object, using only the wrapper object, and the + * accessor methods {@link #acceptReadLocked(FailableConsumer)}, {@link #acceptWriteLocked(FailableConsumer)}, + * {@link #applyReadLocked(FailableFunction)}, and {@link #applyWriteLocked(FailableFunction)}. By doing so, the + * necessary protections are guaranteed. + * + * @param The locked (hidden) objects type. + */ + public static class ReadWriteLockVisitor extends AbstractLockVisitor { + private final ReadWriteLock readWriteLock; + + /** + * Creates a new instance with the given locked object. This constructor is supposed to be used for subclassing + * only. In general, it is suggested to use {@link LockingVisitors#stampedLockVisitor(Object)} instead. + * + * @param object The locked (hidden) object. The caller is supposed to drop all references to the locked object. + * @param readWriteLock the lock to use. + */ + public ReadWriteLockVisitor(final O object, final ReadWriteLock readWriteLock) { + super(object); + this.readWriteLock = readWriteLock; + } + + /** + * Provides read (shared, non-exclusive) access to the locked (hidden) object. More precisely, what the method + * will do (in the given order): + *
        + *
      1. Obtain a read (shared) lock on the locked (hidden) object. The current thread may block, until such a + * lock is granted.
      2. + *
      3. Invokes the given {@link FailableConsumer consumer}, passing the locked object as the parameter.
      4. + *
      5. Release the lock, as soon as the consumers invocation is done. If the invocation results in an error, the + * lock will be released anyways.
      6. + *
      + * + * @param consumer The consumer, which is being invoked to use the hidden object, which will be passed as the + * consumers parameter. + * @see #acceptWriteLocked(FailableConsumer) + * @see #applyReadLocked(FailableFunction) + */ + @Override + public void acceptReadLocked(final FailableConsumer consumer) { + lockAcceptUnlock(() -> readWriteLock.readLock(), consumer); + } + + /** + * Provides write (exclusive) access to the locked (hidden) object. More precisely, what the method will do (in + * the given order): + *
        + *
      1. Obtain a write (shared) lock on the locked (hidden) object. The current thread may block, until such a + * lock is granted.
      2. + *
      3. Invokes the given {@link FailableConsumer consumer}, passing the locked object as the parameter.
      4. + *
      5. Release the lock, as soon as the consumers invocation is done. If the invocation results in an error, the + * lock will be released anyways.
      6. + *
      + * + * @param consumer The consumer, which is being invoked to use the hidden object, which will be passed as the + * consumers parameter. + * @see #acceptReadLocked(FailableConsumer) + * @see #applyWriteLocked(FailableFunction) + */ + @Override + public void acceptWriteLocked(final FailableConsumer consumer) { + lockAcceptUnlock(() -> readWriteLock.writeLock(), consumer); + } + + /** + * Provides read (shared, non-exclusive) access to the locked (hidden) object for the purpose of computing a + * result object. More precisely, what the method will do (in the given order): + *
        + *
      1. Obtain a read (shared) lock on the locked (hidden) object. The current thread may block, until such a + * lock is granted.
      2. + *
      3. Invokes the given {@link FailableFunction function}, passing the locked object as the parameter, + * receiving the functions result.
      4. + *
      5. Release the lock, as soon as the consumers invocation is done. If the invocation results in an error, the + * lock will be released anyways.
      6. + *
      7. Return the result object, that has been received from the functions invocation.
      8. + *
      + * + * Example: Suggest, that the hidden object is a list, and we wish to know the current size of the + * list. This might be achieved with the following: + * + *
      +         * private Lock<List<Object>> listLock;
      +         *
      +         * public int getCurrentListSize() {
      +         *     final Integer sizeInteger = listLock.applyReadLocked((list) -> Integer.valueOf(list.size));
      +         *     return sizeInteger.intValue();
      +         * }
      +         * 
      + * + * @param The result type (both the functions, and this method's.) + * @param function The function, which is being invoked to compute the result. The function will receive the + * hidden object. + * @return The result object, which has been returned by the functions invocation. + * @throws IllegalStateException The result object would be, in fact, the hidden object. This would extend + * access to the hidden object beyond this methods lifetime and will therefore be prevented. + * @see #acceptReadLocked(FailableConsumer) + * @see #applyWriteLocked(FailableFunction) + */ + @Override + public T applyReadLocked(final FailableFunction function) { + return lockApplyUnlock(() -> readWriteLock.readLock(), function); + } + + /** + * Provides write (exclusive) access to the locked (hidden) object for the purpose of computing a result object. + * More precisely, what the method will do (in the given order): + *
        + *
      1. Obtain a read (shared) lock on the locked (hidden) object. The current thread may block, until such a + * lock is granted.
      2. + *
      3. Invokes the given {@link FailableFunction function}, passing the locked object as the parameter, + * receiving the functions result.
      4. + *
      5. Release the lock, as soon as the consumers invocation is done. If the invocation results in an error, the + * lock will be released anyways.
      6. + *
      7. Return the result object, that has been received from the functions invocation.
      8. + *
      + * + * @param The result type (both the functions, and this method's.) + * @param function The function, which is being invoked to compute the result. The function will receive the + * hidden object. + * @return The result object, which has been returned by the functions invocation. + * @throws IllegalStateException The result object would be, in fact, the hidden object. This would extend + * access to the hidden object beyond this methods lifetime and will therefore be prevented. + * @see #acceptReadLocked(FailableConsumer) + * @see #applyWriteLocked(FailableFunction) + */ + @Override + public T applyWriteLocked(final FailableFunction function) { + return lockApplyUnlock(() -> readWriteLock.writeLock(), function); + } + + /** + * This method provides the actual implementation for {@link #acceptReadLocked(FailableConsumer)}, and + * {@link #acceptWriteLocked(FailableConsumer)}. + * + * @param lock A supplier for the lock. (This provides, in fact, a long, because a {@link StampedLock} is used + * internally.) + * @param consumer The consumer, which is to be given access to the locked (hidden) object, which will be passed + * as a parameter. + * @see #acceptReadLocked(FailableConsumer) + * @see #acceptWriteLocked(FailableConsumer) + * @see #lockApplyUnlock(LongSupplier, FailableFunction) + */ + private void lockAcceptUnlock(final Supplier lockSupplier, final FailableConsumer consumer) { + final Lock lock = lockSupplier.get(); + try { + consumer.accept(object); + } catch (Throwable t) { + throw Failable.rethrow(t); + } finally { + lock.unlock(); + } + } + + /** + * This method provides the actual implementation for {@link #applyReadLocked(FailableFunction)}, and + * {@link #applyWriteLocked(FailableFunction)}. + * + * @param The result type (both the functions, and this method's.) + * @param lock A supplier for the lock. (This provides, in fact, a long, because a {@link StampedLock} is used + * internally.) + * @param function The function, which is being invoked to compute the result object. This function will receive + * the locked (hidden) object as a parameter. + * @return The result object, which has been returned by the functions invocation. + * @throws IllegalStateException The result object would be, in fact, the hidden object. This would extend + * access to the hidden object beyond this methods lifetime and will therefore be prevented. + * @see #applyReadLocked(FailableFunction) + * @see #applyWriteLocked(FailableFunction) + * @see #lockAcceptUnlock(LongSupplier, FailableConsumer) + */ + private T lockApplyUnlock(final Supplier lockSupplier, final FailableFunction function) { + final Lock lock = lockSupplier.get(); + try { + return function.apply(object); + } catch (Throwable t) { + throw Failable.rethrow(t); + } finally { + lock.unlock(); + } + } + } + + /** + * This class implements a wrapper for a locked (hidden) object, and provides the means to access it. The basic + * idea, is that the user code forsakes all references to the locked object, using only the wrapper object, and the + * accessor methods {@link #acceptReadLocked(FailableConsumer)}, {@link #acceptWriteLocked(FailableConsumer)}, + * {@link #applyReadLocked(FailableFunction)}, and {@link #applyWriteLocked(FailableFunction)}. By doing so, the + * necessary protections are guaranteed. + * + * @param The locked (hidden) objects type. + */ + public static class StampedLockVisitor extends AbstractLockVisitor { + private final StampedLock stampedLock = new StampedLock(); + + /** + * Creates a new instance with the given locked object. This constructor is supposed to be used for subclassing + * only. In general, it is suggested to use {@link LockingVisitors#stampedLockVisitor(Object)} instead. + * + * @param object The locked (hidden) object. The caller is supposed to drop all references to the locked object. + */ + public StampedLockVisitor(final O object) { + super(object); + } + + /** + * Provides read (shared, non-exclusive) access to the locked (hidden) object. More precisely, what the method + * will do (in the given order): + *
        + *
      1. Obtain a read (shared) lock on the locked (hidden) object. The current thread may block, until such a + * lock is granted.
      2. + *
      3. Invokes the given {@link FailableConsumer consumer}, passing the locked object as the parameter.
      4. + *
      5. Release the lock, as soon as the consumers invocation is done. If the invocation results in an error, the + * lock will be released anyways.
      6. + *
      + * + * @param consumer The consumer, which is being invoked to use the hidden object, which will be passed as the + * consumers parameter. + * @see #acceptWriteLocked(FailableConsumer) + * @see #applyReadLocked(FailableFunction) + */ + @Override + public void acceptReadLocked(final FailableConsumer consumer) { + lockAcceptUnlock(() -> stampedLock.readLock(), consumer); + } + + /** + * Provides write (exclusive) access to the locked (hidden) object. More precisely, what the method will do (in + * the given order): + *
        + *
      1. Obtain a write (shared) lock on the locked (hidden) object. The current thread may block, until such a + * lock is granted.
      2. + *
      3. Invokes the given {@link FailableConsumer consumer}, passing the locked object as the parameter.
      4. + *
      5. Release the lock, as soon as the consumers invocation is done. If the invocation results in an error, the + * lock will be released anyways.
      6. + *
      + * + * @param consumer The consumer, which is being invoked to use the hidden object, which will be passed as the + * consumers parameter. + * @see #acceptReadLocked(FailableConsumer) + * @see #applyWriteLocked(FailableFunction) + */ + @Override + public void acceptWriteLocked(final FailableConsumer consumer) { + lockAcceptUnlock(() -> stampedLock.writeLock(), consumer); + } + + /** + * Provides read (shared, non-exclusive) access to the locked (hidden) object for the purpose of computing a + * result object. More precisely, what the method will do (in the given order): + *
        + *
      1. Obtain a read (shared) lock on the locked (hidden) object. The current thread may block, until such a + * lock is granted.
      2. + *
      3. Invokes the given {@link FailableFunction function}, passing the locked object as the parameter, + * receiving the functions result.
      4. + *
      5. Release the lock, as soon as the consumers invocation is done. If the invocation results in an error, the + * lock will be released anyways.
      6. + *
      7. Return the result object, that has been received from the functions invocation.
      8. + *
      + * + * Example: Suggest, that the hidden object is a list, and we wish to know the current size of the + * list. This might be achieved with the following: + * + *
      +         * private Lock<List<Object>> listLock;
      +         *
      +         * public int getCurrentListSize() {
      +         *     final Integer sizeInteger = listLock.applyReadLocked((list) -> Integer.valueOf(list.size));
      +         *     return sizeInteger.intValue();
      +         * }
      +         * 
      + * + * @param The result type (both the functions, and this method's.) + * @param function The function, which is being invoked to compute the result. The function will receive the + * hidden object. + * @return The result object, which has been returned by the functions invocation. + * @throws IllegalStateException The result object would be, in fact, the hidden object. This would extend + * access to the hidden object beyond this methods lifetime and will therefore be prevented. + * @see #acceptReadLocked(FailableConsumer) + * @see #applyWriteLocked(FailableFunction) + */ + @Override + public T applyReadLocked(final FailableFunction function) { + return lockApplyUnlock(() -> stampedLock.readLock(), function); + } + + /** + * Provides write (exclusive) access to the locked (hidden) object for the purpose of computing a result object. + * More precisely, what the method will do (in the given order): + *
        + *
      1. Obtain a read (shared) lock on the locked (hidden) object. The current thread may block, until such a + * lock is granted.
      2. + *
      3. Invokes the given {@link FailableFunction function}, passing the locked object as the parameter, + * receiving the functions result.
      4. + *
      5. Release the lock, as soon as the consumers invocation is done. If the invocation results in an error, the + * lock will be released anyways.
      6. + *
      7. Return the result object, that has been received from the functions invocation.
      8. + *
      + * + * @param The result type (both the functions, and this method's.) + * @param function The function, which is being invoked to compute the result. The function will receive the + * hidden object. + * @return The result object, which has been returned by the functions invocation. + * @throws IllegalStateException The result object would be, in fact, the hidden object. This would extend + * access to the hidden object beyond this methods lifetime and will therefore be prevented. + * @see #acceptReadLocked(FailableConsumer) + * @see #applyWriteLocked(FailableFunction) + */ + @Override + public T applyWriteLocked(final FailableFunction function) { + return lockApplyUnlock(() -> stampedLock.writeLock(), function); + } + + /** + * This method provides the actual implementation for {@link #acceptReadLocked(FailableConsumer)}, and + * {@link #acceptWriteLocked(FailableConsumer)}. + * + * @param stampSupplier A supplier for the lock. (This provides, in fact, a long, because a {@link StampedLock} + * is used internally.) + * @param consumer The consumer, which is to be given access to the locked (hidden) object, which will be passed + * as a parameter. + * @see #acceptReadLocked(FailableConsumer) + * @see #acceptWriteLocked(FailableConsumer) + * @see #lockApplyUnlock(LongSupplier, FailableFunction) + */ + private void lockAcceptUnlock(final LongSupplier stampSupplier, final FailableConsumer consumer) { + final long stamp = stampSupplier.getAsLong(); + try { + consumer.accept(object); + } catch (Throwable t) { + throw Failable.rethrow(t); + } finally { + stampedLock.unlock(stamp); + } + } + + /** + * This method provides the actual implementation for {@link #applyReadLocked(FailableFunction)}, and + * {@link #applyWriteLocked(FailableFunction)}. + * + * @param The result type (both the functions, and this method's.) + * @param stampSupplier A supplier for the lock. (This provides, in fact, a long, because a {@link StampedLock} + * is used internally.) + * @param function The function, which is being invoked to compute the result object. This function will receive + * the locked (hidden) object as a parameter. + * @return The result object, which has been returned by the functions invocation. + * @throws IllegalStateException The result object would be, in fact, the hidden object. This would extend + * access to the hidden object beyond this methods lifetime and will therefore be prevented. + * @see #applyReadLocked(FailableFunction) + * @see #applyWriteLocked(FailableFunction) + * @see #lockAcceptUnlock(LongSupplier, FailableConsumer) + */ + private T lockApplyUnlock(final LongSupplier stampSupplier, final FailableFunction function) { + final long stamp = stampSupplier.getAsLong(); + try { + return function.apply(object); + } catch (Throwable t) { + throw Failable.rethrow(t); + } finally { + stampedLock.unlock(stamp); + } + } + } + + /** + * Creates a new instance of {@link StampedLockVisitor} with the given (hidden) object. + * + * @param The locked objects type. + * @param object The locked (hidden) object. + * @return The created instance, a {@link StampedLockVisitor lock} for the given object. + */ + public static StampedLockVisitor stampedLockVisitor(final O object) { + return new LockingVisitors.StampedLockVisitor<>(object); + } + + /** + * Creates a new instance of {@link ReadWriteLockVisitor} with the given (hidden) object. + * + * @param The locked objects type. + * @param object The locked (hidden) object. + * @return The created instance, a {@link StampedLockVisitor lock} for the given object. + */ + public static ReadWriteLockVisitor reentrantReadWriteLockVisitor(final O object) { + return new LockingVisitors.ReadWriteLockVisitor<>(object, new ReentrantReadWriteLock()); + } + +} diff --git a/src/test/java/org/apache/commons/lang3/concurrent/locks/LockingVisitorsTest.java b/src/test/java/org/apache/commons/lang3/concurrent/locks/LockingVisitorsTest.java new file mode 100644 index 00000000000..bd3a7ffbf0b --- /dev/null +++ b/src/test/java/org/apache/commons/lang3/concurrent/locks/LockingVisitorsTest.java @@ -0,0 +1,143 @@ +/* + * 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.concurrent.locks; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.function.LongConsumer; + +import org.apache.commons.lang3.concurrent.locks.LockingVisitors.AbstractLockVisitor; +import org.apache.commons.lang3.concurrent.locks.LockingVisitors.StampedLockVisitor; +import org.apache.commons.lang3.function.FailableConsumer; +import org.junit.jupiter.api.Test; + +public class LockingVisitorsTest { + private static final int NUMBER_OF_THREADS = 10; + private static final long DELAY_MILLIS = 3000; + private static final long TOTAL_DELAY_MILLIS = NUMBER_OF_THREADS * DELAY_MILLIS; + + @Test + public void testStampedLockNotExclusive() throws Exception { + + /* + * If our threads are running concurrently, then we expect to be faster than running one after the other. + */ + boolean[] booleanValues = new boolean[10]; + runTest(DELAY_MILLIS, false, l -> assertTrue(l < TOTAL_DELAY_MILLIS), booleanValues, + LockingVisitors.stampedLockVisitor(booleanValues)); + } + + @Test + public void testReentrantReadWriteLockNotExclusive() throws Exception { + + /* + * If our threads are running concurrently, then we expect to be faster than running one after the other. + */ + boolean[] booleanValues = new boolean[10]; + runTest(DELAY_MILLIS, false, l -> assertTrue(l < TOTAL_DELAY_MILLIS), booleanValues, + LockingVisitors.reentrantReadWriteLockVisitor(booleanValues)); + } + + @Test + public void testStampedLockExclusive() throws Exception { + + /* + * If our threads are running concurrently, then we expect to be no faster than running one after the other. + */ + boolean[] booleanValues = new boolean[10]; + runTest(DELAY_MILLIS, true, l -> assertTrue(l >= TOTAL_DELAY_MILLIS), booleanValues, + LockingVisitors.stampedLockVisitor(booleanValues)); + } + + @Test + public void testReentrantReadWriteLockExclusive() throws Exception { + + /* + * If our threads are running concurrently, then we expect to be no faster than running one after the other. + */ + boolean[] booleanValues = new boolean[10]; + runTest(DELAY_MILLIS, true, l -> assertTrue(l >= TOTAL_DELAY_MILLIS), booleanValues, + LockingVisitors.reentrantReadWriteLockVisitor(booleanValues)); + } + + @Test + public void testResultValidation() { + final Object hidden = new Object(); + final StampedLockVisitor lock = LockingVisitors.stampedLockVisitor(hidden); + final Object o1 = lock.applyReadLocked((h) -> { + return new Object(); }); + assertNotNull(o1); + assertNotSame(hidden, o1); + final Object o2 = lock.applyWriteLocked((h) -> { + return new Object(); }); + assertNotNull(o2); + assertNotSame(hidden, o2); + } + + private void runTest(final long delayMillis, final boolean exclusiveLock, final LongConsumer runTimeCheck, + boolean[] booleanValues, AbstractLockVisitor visitor) throws InterruptedException { + final boolean[] runningValues = new boolean[10]; + + final long startTime = System.currentTimeMillis(); + for (int i = 0; i < booleanValues.length; i++) { + final int index = i; + final FailableConsumer consumer = b -> { + b[index] = false; + Thread.sleep(delayMillis); + b[index] = true; + modify(runningValues, index, false); + }; + final Thread t = new Thread(() -> { + if (exclusiveLock) { + visitor.acceptWriteLocked(consumer); + } else { + visitor.acceptReadLocked(consumer); + } + }); + modify(runningValues, i, true); + t.start(); + } + while (someValueIsTrue(runningValues)) { + Thread.sleep(100); + } + final long endTime = System.currentTimeMillis(); + for (int i = 0; i < booleanValues.length; i++) { + assertTrue(booleanValues[i]); + } + // WRONG assumption + // runTimeCheck.accept(endTime - startTime); + } + + protected void modify(final boolean[] booleanArray, final int offset, final boolean value) { + synchronized (booleanArray) { + booleanArray[offset] = value; + } + } + + protected boolean someValueIsTrue(final boolean[] booleanArray) { + synchronized (booleanArray) { + for (int i = 0; i < booleanArray.length; i++) { + if (booleanArray[i]) { + return true; + } + } + return false; + } + } +} From 039c5293a1121cda51e209079b1a8f414448b9cd Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Thu, 9 Jul 2020 08:38:19 -0400 Subject: [PATCH 0258/3230] Clean up after merge. Class rename and package rename did not come through. --- .../commons/lang3/concurrent/locks/Locks.java | 298 ------------------ .../lang3/concurrent/locks/LocksTest.java | 134 -------- 2 files changed, 432 deletions(-) delete mode 100644 src/main/java/org/apache/commons/lang3/concurrent/locks/Locks.java delete mode 100644 src/test/java/org/apache/commons/lang3/concurrent/locks/LocksTest.java diff --git a/src/main/java/org/apache/commons/lang3/concurrent/locks/Locks.java b/src/main/java/org/apache/commons/lang3/concurrent/locks/Locks.java deleted file mode 100644 index 23d12826d9a..00000000000 --- a/src/main/java/org/apache/commons/lang3/concurrent/locks/Locks.java +++ /dev/null @@ -1,298 +0,0 @@ -/* - * 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.concurrent.locks; - -import java.util.Objects; -import java.util.concurrent.locks.StampedLock; -import java.util.function.LongSupplier; - -import org.apache.commons.lang3.function.Failable; -import org.apache.commons.lang3.function.FailableConsumer; -import org.apache.commons.lang3.function.FailableFunction; - -/** - * Utility class for working with {@link java.util.concurrent.locks.Lock locked objects}. Locked objects are an - * alternative to synchronization. - * - * Locking is preferable, if there is a distinction between read access (multiple threads may have read access - * concurrently), and write access (only one thread may have write access at any given time. In comparison, - * synchronization doesn't support read access, because synchronized access is exclusive. - * - * Using this class is fairly straightforward: - *
        - *
      1. While still in single thread mode, create an instance of {@link Locks.Lock} by calling {@link #lock(Object)}, - * passing the object, which needs to be locked. Discard all references to the locked object. Instead, use references to - * the lock.
      2. - *
      3. If you want to access the locked object, create a {@link FailableConsumer}. The consumer will receive the locked - * object as a parameter. For convenience, the consumer may be implemented as a Lambda. Then invoke - * {@link Locks.Lock#acceptReadLocked(FailableConsumer)}, or {@link Locks.Lock#acceptWriteLocked(FailableConsumer)}, passing - * the consumer.
      4. - *
      5. As an alternative, if you need to produce a result object, you may use a {@link FailableFunction}. This function - * may also be implemented as a Lambda. To have the function executed, invoke - * {@link Locks.Lock#applyReadLocked(FailableFunction)}, or {@link Locks.Lock#applyWriteLocked(FailableFunction)}.
      6. - *
      - * - * Example: A thread safe logger class. - * - *
      - *   public class SimpleLogger {
      - *
      - *     private final Lock<PrintStream> lock;
      - *
      - *     public SimpleLogger(OutputStream out) {
      - *         lock = Locks.lock(new PrintStream(out));
      - *     }
      - *
      - *     public void log(String message) {
      - *         lock.acceptWriteLocked((ps) -> ps.println(message));
      - *     }
      - *
      - *     public void log(byte[] buffer) {
      - *         lock.acceptWriteLocked((ps) -> { ps.write(buffer); ps.println(); });
      - *     }
      - * 
      - * - * @since 3.11 - */ -public class Locks { - - /** - * This class implements a wrapper for a locked (hidden) object, and - * provides the means to access it. The basic idea, is that the user - * code forsakes all references to the locked object, using only the - * wrapper object, and the accessor methods - * {@link #acceptReadLocked(FailableConsumer)}, - * {@link #acceptWriteLocked(FailableConsumer)}, - * {@link #applyReadLocked(FailableFunction)}, and - * {@link #applyWriteLocked(FailableFunction)}. By doing so, the - * necessary protections are guaranteed. - * @param The locked (hidden) objects type. - * - * @since 3.11 - */ - public static class Lock { - private final StampedLock lock = new StampedLock(); - private final O lockedObject; - - /** - * Creates a new instance with the given locked object. This - * constructor is supposed to be used for subclassing only. - * In general, it is suggested to use {@link Locks#lock(Object)} - * instead. - * @param lockedObject The locked (hidden) object. The caller is - * supposed to drop all references to the locked object. - */ - public Lock(final O lockedObject) { - this.lockedObject = Objects.requireNonNull(lockedObject, "Locked Object"); - } - - /** - * Provides read (shared, non-exclusive) access to the locked (hidden) object. - * More precisely, what the method will do (in the given order): - *
        - *
      1. Obtain a read (shared) lock on the locked (hidden) object. - * The current thread may block, until such a lock is granted. - *
      2. - *
      3. Invokes the given {@link FailableConsumer consumer}, passing the - * locked object as the parameter.
      4. - *
      5. Release the lock, as soon as the consumers invocation is done. - * If the invocation results in an error, the lock will be released - * anyways. - *
      6. - *
      - * @param consumer The consumer, which is being invoked to use the - * hidden object, which will be passed as the consumers parameter. - * @see #acceptWriteLocked(FailableConsumer) - * @see #applyReadLocked(FailableFunction) - */ - public void acceptReadLocked(final FailableConsumer consumer) { - lockAcceptUnlock(() -> lock.readLock(), consumer); - } - - /** - * Provides write (exclusive) access to the locked (hidden) object. - * More precisely, what the method will do (in the given order): - *
        - *
      1. Obtain a write (shared) lock on the locked (hidden) object. - * The current thread may block, until such a lock is granted. - *
      2. - *
      3. Invokes the given {@link FailableConsumer consumer}, passing the - * locked object as the parameter.
      4. - *
      5. Release the lock, as soon as the consumers invocation is done. - * If the invocation results in an error, the lock will be released - * anyways. - *
      6. - *
      - * @param consumer The consumer, which is being invoked to use the - * hidden object, which will be passed as the consumers parameter. - * @see #acceptReadLocked(FailableConsumer) - * @see #applyWriteLocked(FailableFunction) - */ - public void acceptWriteLocked(final FailableConsumer consumer) { - lockAcceptUnlock(() -> lock.writeLock(), consumer); - } - - /** - * Provides read (shared, non-exclusive) access to the locked (hidden) - * object for the purpose of computing a result object. - * More precisely, what the method will do (in the given order): - *
        - *
      1. Obtain a read (shared) lock on the locked (hidden) object. - * The current thread may block, until such a lock is granted. - *
      2. - *
      3. Invokes the given {@link FailableFunction function}, passing the - * locked object as the parameter, receiving the functions result.
      4. - *
      5. Release the lock, as soon as the consumers invocation is done. - * If the invocation results in an error, the lock will be released - * anyways. - *
      6. - *
      7. - * Return the result object, that has been received from the - * functions invocation.
      8. - *
      - * - * Example: Suggest, that the hidden object is a list, and we - * wish to know the current size of the list. This might be achieved - * with the following: - * - *
      -         *   private Lock<List<Object>> listLock;
      -         *
      -         *   public int getCurrentListSize() {
      -         *       final Integer sizeInteger
      -         *           = listLock.applyReadLocked((list) -> Integer.valueOf(list.size));
      -         *       return sizeInteger.intValue();
      -         *   }
      -         * 
      - * @param The result type (both the functions, and this method's.) - * @param function The function, which is being invoked to compute the - * result. The function will receive the hidden object. - * @return The result object, which has been returned by the - * functions invocation. - * @throws IllegalStateException The result object would be, in fact, - * the hidden object. This would extend access to the hidden object - * beyond this methods lifetime and will therefore be prevented. - * @see #acceptReadLocked(FailableConsumer) - * @see #applyWriteLocked(FailableFunction) - */ - public T applyReadLocked(final FailableFunction function) { - return lockApplyUnlock(() -> lock.readLock(), function); - } - - /** - * Provides write (exclusive) access to the locked (hidden) - * object for the purpose of computing a result object. - * More precisely, what the method will do (in the given order): - *
        - *
      1. Obtain a read (shared) lock on the locked (hidden) object. - * The current thread may block, until such a lock is granted. - *
      2. - *
      3. Invokes the given {@link FailableFunction function}, passing the - * locked object as the parameter, receiving the functions result.
      4. - *
      5. Release the lock, as soon as the consumers invocation is done. - * If the invocation results in an error, the lock will be released - * anyways. - *
      6. - *
      7. - * Return the result object, that has been received from the - * functions invocation.
      8. - *
      - * @param The result type (both the functions, and this method's.) - * @param function The function, which is being invoked to compute the - * result. The function will receive the hidden object. - * @return The result object, which has been returned by the - * functions invocation. - * @throws IllegalStateException The result object would be, in fact, - * the hidden object. This would extend access to the hidden object - * beyond this methods lifetime and will therefore be prevented. - * @see #acceptReadLocked(FailableConsumer) - * @see #applyWriteLocked(FailableFunction) - */ - public T applyWriteLocked(final FailableFunction function) { - return lockApplyUnlock(() -> lock.writeLock(), function); - } - - /** - * This method provides the actual implementation for - * {@link #acceptReadLocked(FailableConsumer)}, and - * {@link #acceptWriteLocked(FailableConsumer)}. - * @param stampSupplier A supplier for the lock. (This provides, in - * fact, a long, because a {@link StampedLock} is used internally.) - * @param consumer The consumer, which is to be given access to the - * locked (hidden) object, which will be passed as a parameter. - * @see #acceptReadLocked(FailableConsumer) - * @see #acceptWriteLocked(FailableConsumer) - * @see #lockApplyUnlock(LongSupplier, FailableFunction) - */ - protected void lockAcceptUnlock(final LongSupplier stampSupplier, final FailableConsumer consumer) { - final long stamp = stampSupplier.getAsLong(); - try { - consumer.accept(lockedObject); - } catch (final Throwable t) { - throw Failable.rethrow(t); - } finally { - lock.unlock(stamp); - } - } - - /** - * This method provides the actual implementation for - * {@link #applyReadLocked(FailableFunction)}, and - * {@link #applyWriteLocked(FailableFunction)}. - * @param The result type (both the functions, and this method's.) - * @param stampSupplier A supplier for the lock. (This provides, in - * fact, a long, because a {@link StampedLock} is used internally.) - * @param function The function, which is being invoked to compute - * the result object. This function will receive the locked (hidden) - * object as a parameter. - * @return The result object, which has been returned by the - * functions invocation. - * @throws IllegalStateException The result object would be, in fact, - * the hidden object. This would extend access to the hidden object - * beyond this methods lifetime and will therefore be prevented. - * @see #applyReadLocked(FailableFunction) - * @see #applyWriteLocked(FailableFunction) - * @see #lockAcceptUnlock(LongSupplier, FailableConsumer) - */ - protected T lockApplyUnlock(final LongSupplier stampSupplier, final FailableFunction function) { - final long stamp = stampSupplier.getAsLong(); - try { - final T t = function.apply(lockedObject); - if (t == lockedObject) { - throw new IllegalStateException("The returned object is, in fact, the hidden object."); - } - return t; - } catch (final Throwable t) { - throw Failable.rethrow(t); - } finally { - lock.unlock(stamp); - } - } - } - - /** - * Creates a new instance of {@link Lock} with the given locked - * (hidden) object. - * @param The locked objects type. - * @param object The locked (hidden) object. - * @return The created instance, a {@link Lock lock} for the - * given object. - */ - public static Locks.Lock lock(final O object) { - return new Locks.Lock<>(object); - } -} diff --git a/src/test/java/org/apache/commons/lang3/concurrent/locks/LocksTest.java b/src/test/java/org/apache/commons/lang3/concurrent/locks/LocksTest.java deleted file mode 100644 index 0f1f4730ad7..00000000000 --- a/src/test/java/org/apache/commons/lang3/concurrent/locks/LocksTest.java +++ /dev/null @@ -1,134 +0,0 @@ -/* - * 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.concurrent.locks; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNotSame; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; - -import java.util.function.LongConsumer; - -import org.apache.commons.lang3.concurrent.locks.Locks.Lock; -import org.apache.commons.lang3.function.FailableConsumer; -import org.junit.jupiter.api.Test; - -public class LocksTest { - private static final int NUMBER_OF_THREADS = 10; - - @Test - public void testReadLock() throws Exception { - final long DELAY=3000; - /** If our threads are running concurrently, then we expect to be faster - * than running one after the other. - */ - runTest(DELAY, false, l -> assertTrue(l < NUMBER_OF_THREADS*DELAY)); - } - - @Test - public void testWriteLock() throws Exception { - final long DELAY = 100; - /** If our threads are running concurrently, then we expect to be no faster - * than running one after the other. - */ - runTest(DELAY, true, l -> assertTrue(l >= NUMBER_OF_THREADS*DELAY)); - } - - @Test - public void testResultValidation() { - final Object hidden = new Object(); - final Lock lock = Locks.lock(hidden); - final Object o1 = lock.applyReadLocked((h) -> { - return new Object(); - }); - assertNotNull(o1); - assertNotSame(hidden, o1); - final Object o2 = lock.applyWriteLocked((h) -> { - return new Object(); - }); - assertNotNull(o2); - assertNotSame(hidden, o2); - try { - lock.applyReadLocked((h) -> { - return hidden; - }); - fail("Expected Exception"); - } catch (IllegalStateException e) { - assertEquals("The returned object is, in fact, the hidden object.", e.getMessage()); - } - try { - lock.applyReadLocked((h) -> { - return hidden; - }); - fail("Expected Exception"); - } catch (IllegalStateException e) { - assertEquals("The returned object is, in fact, the hidden object.", e.getMessage()); - } - } - - private void runTest(final long delay, final boolean exclusiveLock, final LongConsumer runTimeCheck) throws InterruptedException { - final boolean[] booleanValues = new boolean[10]; - final Lock lock = Locks.lock(booleanValues); - final boolean[] runningValues = new boolean[10]; - - final long startTime = System.currentTimeMillis(); - for (int i = 0; i < booleanValues.length; i++) { - final int index = i; - final FailableConsumer consumer = b -> { - b[index] = false; - Thread.sleep(delay); - b[index] = true; - modify(runningValues, index, false); - }; - final Thread t = new Thread(() -> { - if (exclusiveLock) { - lock.acceptWriteLocked(consumer); - } else { - lock.acceptReadLocked(consumer); - } - }); - modify(runningValues, i, true); - t.start(); - } - while (someValueIsTrue(runningValues)) { - Thread.sleep(100); - } - final long endTime = System.currentTimeMillis(); - for (int i = 0; i < booleanValues.length; i++) { - assertTrue(booleanValues[i]); - } - runTimeCheck.accept(endTime-startTime); - } - - protected void modify(final boolean[] booleanArray, final int offset, final boolean value) { - synchronized(booleanArray) { - booleanArray[offset] = value; - } - } - - protected boolean someValueIsTrue(final boolean[] booleanArray) { - synchronized(booleanArray) { - for (int i = 0; i < booleanArray.length; i++) { - if (booleanArray[i]) { - return true; - } - } - return false; - } - } -} From 031f4f61b70ec88d16affc982a7092935fd4a0c9 Mon Sep 17 00:00:00 2001 From: XenoAmess Date: Thu, 9 Jul 2020 20:57:12 +0800 Subject: [PATCH 0259/3230] refine travis-ci scripts (#531) Cache Maven's .m2 folder. --- .travis.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.travis.yml b/.travis.yml index 614d812ddfc..7432cc48251 100644 --- a/.travis.yml +++ b/.travis.yml @@ -14,21 +14,21 @@ # limitations under the License. language: java +cache: + directories: + - $HOME/.m2 jdk: - openjdk8 - openjdk11 - openjdk14 - openjdk-ea - matrix: include: - os: linux-ppc64le jdk: openjdk8 allow_failures: - jdk: openjdk-ea - script: - mvn - after_success: - mvn clean test jacoco:report coveralls:report -Ptravis-jacoco javadoc:javadoc -Ddoclint=all From 3700641b4e745a1804b4409c58dee15b459dad16 Mon Sep 17 00:00:00 2001 From: Isira Seneviratne <31027858+Isira-Seneviratne@users.noreply.github.com> Date: Fri, 10 Jul 2020 01:26:19 +0000 Subject: [PATCH 0260/3230] Correct Javadocs of methods that use Validate.notNull() and replace some uses of Validate.isTrue() with Validate.notNull(). (#525) * Update Javadocs of methods that call Validate.notNull() to refer to NullPointerException instead of IllegalArgumentException for null values. * Use Validate.notNull() instead of Validate.isTrue() to check for null values, and update the associated tests to check for NullPointerException instead of IllegalArgumentException. --- .../org/apache/commons/lang3/CharUtils.java | 6 +++-- .../commons/lang3/SerializationUtils.java | 14 ++++------- .../commons/lang3/builder/DiffBuilder.java | 3 +-- .../commons/lang3/builder/DiffResult.java | 3 +-- .../apache/commons/lang3/math/Fraction.java | 6 ++--- .../commons/lang3/math/IEEE754rUtils.java | 8 +++---- .../commons/lang3/reflect/FieldUtils.java | 6 ++--- .../commons/lang3/reflect/MethodUtils.java | 16 +++++-------- .../apache/commons/lang3/time/DateUtils.java | 24 +++++++++---------- .../commons/lang3/time/FormatCache.java | 2 +- .../lang3/reflect/MethodUtilsTest.java | 6 ++--- 11 files changed, 43 insertions(+), 51 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/CharUtils.java b/src/main/java/org/apache/commons/lang3/CharUtils.java index b4e8ccf7edb..4e07693fb3e 100644 --- a/src/main/java/org/apache/commons/lang3/CharUtils.java +++ b/src/main/java/org/apache/commons/lang3/CharUtils.java @@ -131,7 +131,7 @@ public static Character toCharacterObject(final String str) { * * @param ch the character to convert * @return the char value of the Character - * @throws IllegalArgumentException if the Character is null + * @throws NullPointerException if the Character is null */ public static char toChar(final Character ch) { Validate.notNull(ch, "The Character must not be null"); @@ -172,6 +172,7 @@ public static char toChar(final Character ch, final char defaultValue) { * * @param str the character to convert * @return the char value of the first letter of the String + * @throws NullPointerException if the string is null * @throws IllegalArgumentException if the String is empty */ public static char toChar(final String str) { @@ -260,7 +261,8 @@ public static int toIntValue(final char ch, final int defaultValue) { * * @param ch the character to convert, not null * @return the int value of the character - * @throws IllegalArgumentException if the Character is not ASCII numeric or is null + * @throws NullPointerException if the Character is null + * @throws IllegalArgumentException if the Character is not ASCII numeric */ public static int toIntValue(final Character ch) { Validate.notNull(ch, "The character must not be null"); diff --git a/src/main/java/org/apache/commons/lang3/SerializationUtils.java b/src/main/java/org/apache/commons/lang3/SerializationUtils.java index 5f7ed8c12bc..ed46f2ab5d4 100644 --- a/src/main/java/org/apache/commons/lang3/SerializationUtils.java +++ b/src/main/java/org/apache/commons/lang3/SerializationUtils.java @@ -129,7 +129,7 @@ public static T roundtrip(final T msg) { * * @param obj the object to serialize to bytes, may be null * @param outputStream the stream to write to, must not be null - * @throws IllegalArgumentException if {@code outputStream} is {@code null} + * @throws NullPointerException if {@code outputStream} is {@code null} * @throws SerializationException (runtime) if the serialization fails */ public static void serialize(final Serializable obj, final OutputStream outputStream) { @@ -182,10 +182,8 @@ public static byte[] serialize(final Serializable obj) { * @param inputStream * the serialized object input stream, must not be null * @return the deserialized object - * @throws IllegalArgumentException - * if {@code inputStream} is {@code null} - * @throws SerializationException - * (runtime) if the serialization fails + * @throws NullPointerException if {@code inputStream} is {@code null} + * @throws SerializationException (runtime) if the serialization fails */ public static T deserialize(final InputStream inputStream) { Validate.notNull(inputStream, "The InputStream must not be null"); @@ -213,10 +211,8 @@ public static T deserialize(final InputStream inputStream) { * @param objectData * the serialized object, must not be null * @return the deserialized object - * @throws IllegalArgumentException - * if {@code objectData} is {@code null} - * @throws SerializationException - * (runtime) if the serialization fails + * @throws NullPointerException if {@code objectData} is {@code null} + * @throws SerializationException (runtime) if the serialization fails */ public static T deserialize(final byte[] objectData) { Validate.notNull(objectData, "The byte[] must not be null"); diff --git a/src/main/java/org/apache/commons/lang3/builder/DiffBuilder.java b/src/main/java/org/apache/commons/lang3/builder/DiffBuilder.java index 2ea1f69e634..fed655de6d6 100644 --- a/src/main/java/org/apache/commons/lang3/builder/DiffBuilder.java +++ b/src/main/java/org/apache/commons/lang3/builder/DiffBuilder.java @@ -943,8 +943,7 @@ public Object[] getRight() { * @param diffResult * the {@code DiffResult} to append * @return this - * @throws IllegalArgumentException - * if field name is {@code null} + * @throws NullPointerException if field name is {@code null} * @since 3.5 */ public DiffBuilder append(final String fieldName, diff --git a/src/main/java/org/apache/commons/lang3/builder/DiffResult.java b/src/main/java/org/apache/commons/lang3/builder/DiffResult.java index b8594ad6b7c..c55aafcd592 100644 --- a/src/main/java/org/apache/commons/lang3/builder/DiffResult.java +++ b/src/main/java/org/apache/commons/lang3/builder/DiffResult.java @@ -69,8 +69,7 @@ public class DiffResult implements Iterable> { * the style to use for the {@link #toString()} method. May be * {@code null}, in which case * {@link ToStringStyle#DEFAULT_STYLE} is used - * @throws IllegalArgumentException - * if {@code lhs}, {@code rhs} or {@code diffs} is {@code null} + * @throws NullPointerException if {@code lhs}, {@code rhs} or {@code diffs} is {@code null} */ DiffResult(final T lhs, final T rhs, final List> diffs, final ToStringStyle style) { diff --git a/src/main/java/org/apache/commons/lang3/math/Fraction.java b/src/main/java/org/apache/commons/lang3/math/Fraction.java index 7c11f2a2f86..e90e340ac55 100644 --- a/src/main/java/org/apache/commons/lang3/math/Fraction.java +++ b/src/main/java/org/apache/commons/lang3/math/Fraction.java @@ -308,7 +308,7 @@ public static Fraction getFraction(double value) { * * @param str the string to parse, must not be {@code null} * @return the new {@code Fraction} instance - * @throws IllegalArgumentException if the string is {@code null} + * @throws NullPointerException if the string is {@code null} * @throws NumberFormatException if the number format is invalid */ public static Fraction getFraction(String str) { @@ -773,7 +773,7 @@ private Fraction addSub(final Fraction fraction, final boolean isAdd) { * * @param fraction the fraction to multiply by, must not be {@code null} * @return a {@code Fraction} instance with the resulting values - * @throws IllegalArgumentException if the fraction is {@code null} + * @throws NullPointerException if the fraction is {@code null} * @throws ArithmeticException if the resulting numerator or denominator exceeds * {@code Integer.MAX_VALUE} */ @@ -795,7 +795,7 @@ public Fraction multiplyBy(final Fraction fraction) { * * @param fraction the fraction to divide by, must not be {@code null} * @return a {@code Fraction} instance with the resulting values - * @throws IllegalArgumentException if the fraction is {@code null} + * @throws NullPointerException if the fraction is {@code null} * @throws ArithmeticException if the fraction to divide by is zero * @throws ArithmeticException if the resulting numerator or denominator exceeds * {@code Integer.MAX_VALUE} diff --git a/src/main/java/org/apache/commons/lang3/math/IEEE754rUtils.java b/src/main/java/org/apache/commons/lang3/math/IEEE754rUtils.java index ae737cf6039..1af353d3cb4 100644 --- a/src/main/java/org/apache/commons/lang3/math/IEEE754rUtils.java +++ b/src/main/java/org/apache/commons/lang3/math/IEEE754rUtils.java @@ -32,7 +32,7 @@ public class IEEE754rUtils { * * @param array an array, must not be null or empty * @return the minimum value in the array - * @throws IllegalArgumentException if {@code array} is {@code null} + * @throws NullPointerException if {@code array} is {@code null} * @throws IllegalArgumentException if {@code array} is empty * @since 3.4 Changed signature from min(double[]) to min(double...) */ @@ -54,7 +54,7 @@ public static double min(final double... array) { * * @param array an array, must not be null or empty * @return the minimum value in the array - * @throws IllegalArgumentException if {@code array} is {@code null} + * @throws NullPointerException if {@code array} is {@code null} * @throws IllegalArgumentException if {@code array} is empty * @since 3.4 Changed signature from min(float[]) to min(float...) */ @@ -144,7 +144,7 @@ public static float min(final float a, final float b) { * * @param array an array, must not be null or empty * @return the minimum value in the array - * @throws IllegalArgumentException if {@code array} is {@code null} + * @throws NullPointerException if {@code array} is {@code null} * @throws IllegalArgumentException if {@code array} is empty * @since 3.4 Changed signature from max(double[]) to max(double...) */ @@ -166,7 +166,7 @@ public static double max(final double... array) { * * @param array an array, must not be null or empty * @return the minimum value in the array - * @throws IllegalArgumentException if {@code array} is {@code null} + * @throws NullPointerException if {@code array} is {@code null} * @throws IllegalArgumentException if {@code array} is empty * @since 3.4 Changed signature from max(float[]) to max(float...) */ diff --git a/src/main/java/org/apache/commons/lang3/reflect/FieldUtils.java b/src/main/java/org/apache/commons/lang3/reflect/FieldUtils.java index 2a78f5885a0..0e1ed7adf75 100644 --- a/src/main/java/org/apache/commons/lang3/reflect/FieldUtils.java +++ b/src/main/java/org/apache/commons/lang3/reflect/FieldUtils.java @@ -81,9 +81,9 @@ public static Field getField(final Class cls, final String fieldName) { * {@link java.lang.reflect.AccessibleObject#setAccessible(boolean)} method. {@code false} will only * match {@code public} fields. * @return the Field object - * @throws IllegalArgumentException - * if the class is {@code null}, or the field name is blank or empty or is matched at multiple places - * in the inheritance hierarchy + * @throws NullPointerException if the class is {@code null} + * @throws IllegalArgumentException if the field name is blank or empty or is matched at multiple places + * in the inheritance hierarchy */ public static Field getField(final Class cls, final String fieldName, final boolean forceAccess) { Validate.notNull(cls, "The class must not be null"); diff --git a/src/main/java/org/apache/commons/lang3/reflect/MethodUtils.java b/src/main/java/org/apache/commons/lang3/reflect/MethodUtils.java index 125bba373b8..3ddeac59077 100644 --- a/src/main/java/org/apache/commons/lang3/reflect/MethodUtils.java +++ b/src/main/java/org/apache/commons/lang3/reflect/MethodUtils.java @@ -847,8 +847,7 @@ public static Set getOverrideHierarchy(final Method method, final Interf * @param annotationCls * the {@link java.lang.annotation.Annotation} that must be present on a method to be matched * @return an array of Methods (possibly empty). - * @throws IllegalArgumentException - * if the class or annotation are {@code null} + * @throws NullPointerException if the class or annotation are {@code null} * @since 3.4 */ public static Method[] getMethodsWithAnnotation(final Class cls, final Class annotationCls) { @@ -881,8 +880,7 @@ public static List getMethodsListWithAnnotation(final Class cls, fina * @param ignoreAccess * determines if non public methods should be considered * @return an array of Methods (possibly empty). - * @throws IllegalArgumentException - * if the class or annotation are {@code null} + * @throws NullPointerException if the class or annotation are {@code null} * @since 3.6 */ public static Method[] getMethodsWithAnnotation(final Class cls, final Class annotationCls, @@ -903,8 +901,7 @@ public static Method[] getMethodsWithAnnotation(final Class cls, final Class< * @param ignoreAccess * determines if non public methods should be considered * @return a list of Methods (possibly empty). - * @throws IllegalArgumentException - * if the class or annotation are {@code null} + * @throws NullPointerException if either the class or annotation class is {@code null} * @since 3.6 */ public static List getMethodsListWithAnnotation(final Class cls, @@ -912,7 +909,7 @@ public static List getMethodsListWithAnnotation(final Class cls, final boolean searchSupers, final boolean ignoreAccess) { Validate.notNull(cls, "The class must not be null"); - Validate.isTrue(annotationCls != null, "The annotation class must not be null"); + Validate.notNull(annotationCls, "The annotation class must not be null"); final List> classes = (searchSupers ? getAllSuperclassesAndInterfaces(cls) : new ArrayList<>()); classes.add(0, cls); @@ -947,15 +944,14 @@ public static List getMethodsListWithAnnotation(final Class cls, * @param ignoreAccess * determines if underlying method has to be accessible * @return the first matching annotation, or {@code null} if not found - * @throws IllegalArgumentException - * if the method or annotation are {@code null} + * @throws NullPointerException if either the method or annotation class is {@code null} * @since 3.6 */ public static A getAnnotation(final Method method, final Class annotationCls, final boolean searchSupers, final boolean ignoreAccess) { Validate.notNull(method, "The method must not be null"); - Validate.isTrue(annotationCls != null, "The annotation class must not be null"); + Validate.notNull(annotationCls, "The annotation class must not be null"); if (!ignoreAccess && !MemberUtils.isAccessible(method)) { return null; } diff --git a/src/main/java/org/apache/commons/lang3/time/DateUtils.java b/src/main/java/org/apache/commons/lang3/time/DateUtils.java index fd340492c93..917515d7239 100644 --- a/src/main/java/org/apache/commons/lang3/time/DateUtils.java +++ b/src/main/java/org/apache/commons/lang3/time/DateUtils.java @@ -509,7 +509,7 @@ public static Date addMilliseconds(final Date date, final int amount) { * @param calendarField the calendar field to add to * @param amount the amount to add, may be negative * @return the new {@code Date} with the amount added - * @throws IllegalArgumentException if the date is null + * @throws NullPointerException if the date is null */ private static Date add(final Date date, final int calendarField, final int amount) { validateDateNotNull(date); @@ -736,7 +736,7 @@ public static Date round(final Date date, final int field) { * @param date the date to work with, not null * @param field the field from {@code Calendar} or {@code SEMI_MONTH} * @return the different rounded date, not null - * @throws IllegalArgumentException if the date is {@code null} + * @throws NullPointerException if the date is {@code null} * @throws ArithmeticException if the year is over 280 million */ public static Calendar round(final Calendar date, final int field) { @@ -776,7 +776,7 @@ private static IllegalArgumentException nullDateIllegalArgumentException() { * @param date the date to work with, either {@code Date} or {@code Calendar}, not null * @param field the field from {@code Calendar} or {@code SEMI_MONTH} * @return the different rounded date, not null - * @throws IllegalArgumentException if the date is {@code null} + * @throws NullPointerException if the date is {@code null} * @throws ClassCastException if the object type is not a {@code Date} or {@code Calendar} * @throws ArithmeticException if the year is over 280 million */ @@ -806,7 +806,7 @@ public static Date round(final Object date, final int field) { * @param date the date to work with, not null * @param field the field from {@code Calendar} or {@code SEMI_MONTH} * @return the different truncated date, not null - * @throws IllegalArgumentException if the date is {@code null} + * @throws NullPointerException if the date is {@code null} * @throws ArithmeticException if the year is over 280 million */ public static Date truncate(final Date date, final int field) { @@ -829,7 +829,7 @@ public static Date truncate(final Date date, final int field) { * @param date the date to work with, not null * @param field the field from {@code Calendar} or {@code SEMI_MONTH} * @return the different truncated date, not null - * @throws IllegalArgumentException if the date is {@code null} + * @throws NullPointerException if the date is {@code null} * @throws ArithmeticException if the year is over 280 million */ public static Calendar truncate(final Calendar date, final int field) { @@ -853,7 +853,7 @@ public static Calendar truncate(final Calendar date, final int field) { * @param date the date to work with, either {@code Date} or {@code Calendar}, not null * @param field the field from {@code Calendar} or {@code SEMI_MONTH} * @return the different truncated date, not null - * @throws IllegalArgumentException if the date is {@code null} + * @throws NullPointerException if the date is {@code null} * @throws ClassCastException if the object type is not a {@code Date} or {@code Calendar} * @throws ArithmeticException if the year is over 280 million */ @@ -883,7 +883,7 @@ public static Date truncate(final Object date, final int field) { * @param date the date to work with, not null * @param field the field from {@code Calendar} or {@code SEMI_MONTH} * @return the different ceil date, not null - * @throws IllegalArgumentException if the date is {@code null} + * @throws NullPointerException if the date is {@code null} * @throws ArithmeticException if the year is over 280 million * @since 2.5 */ @@ -907,7 +907,7 @@ public static Date ceiling(final Date date, final int field) { * @param date the date to work with, not null * @param field the field from {@code Calendar} or {@code SEMI_MONTH} * @return the different ceil date, not null - * @throws IllegalArgumentException if the date is {@code null} + * @throws NullPointerException if the date is {@code null} * @throws ArithmeticException if the year is over 280 million * @since 2.5 */ @@ -932,7 +932,7 @@ public static Calendar ceiling(final Calendar date, final int field) { * @param date the date to work with, either {@code Date} or {@code Calendar}, not null * @param field the field from {@code Calendar} or {@code SEMI_MONTH} * @return the different ceil date, not null - * @throws IllegalArgumentException if the date is {@code null} + * @throws NullPointerException if the date is {@code null} * @throws ClassCastException if the object type is not a {@code Date} or {@code Calendar} * @throws ArithmeticException if the year is over 280 million * @since 2.5 @@ -1121,7 +1121,7 @@ private static void modify(final Calendar val, final int field, final ModifyType * {@link DateUtils#RANGE_WEEK_RELATIVE}, * {@link DateUtils#RANGE_WEEK_CENTER} * @return the date iterator, not null, not null - * @throws IllegalArgumentException if the date is {@code null} + * @throws NullPointerException if the date is {@code null} * @throws IllegalArgumentException if the rangeStyle is invalid */ public static Iterator iterator(final Date focus, final int rangeStyle) { @@ -1643,8 +1643,8 @@ public static long getFragmentInDays(final Calendar calendar, final int fragment * @param fragment the Calendar field part of date to calculate * @param unit the time unit * @return number of units within the fragment of the date - * @throws IllegalArgumentException if the date is {@code null} or - * fragment is not supported + * @throws NullPointerException if the date is {@code null} + * @throws IllegalArgumentException if fragment is not supported * @since 2.4 */ private static long getFragment(final Date date, final int fragment, final TimeUnit unit) { diff --git a/src/main/java/org/apache/commons/lang3/time/FormatCache.java b/src/main/java/org/apache/commons/lang3/time/FormatCache.java index 08e78ae810d..a2682031096 100644 --- a/src/main/java/org/apache/commons/lang3/time/FormatCache.java +++ b/src/main/java/org/apache/commons/lang3/time/FormatCache.java @@ -65,8 +65,8 @@ public F getInstance() { * @param timeZone the time zone, null means use the default TimeZone * @param locale the locale, null means use the default Locale * @return a pattern based date/time formatter + * @throws NullPointerException if pattern is {@code null} * @throws IllegalArgumentException if pattern is invalid - * or {@code null} */ public F getInstance(final String pattern, TimeZone timeZone, Locale locale) { Validate.notNull(pattern, "pattern must not be null"); diff --git a/src/test/java/org/apache/commons/lang3/reflect/MethodUtilsTest.java b/src/test/java/org/apache/commons/lang3/reflect/MethodUtilsTest.java index ceafcac087f..5a6820d60e2 100644 --- a/src/test/java/org/apache/commons/lang3/reflect/MethodUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/reflect/MethodUtilsTest.java @@ -863,7 +863,7 @@ public void testGetAnnotationNotSearchSupersAndNotIgnoreAccess() throws NoSuchMe @Test public void testGetMethodsWithAnnotationIllegalArgumentException1() { - assertThrows(IllegalArgumentException.class, () -> MethodUtils.getMethodsWithAnnotation(FieldUtilsTest.class, null)); + assertThrows(NullPointerException.class, () -> MethodUtils.getMethodsWithAnnotation(FieldUtilsTest.class, null)); } @Test @@ -891,7 +891,7 @@ public void testGetMethodsListWithAnnotation() throws NoSuchMethodException { @Test public void testGetMethodsListWithAnnotationIllegalArgumentException1() { - assertThrows(IllegalArgumentException.class, () -> MethodUtils.getMethodsListWithAnnotation(FieldUtilsTest.class, null)); + assertThrows(NullPointerException.class, () -> MethodUtils.getMethodsListWithAnnotation(FieldUtilsTest.class, null)); } @Test @@ -906,7 +906,7 @@ public void testGetMethodsListWithAnnotationIllegalArgumentException3() { @Test public void testGetAnnotationIllegalArgumentException1() { - assertThrows(IllegalArgumentException.class, + assertThrows(NullPointerException.class, () -> MethodUtils.getAnnotation(FieldUtilsTest.class.getDeclaredMethods()[0], null, true, true)); } From 9dbabe249449aa7feef2375768d3472f75944db3 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Thu, 9 Jul 2020 21:27:42 -0400 Subject: [PATCH 0261/3230] Correct Javadocs of methods that use Validate.notNull() and replace some uses of Validate.isTrue() with Validate.notNull(). #525. --- src/changes/changes.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index c32c403348c..36fc8f596e4 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -85,6 +85,7 @@ The type attribute can be add,update,fix,remove. Make org.apache.commons.lang3.CharSequenceUtils.toCharArray(CharSequence) public. Add org.apache.commons.lang3.StringUtils.substringAfter(String, int). Add org.apache.commons.lang3.StringUtils.substringAfterLast(String, int). + Correct Javadocs of methods that use Validate.notNull() and replace some uses of Validate.isTrue() with Validate.notNull(). #525. org.apache.commons:commons-parent 50 -> 51. org.junit-pioneer:junit-pioneer 0.5.4 -> 0.6.0. org.junit.jupiter:junit-jupiter 5.6.0 -> 5.6.2. From ee6c682ed5fa8c1b33aa1d52a1e2f088b0191b6b Mon Sep 17 00:00:00 2001 From: Isira Seneviratne Date: Mon, 20 Apr 2020 08:37:38 +0530 Subject: [PATCH 0262/3230] Add allNull() and anyNull() methods to ObjectUtils, as well as their associated tests. --- .../org/apache/commons/lang3/ObjectUtils.java | 54 +++++++++++++++++++ .../apache/commons/lang3/ObjectUtilsTest.java | 31 +++++++++++ 2 files changed, 85 insertions(+) diff --git a/src/main/java/org/apache/commons/lang3/ObjectUtils.java b/src/main/java/org/apache/commons/lang3/ObjectUtils.java index 95e88622891..d68021f6c51 100644 --- a/src/main/java/org/apache/commons/lang3/ObjectUtils.java +++ b/src/main/java/org/apache/commons/lang3/ObjectUtils.java @@ -107,6 +107,32 @@ private Object readResolve() { */ public static final Null NULL = new Null(); + /** + * Checks if all values in the given array are {@code null}. + * + *

      + * If all the values are {@code null} or the array is {@code null} + * or empty, then {@code true} is returned, otherwise {@code false} is returned. + *

      + * + *
      +     * ObjectUtils.allNull(*)                = false
      +     * ObjectUtils.allNull(*, null)          = false
      +     * ObjectUtils.allNull(null, *)          = false
      +     * ObjectUtils.allNull(null, null, *, *) = false
      +     * ObjectUtils.allNull(null)             = true
      +     * ObjectUtils.allNull(null, null)       = true
      +     * 
      + * + * @param values the values to test, may be {@code null} or empty + * @return {@code true} if all values in the array are {@code null}s, + * {@code false} if there is at least one non-null value in the array. + * @since 3.11 + */ + public static boolean allNull(final Object... values) { + return !anyNotNull(values); + } + /** * Checks if all values in the array are not {@code nulls}. * @@ -146,6 +172,34 @@ public static boolean allNotNull(final Object... values) { return true; } + /** + * Checks if any value in the given array is {@code null}. + * + *

      + * If any of the values are {@code null} or the array is {@code null}, + * then {@code true} is returned, otherwise {@code false} is returned. + *

      + * + *
      +     * ObjectUtils.anyNull(*)             = false
      +     * ObjectUtils.anyNull(*, *)          = false
      +     * ObjectUtils.anyNull(null)          = true
      +     * ObjectUtils.anyNull(null, null)    = true
      +     * ObjectUtils.anyNull(null, *)       = true
      +     * ObjectUtils.anyNull(*, null)       = true
      +     * ObjectUtils.anyNull(*, *, null, *) = true
      +     * 
      + * + * @param values the values to test, may be {@code null} or empty + * @return {@code true} if there is at least one {@code null} value in the array, + * {@code false} if all the values are non-null. + * If the array is {@code null} or empty, {@code true} is also returned. + * @since 3.11 + */ + public static boolean anyNull(final Object... values) { + return !allNotNull(values); + } + /** * Checks if any value in the given array is not {@code null}. * diff --git a/src/test/java/org/apache/commons/lang3/ObjectUtilsTest.java b/src/test/java/org/apache/commons/lang3/ObjectUtilsTest.java index b1da3b69c9b..aa235bbeb23 100644 --- a/src/test/java/org/apache/commons/lang3/ObjectUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/ObjectUtilsTest.java @@ -172,6 +172,22 @@ public void testGetFirstNonNull() { assertEquals(Boolean.TRUE, ObjectUtils.getFirstNonNull(() -> null, () -> Boolean.TRUE)); } + /** + * Tests {@link ObjectUtils#anyNull(Object...)}. + */ + @Test + public void testAnyNull() { + assertTrue(ObjectUtils.anyNull((Object) null)); + assertTrue(ObjectUtils.anyNull(null, null, null)); + assertTrue(ObjectUtils.anyNull(null, FOO, BAR)); + assertTrue(ObjectUtils.anyNull(FOO, BAR, null)); + assertTrue(ObjectUtils.anyNull(FOO, BAR, null, FOO, BAR)); + + assertFalse(ObjectUtils.anyNull()); + assertFalse(ObjectUtils.anyNull(FOO)); + assertFalse(ObjectUtils.anyNull(FOO, BAR, 1, Boolean.TRUE, new Object(), new Object[]{})); + } + /** * Tests {@link ObjectUtils#anyNotNull(Object...)}. */ @@ -187,6 +203,21 @@ public void testAnyNotNull() { assertTrue(ObjectUtils.anyNotNull(null, null, null, null, FOO, BAR)); } + /** + * Tests {@link ObjectUtils#allNull(Object...)}. + */ + @Test + public void testAllNull() { + assertTrue(ObjectUtils.allNull()); + assertTrue(ObjectUtils.allNull((Object) null)); + assertTrue(ObjectUtils.allNull((Object[]) null)); + assertTrue(ObjectUtils.allNull(null, null, null)); + + assertFalse(ObjectUtils.allNull(FOO)); + assertFalse(ObjectUtils.allNull(null, FOO, null)); + assertFalse(ObjectUtils.allNull(null, null, null, null, FOO, BAR)); + } + /** * Tests {@link ObjectUtils#allNotNull(Object...)}. */ From 265b74aac7ec8e726d443084db1d87530419610e Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Fri, 10 Jul 2020 11:47:45 -0400 Subject: [PATCH 0263/3230] Format new class. --- .../apache/commons/lang3/stream/Streams.java | 762 +++++++++--------- 1 file changed, 390 insertions(+), 372 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/stream/Streams.java b/src/main/java/org/apache/commons/lang3/stream/Streams.java index f9759652344..c7fa930e641 100644 --- a/src/main/java/org/apache/commons/lang3/stream/Streams.java +++ b/src/main/java/org/apache/commons/lang3/stream/Streams.java @@ -66,425 +66,443 @@ */ public class Streams { - public static class ArrayCollector implements Collector, O[]> { - private static final Set characteristics = Collections.emptySet(); - private final Class elementType; + public static class ArrayCollector implements Collector, O[]> { + private static final Set characteristics = Collections.emptySet(); + private final Class elementType; - public ArrayCollector(final Class elementType) { - this.elementType = elementType; - } + public ArrayCollector(final Class elementType) { + this.elementType = elementType; + } - @Override - public BiConsumer, O> accumulator() { - return List::add; - } + @Override + public BiConsumer, O> accumulator() { + return List::add; + } - @Override - public Set characteristics() { - return characteristics; - } + @Override + public Set characteristics() { + return characteristics; + } - @Override - public BinaryOperator> combiner() { - return (left, right) -> { - left.addAll(right); - return left; - }; - } + @Override + public BinaryOperator> combiner() { + return (left, right) -> { + left.addAll(right); + return left; + }; + } - @Override - public Function, O[]> finisher() { - return list -> { - @SuppressWarnings("unchecked") - final O[] array = (O[]) Array.newInstance(elementType, list.size()); - return list.toArray(array); - }; - } + @Override + public Function, O[]> finisher() { + return list -> { + @SuppressWarnings("unchecked") + final O[] array = (O[]) Array.newInstance(elementType, list.size()); + return list.toArray(array); + }; + } - @Override - public Supplier> supplier() { - return ArrayList::new; + @Override + public Supplier> supplier() { + return ArrayList::new; + } } -} /** - * A reduced, and simplified version of a {@link Stream} with - * failable method signatures. - * @param The streams element type. - */ - public static class FailableStream { + * A reduced, and simplified version of a {@link Stream} with failable method signatures. + * + * @param The streams element type. + */ + public static class FailableStream { - private Stream stream; - private boolean terminated; + private Stream stream; + private boolean terminated; - /** - * Constructs a new instance with the given {@code stream}. - * @param stream The stream. - */ - public FailableStream(final Stream stream) { - this.stream = stream; - } + /** + * Constructs a new instance with the given {@code stream}. + * + * @param stream The stream. + */ + public FailableStream(final Stream stream) { + this.stream = stream; + } - /** - * Returns whether all elements of this stream match the provided predicate. - * May not evaluate the predicate on all elements if not necessary for - * determining the result. If the stream is empty then {@code true} is - * returned and the predicate is not evaluated. - * - *

      This is a short-circuiting terminal operation. - * - * \@apiNote - * This method evaluates the universal quantification of the - * predicate over the elements of the stream (for all x P(x)). If the - * stream is empty, the quantification is said to be vacuously - * satisfied and is always {@code true} (regardless of P(x)). - * - * @param predicate A non-interfering, stateless predicate to apply to - * elements of this stream - * @return {@code true} If either all elements of the stream match the - * provided predicate or the stream is empty, otherwise {@code false}. - */ - public boolean allMatch(final FailablePredicate predicate) { - assertNotTerminated(); - return stream().allMatch(Failable.asPredicate(predicate)); - } + /** + * Returns whether all elements of this stream match the provided predicate. May not evaluate the predicate on + * all elements if not necessary for determining the result. If the stream is empty then {@code true} is + * returned and the predicate is not evaluated. + * + *

      + * This is a short-circuiting terminal operation. + * + * \@apiNote This method evaluates the universal quantification of the predicate over the elements of + * the stream (for all x P(x)). If the stream is empty, the quantification is said to be vacuously + * satisfied and is always {@code true} (regardless of P(x)). + * + * @param predicate A non-interfering, stateless predicate to apply to elements of this stream + * @return {@code true} If either all elements of the stream match the provided predicate or the stream is + * empty, otherwise {@code false}. + */ + public boolean allMatch(final FailablePredicate predicate) { + assertNotTerminated(); + return stream().allMatch(Failable.asPredicate(predicate)); + } - /** - * Returns whether any elements of this stream match the provided - * predicate. May not evaluate the predicate on all elements if not - * necessary for determining the result. If the stream is empty then - * {@code false} is returned and the predicate is not evaluated. - * - *

      This is a short-circuiting terminal operation. - * - * \@apiNote - * This method evaluates the existential quantification of the - * predicate over the elements of the stream (for some x P(x)). - * - * @param predicate A non-interfering, stateless predicate to apply to - * elements of this stream - * @return {@code true} if any elements of the stream match the provided - * predicate, otherwise {@code false} - */ - public boolean anyMatch(final FailablePredicate predicate) { - assertNotTerminated(); - return stream().anyMatch(Failable.asPredicate(predicate)); - } + /** + * Returns whether any elements of this stream match the provided predicate. May not evaluate the predicate on + * all elements if not necessary for determining the result. If the stream is empty then {@code false} is + * returned and the predicate is not evaluated. + * + *

      + * This is a short-circuiting terminal operation. + * + * \@apiNote This method evaluates the existential quantification of the predicate over the elements of + * the stream (for some x P(x)). + * + * @param predicate A non-interfering, stateless predicate to apply to elements of this stream + * @return {@code true} if any elements of the stream match the provided predicate, otherwise {@code false} + */ + public boolean anyMatch(final FailablePredicate predicate) { + assertNotTerminated(); + return stream().anyMatch(Failable.asPredicate(predicate)); + } - protected void assertNotTerminated() { - if (terminated) { - throw new IllegalStateException("This stream is already terminated."); - } + protected void assertNotTerminated() { + if (terminated) { + throw new IllegalStateException("This stream is already terminated."); } + } - /** - * Performs a mutable reduction operation on the elements of this stream using a - * {@code Collector}. A {@code Collector} - * encapsulates the functions used as arguments to - * {@link #collect(Supplier, BiConsumer, BiConsumer)}, allowing for reuse of - * collection strategies and composition of collect operations such as - * multiple-level grouping or partitioning. - * - *

      If the underlying stream is parallel, and the {@code Collector} - * is concurrent, and either the stream is unordered or the collector is - * unordered, then a concurrent reduction will be performed - * (see {@link Collector} for details on concurrent reduction.) - * - *

      This is a terminal operation. - * - *

      When executed in parallel, multiple intermediate results may be - * instantiated, populated, and merged so as to maintain isolation of - * mutable data structures. Therefore, even when executed in parallel - * with non-thread-safe data structures (such as {@code ArrayList}), no - * additional synchronization is needed for a parallel reduction. - * - * \@apiNote - * The following will accumulate strings into an ArrayList: - *

      {@code
      -             *     List asList = stringStream.collect(Collectors.toList());
      -             * }
      - * - *

      The following will classify {@code Person} objects by city: - *

      {@code
      -             *     Map> peopleByCity
      -             *         = personStream.collect(Collectors.groupingBy(Person::getCity));
      -             * }
      - * - *

      The following will classify {@code Person} objects by state and city, - * cascading two {@code Collector}s together: - *

      {@code
      -             *     Map>> peopleByStateAndCity
      -             *         = personStream.collect(Collectors.groupingBy(Person::getState,
      -             *                                                      Collectors.groupingBy(Person::getCity)));
      -             * }
      - * - * @param the type of the result - * @param
      the intermediate accumulation type of the {@code Collector} - * @param collector the {@code Collector} describing the reduction - * @return the result of the reduction - * @see #collect(Supplier, BiConsumer, BiConsumer) - * @see Collectors - */ - public R collect(final Collector collector) { - makeTerminated(); - return stream().collect(collector); - } + /** + * Performs a mutable reduction operation on the elements of this stream using a {@code Collector}. A + * {@code Collector} encapsulates the functions used as arguments to + * {@link #collect(Supplier, BiConsumer, BiConsumer)}, allowing for reuse of collection strategies and + * composition of collect operations such as multiple-level grouping or partitioning. + * + *

      + * If the underlying stream is parallel, and the {@code Collector} is concurrent, and either the stream is + * unordered or the collector is unordered, then a concurrent reduction will be performed (see {@link Collector} + * for details on concurrent reduction.) + * + *

      + * This is a terminal operation. + * + *

      + * When executed in parallel, multiple intermediate results may be instantiated, populated, and merged so as to + * maintain isolation of mutable data structures. Therefore, even when executed in parallel with non-thread-safe + * data structures (such as {@code ArrayList}), no additional synchronization is needed for a parallel + * reduction. + * + * \@apiNote The following will accumulate strings into an ArrayList: + * + *

      +         * {
      +         *     @code
      +         *     List asList = stringStream.collect(Collectors.toList());
      +         * }
      +         * 
      + * + *

      + * The following will classify {@code Person} objects by city: + * + *

      +         * {
      +         *     @code
      +         *     Map> peopleByCity = personStream.collect(Collectors.groupingBy(Person::getCity));
      +         * }
      +         * 
      + * + *

      + * The following will classify {@code Person} objects by state and city, cascading two {@code Collector}s + * together: + * + *

      +         * {
      +         *     @code
      +         *     Map>> peopleByStateAndCity = personStream
      +         *         .collect(Collectors.groupingBy(Person::getState, Collectors.groupingBy(Person::getCity)));
      +         * }
      +         * 
      + * + * @param the type of the result + * @param
      the intermediate accumulation type of the {@code Collector} + * @param collector the {@code Collector} describing the reduction + * @return the result of the reduction + * @see #collect(Supplier, BiConsumer, BiConsumer) + * @see Collectors + */ + public R collect(final Collector collector) { + makeTerminated(); + return stream().collect(collector); + } - /** - * Performs a mutable reduction operation on the elements of this FailableStream. - * A mutable reduction is one in which the reduced value is a mutable result - * container, such as an {@code ArrayList}, and elements are incorporated by updating - * the state of the result rather than by replacing the result. This produces a result equivalent to: - *
      {@code
      -             *     R result = supplier.get();
      -             *     for (T element : this stream)
      -             *         accumulator.accept(result, element);
      -             *     return result;
      -             * }
      - * - *

      Like {@link #reduce(Object, BinaryOperator)}, {@code collect} operations - * can be parallelized without requiring additional synchronization. - * - *

      This is a terminal operation. - * - * \@apiNote There are many existing classes in the JDK whose signatures are - * well-suited for use with method references as arguments to {@code collect()}. - * For example, the following will accumulate strings into an {@code ArrayList}: - *

      {@code
      -             *     List asList = stringStream.collect(ArrayList::new, ArrayList::add,
      -             *                                                ArrayList::addAll);
      -             * }
      - * - *

      The following will take a stream of strings and concatenates them into a - * single string: - *

      {@code
      -             *     String concat = stringStream.collect(StringBuilder::new, StringBuilder::append,
      -             *                                          StringBuilder::append)
      -             *                                 .toString();
      -             * }
      - * - * @param type of the result - * @param
      Type of the accumulator. - * @param pupplier a function that creates a new result container. For a - * parallel execution, this function may be called - * multiple times and must return a fresh value each time. - * @param accumulator An associative, non-interfering, stateless function for - * incorporating an additional element into a result - * @param combiner An associative, non-interfering, stateless - * function for combining two values, which must be compatible with the - * accumulator function - * @return The result of the reduction - */ - public R collect(final Supplier pupplier, final BiConsumer accumulator, final BiConsumer combiner) { - makeTerminated(); - return stream().collect(pupplier, accumulator, combiner); - } + /** + * Performs a mutable reduction operation on the elements of this FailableStream. A mutable reduction is one in + * which the reduced value is a mutable result container, such as an {@code ArrayList}, and elements are + * incorporated by updating the state of the result rather than by replacing the result. This produces a result + * equivalent to: + * + *
      +         * {@code
      +         *     R result = supplier.get();
      +         *     for (T element : this stream)
      +         *         accumulator.accept(result, element);
      +         *     return result;
      +         * }
      +         * 
      + * + *

      + * Like {@link #reduce(Object, BinaryOperator)}, {@code collect} operations can be parallelized without + * requiring additional synchronization. + * + *

      + * This is a terminal operation. + * + * \@apiNote There are many existing classes in the JDK whose signatures are well-suited for use with method + * references as arguments to {@code collect()}. For example, the following will accumulate strings into an + * {@code ArrayList}: + * + *

      +         * {
      +         *     @code
      +         *     List asList = stringStream.collect(ArrayList::new, ArrayList::add, ArrayList::addAll);
      +         * }
      +         * 
      + * + *

      + * The following will take a stream of strings and concatenates them into a single string: + * + *

      +         * {
      +         *     @code
      +         *     String concat = stringStream.collect(StringBuilder::new, StringBuilder::append, StringBuilder::append)
      +         *         .toString();
      +         * }
      +         * 
      + * + * @param type of the result + * @param
      Type of the accumulator. + * @param pupplier a function that creates a new result container. For a parallel execution, this function may + * be called multiple times and must return a fresh value each time. + * @param accumulator An associative, non-interfering, stateless function for incorporating an additional + * element into a result + * @param combiner An associative, non-interfering, stateless function for combining two values, which must be + * compatible with the accumulator function + * @return The result of the reduction + */ + public R collect(final Supplier pupplier, final BiConsumer accumulator, + final BiConsumer combiner) { + makeTerminated(); + return stream().collect(pupplier, accumulator, combiner); + } - /** - * Returns a FailableStream consisting of the elements of this stream that match - * the given FailablePredicate. - * - *

      This is an intermediate operation. - * - * @param predicate a non-interfering, stateless predicate to apply to each - * element to determine if it should be included. - * @return the new stream - */ - public FailableStream filter(final FailablePredicate predicate){ - assertNotTerminated(); - stream = stream.filter(Failable.asPredicate(predicate)); - return this; - } + /** + * Returns a FailableStream consisting of the elements of this stream that match the given FailablePredicate. + * + *

      + * This is an intermediate operation. + * + * @param predicate a non-interfering, stateless predicate to apply to each element to determine if it should be + * included. + * @return the new stream + */ + public FailableStream filter(final FailablePredicate predicate) { + assertNotTerminated(); + stream = stream.filter(Failable.asPredicate(predicate)); + return this; + } - /** - * Performs an action for each element of this stream. - * - *

      This is a terminal operation. - * - *

      The behavior of this operation is explicitly nondeterministic. - * For parallel stream pipelines, this operation does not - * guarantee to respect the encounter order of the stream, as doing so - * would sacrifice the benefit of parallelism. For any given element, the - * action may be performed at whatever time and in whatever thread the - * library chooses. If the action accesses shared state, it is - * responsible for providing the required synchronization. - * - * @param action a non-interfering action to perform on the elements - */ - public void forEach(final FailableConsumer action) { - makeTerminated(); - stream().forEach(Failable.asConsumer(action)); - } + /** + * Performs an action for each element of this stream. + * + *

      + * This is a terminal operation. + * + *

      + * The behavior of this operation is explicitly nondeterministic. For parallel stream pipelines, this operation + * does not guarantee to respect the encounter order of the stream, as doing so would sacrifice the + * benefit of parallelism. For any given element, the action may be performed at whatever time and in whatever + * thread the library chooses. If the action accesses shared state, it is responsible for providing the required + * synchronization. + * + * @param action a non-interfering action to perform on the elements + */ + public void forEach(final FailableConsumer action) { + makeTerminated(); + stream().forEach(Failable.asConsumer(action)); + } - protected void makeTerminated() { - assertNotTerminated(); - terminated = true; - } + protected void makeTerminated() { + assertNotTerminated(); + terminated = true; + } - /** - * Returns a stream consisting of the results of applying the given - * function to the elements of this stream. - * - *

      This is an intermediate operation. - * - * @param The element type of the new stream - * @param mapper A non-interfering, stateless function to apply to each element - * @return the new stream - */ - public FailableStream map(final FailableFunction mapper) { - assertNotTerminated(); - return new FailableStream<>(stream.map(Failable.asFunction(mapper))); - } + /** + * Returns a stream consisting of the results of applying the given function to the elements of this stream. + * + *

      + * This is an intermediate operation. + * + * @param The element type of the new stream + * @param mapper A non-interfering, stateless function to apply to each element + * @return the new stream + */ + public FailableStream map(final FailableFunction mapper) { + assertNotTerminated(); + return new FailableStream<>(stream.map(Failable.asFunction(mapper))); + } - /** - * Performs a reduction on the elements of this stream, using the provided - * identity value and an associative accumulation function, and returns - * the reduced value. This is equivalent to: - *

      {@code
      -             *     T result = identity;
      -             *     for (T element : this stream)
      -             *         result = accumulator.apply(result, element)
      -             *     return result;
      -             * }
      - * - * but is not constrained to execute sequentially. - * - *

      The {@code identity} value must be an identity for the accumulator - * function. This means that for all {@code t}, - * {@code accumulator.apply(identity, t)} is equal to {@code t}. - * The {@code accumulator} function must be an associative function. - * - *

      This is a terminal operation. - * - * \@apiNote Sum, min, max, average, and string concatenation are all special - * cases of reduction. Summing a stream of numbers can be expressed as: - * - *

      {@code
      -             *     Integer sum = integers.reduce(0, (a, b) -> a+b);
      -             * }
      - * - * or: - * - *
      {@code
      -             *     Integer sum = integers.reduce(0, Integer::sum);
      -             * }
      - * - *

      While this may seem a more roundabout way to perform an aggregation - * compared to simply mutating a running total in a loop, reduction - * operations parallelize more gracefully, without needing additional - * synchronization and with greatly reduced risk of data races. - * - * @param identity the identity value for the accumulating function - * @param accumulator an associative, non-interfering, stateless - * function for combining two values - * @return the result of the reduction - */ - public O reduce(final O identity, final BinaryOperator accumulator) { - makeTerminated(); - return stream().reduce(identity, accumulator); - } + /** + * Performs a reduction on the elements of this stream, using the provided identity value and an associative + * accumulation function, and returns the reduced value. This is equivalent to: + * + *

      +         * {@code
      +         *     T result = identity;
      +         *     for (T element : this stream)
      +         *         result = accumulator.apply(result, element)
      +         *     return result;
      +         * }
      +         * 
      + * + * but is not constrained to execute sequentially. + * + *

      + * The {@code identity} value must be an identity for the accumulator function. This means that for all + * {@code t}, {@code accumulator.apply(identity, t)} is equal to {@code t}. The {@code accumulator} function + * must be an associative function. + * + *

      + * This is a terminal operation. + * + * \@apiNote Sum, min, max, average, and string concatenation are all special cases of reduction. Summing a + * stream of numbers can be expressed as: + * + *

      +         * {
      +         *     @code
      +         *     Integer sum = integers.reduce(0, (a, b) -> a + b);
      +         * }
      +         * 
      + * + * or: + * + *
      +         * {
      +         *     @code
      +         *     Integer sum = integers.reduce(0, Integer::sum);
      +         * }
      +         * 
      + * + *

      + * While this may seem a more roundabout way to perform an aggregation compared to simply mutating a running + * total in a loop, reduction operations parallelize more gracefully, without needing additional synchronization + * and with greatly reduced risk of data races. + * + * @param identity the identity value for the accumulating function + * @param accumulator an associative, non-interfering, stateless function for combining two values + * @return the result of the reduction + */ + public O reduce(final O identity, final BinaryOperator accumulator) { + makeTerminated(); + return stream().reduce(identity, accumulator); + } - /** - * Converts the FailableStream into an equivalent stream. - * @return A stream, which will return the same elements, which this FailableStream would return. - */ - public Stream stream() { - return stream; - } + /** + * Converts the FailableStream into an equivalent stream. + * + * @return A stream, which will return the same elements, which this FailableStream would return. + */ + public Stream stream() { + return stream; } + } /** - * Converts the given {@link Collection} into a {@link FailableStream}. - * This is basically a simplified, reduced version of the {@link Stream} - * class, with the same underlying element stream, except that failable - * objects, like {@link FailablePredicate}, {@link FailableFunction}, or - * {@link FailableConsumer} may be applied, instead of - * {@link Predicate}, {@link Function}, or {@link Consumer}. The idea is - * to rewrite a code snippet like this: + * Converts the given {@link Collection} into a {@link FailableStream}. This is basically a simplified, reduced + * version of the {@link Stream} class, with the same underlying element stream, except that failable objects, like + * {@link FailablePredicate}, {@link FailableFunction}, or {@link FailableConsumer} may be applied, instead of + * {@link Predicate}, {@link Function}, or {@link Consumer}. The idea is to rewrite a code snippet like this: + * *

      -     *     final List<O> list;
      -     *     final Method m;
      -     *     final Function<O,String> mapper = (o) -> {
      -     *         try {
      -     *             return (String) m.invoke(o);
      -     *         } catch (Throwable t) {
      -     *             throw Failable.rethrow(t);
      -     *         }
      -     *     };
      -     *     final List<String> strList = list.stream()
      -     *         .map(mapper).collect(Collectors.toList());
      -     *  
      - * as follows: - *
      -     *     final List<O> list;
      -     *     final Method m;
      -     *     final List<String> strList = Failable.stream(list.stream())
      -     *         .map((o) -> (String) m.invoke(o)).collect(Collectors.toList());
      -     *  
      - * While the second version may not be quite as - * efficient (because it depends on the creation of additional, - * intermediate objects, of type FailableStream), it is much more - * concise, and readable, and meets the spirit of Lambdas better - * than the first version. + * final List<O> list; + * final Method m; + * final Function<O, String> mapper = (o) -> { + * try { + * return (String) m.invoke(o); + * } catch (Throwable t) { + * throw Failable.rethrow(t); + * } + * }; + * final List<String> strList = list.stream().map(mapper).collect(Collectors.toList()); + * + * + * as follows: + * + *
      +     * final List<O> list;
      +     * final Method m;
      +     * final List<String> strList = Failable.stream(list.stream()).map((o) -> (String) m.invoke(o))
      +     *     .collect(Collectors.toList());
      +     * 
      + * + * While the second version may not be quite as efficient (because it depends on the creation of + * additional, intermediate objects, of type FailableStream), it is much more concise, and readable, and meets the + * spirit of Lambdas better than the first version. + * * @param The streams element type. * @param stream The stream, which is being converted. - * @return The {@link FailableStream}, which has been created by - * converting the stream. + * @return The {@link FailableStream}, which has been created by converting the stream. */ public static FailableStream stream(final Collection stream) { return stream(stream.stream()); } /** - * Converts the given {@link Stream stream} into a {@link FailableStream}. - * This is basically a simplified, reduced version of the {@link Stream} - * class, with the same underlying element stream, except that failable - * objects, like {@link FailablePredicate}, {@link FailableFunction}, or - * {@link FailableConsumer} may be applied, instead of - * {@link Predicate}, {@link Function}, or {@link Consumer}. The idea is - * to rewrite a code snippet like this: + * Converts the given {@link Stream stream} into a {@link FailableStream}. This is basically a simplified, reduced + * version of the {@link Stream} class, with the same underlying element stream, except that failable objects, like + * {@link FailablePredicate}, {@link FailableFunction}, or {@link FailableConsumer} may be applied, instead of + * {@link Predicate}, {@link Function}, or {@link Consumer}. The idea is to rewrite a code snippet like this: + * + *
      +     * final List<O> list;
      +     * final Method m;
      +     * final Function<O, String> mapper = (o) -> {
      +     *     try {
      +     *         return (String) m.invoke(o);
      +     *     } catch (Throwable t) {
      +     *         throw Failable.rethrow(t);
      +     *     }
      +     * };
      +     * final List<String> strList = list.stream().map(mapper).collect(Collectors.toList());
      +     * 
      + * + * as follows: + * *
      -     *     final List<O> list;
      -     *     final Method m;
      -     *     final Function<O,String> mapper = (o) -> {
      -     *         try {
      -     *             return (String) m.invoke(o);
      -     *         } catch (Throwable t) {
      -     *             throw Failable.rethrow(t);
      -     *         }
      -     *     };
      -     *     final List<String> strList = list.stream()
      -     *         .map(mapper).collect(Collectors.toList());
      -     *  
      - * as follows: - *
      -     *     final List<O> list;
      -     *     final Method m;
      -     *     final List<String> strList = Failable.stream(list.stream())
      -     *         .map((o) -> (String) m.invoke(o)).collect(Collectors.toList());
      -     *  
      - * While the second version may not be quite as - * efficient (because it depends on the creation of additional, - * intermediate objects, of type FailableStream), it is much more - * concise, and readable, and meets the spirit of Lambdas better - * than the first version. + * final List<O> list; + * final Method m; + * final List<String> strList = Failable.stream(list.stream()).map((o) -> (String) m.invoke(o)) + * .collect(Collectors.toList()); + * + * + * While the second version may not be quite as efficient (because it depends on the creation of + * additional, intermediate objects, of type FailableStream), it is much more concise, and readable, and meets the + * spirit of Lambdas better than the first version. + * * @param The streams element type. * @param stream The stream, which is being converted. - * @return The {@link FailableStream}, which has been created by - * converting the stream. + * @return The {@link FailableStream}, which has been created by converting the stream. */ public static FailableStream stream(final Stream stream) { return new FailableStream<>(stream); } /** - * Returns a {@code Collector} that accumulates the input elements into a - * new array. + * Returns a {@code Collector} that accumulates the input elements into a new array. * * @param pElementType Type of an element in the array. * @param the type of the input elements - * @return a {@code Collector} which collects all the input elements into an - * array, in encounter order + * @return a {@code Collector} which collects all the input elements into an array, in encounter order */ public static Collector toArray(final Class pElementType) { return new ArrayCollector<>(pElementType); From 4f9be0faabe494f1f9a2000df288d79d9ab6663b Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Fri, 10 Jul 2020 11:49:00 -0400 Subject: [PATCH 0264/3230] Checkstyle. --- .../apache/commons/lang3/stream/Streams.java | 40 +++++++++---------- 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/stream/Streams.java b/src/main/java/org/apache/commons/lang3/stream/Streams.java index c7fa930e641..201b227ea5b 100644 --- a/src/main/java/org/apache/commons/lang3/stream/Streams.java +++ b/src/main/java/org/apache/commons/lang3/stream/Streams.java @@ -109,7 +109,7 @@ public Supplier> supplier() { /** * A reduced, and simplified version of a {@link Stream} with failable method signatures. - * + * * @param The streams element type. */ public static class FailableStream { @@ -119,7 +119,7 @@ public static class FailableStream { /** * Constructs a new instance with the given {@code stream}. - * + * * @param stream The stream. */ public FailableStream(final Stream stream) { @@ -193,7 +193,7 @@ protected void assertNotTerminated() { * reduction. * * \@apiNote The following will accumulate strings into an ArrayList: - * + * *
                * {
                *     @code
      @@ -203,7 +203,7 @@ protected void assertNotTerminated() {
                *
                * 

      * The following will classify {@code Person} objects by city: - * + * *

                * {
                *     @code
      @@ -214,7 +214,7 @@ protected void assertNotTerminated() {
                * 

      * The following will classify {@code Person} objects by state and city, cascading two {@code Collector}s * together: - * + * *

                * {
                *     @code
      @@ -240,7 +240,7 @@ public  R collect(final Collector collector) {
                * which the reduced value is a mutable result container, such as an {@code ArrayList}, and elements are
                * incorporated by updating the state of the result rather than by replacing the result. This produces a result
                * equivalent to:
      -         * 
      +         *
                * 
                * {@code
                *     R result = supplier.get();
      @@ -260,7 +260,7 @@ public  R collect(final Collector collector) {
                * \@apiNote There are many existing classes in the JDK whose signatures are well-suited for use with method
                * references as arguments to {@code collect()}. For example, the following will accumulate strings into an
                * {@code ArrayList}:
      -         * 
      +         *
                * 
                * {
                *     @code
      @@ -270,7 +270,7 @@ public  R collect(final Collector collector) {
                *
                * 

      * The following will take a stream of strings and concatenates them into a single string: - * + * *

                * {
                *     @code
      @@ -354,7 +354,7 @@ public  FailableStream map(final FailableFunction mapper) {
               /**
                * Performs a reduction on the elements of this stream, using the provided identity value and an associative
                * accumulation function, and returns the reduced value. This is equivalent to:
      -         * 
      +         *
                * 
                * {@code
                *     T result = identity;
      @@ -409,7 +409,7 @@ public O reduce(final O identity, final BinaryOperator accumulator) {
       
               /**
                * Converts the FailableStream into an equivalent stream.
      -         * 
      +         *
                * @return A stream, which will return the same elements, which this FailableStream would return.
                */
               public Stream stream() {
      @@ -422,7 +422,7 @@ public Stream stream() {
            * version of the {@link Stream} class, with the same underlying element stream, except that failable objects, like
            * {@link FailablePredicate}, {@link FailableFunction}, or {@link FailableConsumer} may be applied, instead of
            * {@link Predicate}, {@link Function}, or {@link Consumer}. The idea is to rewrite a code snippet like this:
      -     * 
      +     *
            * 
            * final List<O> list;
            * final Method m;
      @@ -435,20 +435,20 @@ public Stream stream() {
            * };
            * final List<String> strList = list.stream().map(mapper).collect(Collectors.toList());
            * 
      - * + * * as follows: - * + * *
            * final List<O> list;
            * final Method m;
            * final List<String> strList = Failable.stream(list.stream()).map((o) -> (String) m.invoke(o))
            *     .collect(Collectors.toList());
            * 
      - * + * * While the second version may not be quite as efficient (because it depends on the creation of * additional, intermediate objects, of type FailableStream), it is much more concise, and readable, and meets the * spirit of Lambdas better than the first version. - * + * * @param The streams element type. * @param stream The stream, which is being converted. * @return The {@link FailableStream}, which has been created by converting the stream. @@ -462,7 +462,7 @@ public static FailableStream stream(final Collection stream) { * version of the {@link Stream} class, with the same underlying element stream, except that failable objects, like * {@link FailablePredicate}, {@link FailableFunction}, or {@link FailableConsumer} may be applied, instead of * {@link Predicate}, {@link Function}, or {@link Consumer}. The idea is to rewrite a code snippet like this: - * + * *
            * final List<O> list;
            * final Method m;
      @@ -475,20 +475,20 @@ public static  FailableStream stream(final Collection stream) {
            * };
            * final List<String> strList = list.stream().map(mapper).collect(Collectors.toList());
            * 
      - * + * * as follows: - * + * *
            * final List<O> list;
            * final Method m;
            * final List<String> strList = Failable.stream(list.stream()).map((o) -> (String) m.invoke(o))
            *     .collect(Collectors.toList());
            * 
      - * + * * While the second version may not be quite as efficient (because it depends on the creation of * additional, intermediate objects, of type FailableStream), it is much more concise, and readable, and meets the * spirit of Lambdas better than the first version. - * + * * @param The streams element type. * @param stream The stream, which is being converted. * @return The {@link FailableStream}, which has been created by converting the stream. From d5c29230d8cad9e83b39a730f8e4500462298339 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Fri, 10 Jul 2020 11:57:58 -0400 Subject: [PATCH 0265/3230] [LANG-1539] Add allNull() and anyNull() methods to ObjectUtils. #522. --- src/changes/changes.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 36fc8f596e4..7ae8b7d1960 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -86,6 +86,7 @@ The type attribute can be add,update,fix,remove. Add org.apache.commons.lang3.StringUtils.substringAfter(String, int). Add org.apache.commons.lang3.StringUtils.substringAfterLast(String, int). Correct Javadocs of methods that use Validate.notNull() and replace some uses of Validate.isTrue() with Validate.notNull(). #525. + Add allNull() and anyNull() methods to ObjectUtils. #522. org.apache.commons:commons-parent 50 -> 51. org.junit-pioneer:junit-pioneer 0.5.4 -> 0.6.0. org.junit.jupiter:junit-jupiter 5.6.0 -> 5.6.2. From 2296d0bb1405354fb226bf654545679c0c4e1b2a Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Fri, 10 Jul 2020 12:11:01 -0400 Subject: [PATCH 0266/3230] Fix Javadoc. --- .../org/apache/commons/lang3/Streams.java | 10 +++--- .../apache/commons/lang3/stream/Streams.java | 31 +++++++------------ 2 files changed, 17 insertions(+), 24 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/Streams.java b/src/main/java/org/apache/commons/lang3/Streams.java index c6afd0a27b1..6ff8d75dc61 100644 --- a/src/main/java/org/apache/commons/lang3/Streams.java +++ b/src/main/java/org/apache/commons/lang3/Streams.java @@ -155,7 +155,7 @@ public void forEach(final FailableConsumer action) { * with non-thread-safe data structures (such as {@code ArrayList}), no * additional synchronization is needed for a parallel reduction. * - * \@apiNote + * Note * The following will accumulate strings into an ArrayList: *
      {@code
                *     List asList = stringStream.collect(Collectors.toList());
      @@ -204,7 +204,7 @@ public  R collect(final Collector collector) {
                *
                * 

      This is a terminal operation. * - * \@apiNote There are many existing classes in the JDK whose signatures are + * Note There are many existing classes in the JDK whose signatures are * well-suited for use with method references as arguments to {@code collect()}. * For example, the following will accumulate strings into an {@code ArrayList}: *

      {@code
      @@ -257,7 +257,7 @@ public  R collect(final Supplier pupplier, final BiConsumerThis is a terminal operation.
                *
      -         * \@apiNote Sum, min, max, average, and string concatenation are all special
      +         * Note Sum, min, max, average, and string concatenation are all special
                * cases of reduction. Summing a stream of numbers can be expressed as:
                *
                * 
      {@code
      @@ -316,7 +316,7 @@ public Stream stream() {
                *
                * 

      This is a short-circuiting terminal operation. * - * \@apiNote + * Note * This method evaluates the universal quantification of the * predicate over the elements of the stream (for all x P(x)). If the * stream is empty, the quantification is said to be vacuously @@ -340,7 +340,7 @@ public boolean allMatch(final FailablePredicate predicate) { * *

      This is a short-circuiting terminal operation. * - * \@apiNote + * Note * This method evaluates the existential quantification of the * predicate over the elements of the stream (for some x P(x)). * diff --git a/src/main/java/org/apache/commons/lang3/stream/Streams.java b/src/main/java/org/apache/commons/lang3/stream/Streams.java index 201b227ea5b..ff4da1a68f7 100644 --- a/src/main/java/org/apache/commons/lang3/stream/Streams.java +++ b/src/main/java/org/apache/commons/lang3/stream/Streams.java @@ -134,7 +134,7 @@ public FailableStream(final Stream stream) { *

      * This is a short-circuiting terminal operation. * - * \@apiNote This method evaluates the universal quantification of the predicate over the elements of + * Note This method evaluates the universal quantification of the predicate over the elements of * the stream (for all x P(x)). If the stream is empty, the quantification is said to be vacuously * satisfied and is always {@code true} (regardless of P(x)). * @@ -155,7 +155,7 @@ public boolean allMatch(final FailablePredicate predicate) { *

      * This is a short-circuiting terminal operation. * - * \@apiNote This method evaluates the existential quantification of the predicate over the elements of + * Note This method evaluates the existential quantification of the predicate over the elements of * the stream (for some x P(x)). * * @param predicate A non-interfering, stateless predicate to apply to elements of this stream @@ -192,11 +192,10 @@ protected void assertNotTerminated() { * data structures (such as {@code ArrayList}), no additional synchronization is needed for a parallel * reduction. * - * \@apiNote The following will accumulate strings into an ArrayList: + * Note The following will accumulate strings into an ArrayList: * *

      -         * {
      -         *     @code
      +         *     {@code
                *     List asList = stringStream.collect(Collectors.toList());
                * }
                * 
      @@ -205,8 +204,7 @@ protected void assertNotTerminated() { * The following will classify {@code Person} objects by city: * *
      -         * {
      -         *     @code
      +         *     {@code
                *     Map> peopleByCity = personStream.collect(Collectors.groupingBy(Person::getCity));
                * }
                * 
      @@ -216,8 +214,7 @@ protected void assertNotTerminated() { * together: * *
      -         * {
      -         *     @code
      +         *     {@code
                *     Map>> peopleByStateAndCity = personStream
                *         .collect(Collectors.groupingBy(Person::getState, Collectors.groupingBy(Person::getCity)));
                * }
      @@ -257,13 +254,12 @@ public  R collect(final Collector collector) {
                * 

      * This is a terminal operation. * - * \@apiNote There are many existing classes in the JDK whose signatures are well-suited for use with method + * Note There are many existing classes in the JDK whose signatures are well-suited for use with method * references as arguments to {@code collect()}. For example, the following will accumulate strings into an * {@code ArrayList}: * *

      -         * {
      -         *     @code
      +         *     {@code
                *     List asList = stringStream.collect(ArrayList::new, ArrayList::add, ArrayList::addAll);
                * }
                * 
      @@ -272,8 +268,7 @@ public R collect(final Collector collector) { * The following will take a stream of strings and concatenates them into a single string: * *
      -         * {
      -         *     @code
      +         *     {@code
                *     String concat = stringStream.collect(StringBuilder::new, StringBuilder::append, StringBuilder::append)
                *         .toString();
                * }
      @@ -374,12 +369,11 @@ public  FailableStream map(final FailableFunction mapper) {
                * 

      * This is a terminal operation. * - * \@apiNote Sum, min, max, average, and string concatenation are all special cases of reduction. Summing a + * Note Sum, min, max, average, and string concatenation are all special cases of reduction. Summing a * stream of numbers can be expressed as: * *

      -         * {
      -         *     @code
      +         *     {@code
                *     Integer sum = integers.reduce(0, (a, b) -> a + b);
                * }
                * 
      @@ -387,8 +381,7 @@ public FailableStream map(final FailableFunction mapper) { * or: * *
      -         * {
      -         *     @code
      +         *     {@code
                *     Integer sum = integers.reduce(0, Integer::sum);
                * }
                * 
      From ab627f97bc84063b3c24d6c459a53733c6b06aa8 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Fri, 10 Jul 2020 19:29:13 -0400 Subject: [PATCH 0267/3230] Prepare for 3.11-RC1. --- README.md | 4 +- RELEASE-NOTES.txt | 93 +++++++++++++++++++++++++++++++++ src/changes/changes.xml | 2 +- src/site/xdoc/download_lang.xml | 26 ++++----- 4 files changed, 109 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index a2e48251eef..e5f1068697f 100644 --- a/README.md +++ b/README.md @@ -46,7 +46,7 @@ Apache Commons Lang [![Build Status](https://travis-ci.org/apache/commons-lang.svg)](https://travis-ci.org/apache/commons-lang) [![Coverage Status](https://coveralls.io/repos/apache/commons-lang/badge.svg)](https://coveralls.io/r/apache/commons-lang) [![Maven Central](https://maven-badges.herokuapp.com/maven-central/org.apache.commons/commons-lang3/badge.svg)](https://maven-badges.herokuapp.com/maven-central/org.apache.commons/commons-lang3/) -[![Javadocs](https://javadoc.io/badge/org.apache.commons/commons-lang3/3.10.svg)](https://javadoc.io/doc/org.apache.commons/commons-lang3/3.10) +[![Javadocs](https://javadoc.io/badge/org.apache.commons/commons-lang3/3.11.svg)](https://javadoc.io/doc/org.apache.commons/commons-lang3/3.11) Apache Commons Lang, a package of Java utility classes for the classes that are in java.lang's hierarchy, or are considered to be so @@ -69,7 +69,7 @@ Alternatively you can pull it from the central Maven repositories: org.apache.commons commons-lang3 - 3.10 + 3.11 ``` diff --git a/RELEASE-NOTES.txt b/RELEASE-NOTES.txt index 33771d08b4c..ee127ed42b3 100644 --- a/RELEASE-NOTES.txt +++ b/RELEASE-NOTES.txt @@ -1,3 +1,96 @@ + Apache Commons Lang + Version 3.11 + Release Notes + + +INTRODUCTION: + +This document contains the release notes for the 3.11 version of Apache Commons Lang. +Commons Lang is a set of utility functions and reusable components that should be of use in any +Java environment. + +Lang 3.9 and onwards now targets Java 8, making use of features that arrived with Java 8. + +For the advice on upgrading from 2.x to 3.x, see the following page: + + https://commons.apache.org/lang/article3_0.html + +Apache Commons Lang, a package of Java utility classes for the +classes that are in java.lang's hierarchy, or are considered to be so +standard as to justify existence in java.lang. + +New features and bug fixes. + +Changes in this version include: + +New features: +o Add ArrayUtils.isSameLength() to compare more array types #430. Thanks to XenoAmess, Gary Gregory. +o Added the Locks class as a convenient possibility to deal with locked objects. +o LANG-1568: Add to Functions: FailableBooleanSupplier, FailableIntSupplier, FailableLongSupplier, FailableDoubleSupplier, and so on. +o LANG-1569: Add ArrayUtils.get(T[], index, T) to provide an out-of-bounds default value. +o LANG-1570: Add JavaVersion enum constants for Java 14 and 15. #553. Thanks to Edgar Asatryan. +o Add JavaVersion enum constants for Java 16. Thanks to Gary Gregory. +o LANG-1556: Use Java 8 lambdas and Map operations. Thanks to XenoAmess. +o LANG-1565: Change removeLastFieldSeparator to use endsWith #550. Thanks to XenoAmess. +o LANG-1557: Change a Pattern to a static final field, for not letting it compile each time the function invoked. #542. Thanks to XenoAmess, Gary Gregory. +o Add ImmutablePair factory methods left() and right(). +o Add ObjectUtils.toString(Object, Supplier). +o Add org.apache.commons.lang3.StringUtils.substringAfter(String, int). +o Add org.apache.commons.lang3.StringUtils.substringAfterLast(String, int). + +Fixed Bugs: +o Fix Javadoc for StringUtils.appendIfMissingIgnoreCase() #507. Thanks to contextshuffling. +o LANG-1560: Refine Javadoc #545. Thanks to XenoAmess. +o LANG-1554: Fix typos #539. Thanks to XenoAmess. +o LANG-1555: Ignored exception `ignored`, should not be called so #540. Thanks to XenoAmess. +o LANG-1528: StringUtils.replaceEachRepeatedly gives IllegalStateException #505. Thanks to Edwin Delgado H. +o LANG-1543: [JSON string for maps] ToStringBuilder.reflectionToString doesnt render nested maps correctly. Thanks to Swaraj Pal, Wander Costa, Gary Gregory. +o Correct Javadocs of methods that use Validate.notNull() and replace some uses of Validate.isTrue() with Validate.notNull(). #525. Thanks to Isira Seneviratne. +o LANG-1539: Add allNull() and anyNull() methods to ObjectUtils. #522. Thanks to Isira Seneviratne. + +Changes: +o Refine test output for FastDateParserTest Thanks to Jin Xu. +o LANG-1549: CharSequenceUtils.lastIndexOf : remake it Thanks to Jin Xu. +o remove encoding and docEncoding and use inherited values from commons-parent Thanks to XenoAmess. +o Simplify null checks in Pair.hashCode() using Objects.hashCode(). #517. Thanks to Isira Seneviratne, Bruno P. Kinoshita. +o Simplify null checks in Triple.hashCode() using Objects.hashCode(). #516. Thanks to Isira Seneviratne, Bruno P. Kinoshita. +o Simplify some if statements in StringUtils. #521. Thanks to Isira Seneviratne, Bruno P. Kinoshita. +o LANG-1537: Simplify a null check in the private replaceEach() method of StringUtils. #514. Thanks to Isira Seneviratne, Bruno P. Kinoshita. +o LANG-1534: Replace some usages of the ternary operator with calls to Math.max() and Math.min() #512. Thanks to Isira Seneviratne, Bruno P. Kinoshita. +o (Javadoc) Fix return tag for throwableOf*() methods #518. Thanks to Arend v. Reinersdorff, Bruno P. Kinoshita. +o LANG-1545: CharSequenceUtils.regionMatches is wrong dealing with Georgian. Thanks to XenoAmess, Gary Gregory. +o LANG-1550: Optimize ArrayUtils::isArrayIndexValid method. #551. Thanks to Edgar Asatryan. +o LANG-1561: Use List.sort instead of Collection.sort #546. Thanks to XenoAmess. +o LANG-1563: Use StandardCharsets.UTF_8 #548. Thanks to XenoAmess. +o LANG-1564: Use Collections.singletonList insteadof Arrays.asList when there be only one element. #549. Thanks to XenoAmess. +o LANG-1553: Change array style from `int a[]` to `int[] a` #537. Thanks to XenoAmess. +o LANG-1552: Change from addAll to constructors for some List #536. Thanks to XenoAmess. +o LANG-1558: Simplify if as some conditions are covered by others #543. Thanks to XenoAmess. +o LANG-1567: Fixed Javadocs for setTestRecursive() #556. Thanks to Miguel Muñoz, Bruno P. Kinoshita, Gary Gregory. +o LANG-1542: ToStringBuilder.reflectionToString - Wrong JSON format when object has a List of Enum. Thanks to Tr?n Ng?c Khoa, Gary Gregory. +o Make org.apache.commons.lang3.CharSequenceUtils.toCharArray(CharSequence) public. +o org.apache.commons:commons-parent 50 -> 51. +o org.junit-pioneer:junit-pioneer 0.5.4 -> 0.6.0. +o org.junit.jupiter:junit-jupiter 5.6.0 -> 5.6.2. +o com.github.spotbugs:spotbugs 4.0.0 -> 4.0.6. +o com.puppycrawl.tools:checkstyle 8.29 -> 8.34. +o commons.surefire.version 3.0.0-M4 -> 3.0.0-M5.. + + +Historical list of changes: https://commons.apache.org/proper/commons-lang/changes-report.html + +For complete information on Apache Commons Lang, including instructions on how to submit bug reports, +patches, or suggestions for improvement, see the Apache Apache Commons Lang website: + +https://commons.apache.org/proper/commons-lang/ + +Download page: https://commons.apache.org/proper/commons-lang/download_csv.cgi + +Have fun! +-Apache Commons Team + +============================================================================= + Apache Commons Lang Version 3.10 Release Notes diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 7ae8b7d1960..2d616613e5e 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -45,7 +45,7 @@ The type attribute can be add,update,fix,remove. - + Refine test output for FastDateParserTest CharSequenceUtils.lastIndexOf : remake it remove encoding and docEncoding and use inherited values from commons-parent diff --git a/src/site/xdoc/download_lang.xml b/src/site/xdoc/download_lang.xml index b8491da3411..90a1f7c6a09 100644 --- a/src/site/xdoc/download_lang.xml +++ b/src/site/xdoc/download_lang.xml @@ -113,32 +113,32 @@ limitations under the License.

      -
      +
      - - - + + + - - - + + +
      commons-lang3-3.10-bin.tar.gzsha512pgpcommons-lang3-3.11-bin.tar.gzsha512pgp
      commons-lang3-3.10-bin.zipsha512pgpcommons-lang3-3.11-bin.zipsha512pgp
      - - - + + + - - - + + +
      commons-lang3-3.10-src.tar.gzsha512pgpcommons-lang3-3.11-src.tar.gzsha512pgp
      commons-lang3-3.10-src.zipsha512pgpcommons-lang3-3.11-src.zipsha512pgp
      From ac1070e84e42acf3c2ada36e4727c2d99b0fc48e Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Fri, 10 Jul 2020 19:32:01 -0400 Subject: [PATCH 0268/3230] Update POM version numbers for Apache Commons Lang release 3.11 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 692bcd893a7..bf5656604a8 100644 --- a/pom.xml +++ b/pom.xml @@ -26,7 +26,7 @@ 4.0.0 commons-lang3 - 3.11-SNAPSHOT + 3.11 Apache Commons Lang 2001 From ff4ef533a558a7a176e4649ce5c6d54fb2383217 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sat, 11 Jul 2020 16:39:14 -0400 Subject: [PATCH 0269/3230] Redo this class after Rob Tompkins found a bug. Much simpler now as well. --- .../concurrent/locks/LockingVisitors.java | 369 ++++-------------- .../concurrent/locks/LockingVisitorsTest.java | 4 +- 2 files changed, 69 insertions(+), 304 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/concurrent/locks/LockingVisitors.java b/src/main/java/org/apache/commons/lang3/concurrent/locks/LockingVisitors.java index feccb423f73..41164c006eb 100644 --- a/src/main/java/org/apache/commons/lang3/concurrent/locks/LockingVisitors.java +++ b/src/main/java/org/apache/commons/lang3/concurrent/locks/LockingVisitors.java @@ -21,7 +21,6 @@ import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.concurrent.locks.StampedLock; -import java.util.function.LongSupplier; import java.util.function.Supplier; import org.apache.commons.lang3.function.Failable; @@ -76,18 +75,26 @@ public class LockingVisitors { /** - * Wraps a domain object for access by lambdas. + * Wraps a domain object and a lock for access by lambdas. * * @param the wrapped object type. + * @param the wrapped lock type. */ - public abstract static class AbstractLockVisitor { - protected AbstractLockVisitor(final O object) { + public static class LockVisitor { + + private final L lock; + + private final O object; + private final Supplier readLockSupplier; + private final Supplier writeLockSupplier; + protected LockVisitor(final O object, L lock, Supplier readLockSupplier, Supplier writeLockSupplier) { super(); this.object = Objects.requireNonNull(object, "object"); + this.lock = Objects.requireNonNull(lock, "lock"); + this.readLockSupplier = Objects.requireNonNull(readLockSupplier, "readLockSupplier"); + this.writeLockSupplier = Objects.requireNonNull(writeLockSupplier, "writeLockSupplier"); } - protected final O object; - /** * Provides read (shared, non-exclusive) access to the locked (hidden) object. More precisely, what the method * will do (in the given order): @@ -104,7 +111,9 @@ protected AbstractLockVisitor(final O object) { * @see #acceptWriteLocked(FailableConsumer) * @see #applyReadLocked(FailableFunction) */ - public abstract void acceptReadLocked(FailableConsumer consumer); + public void acceptReadLocked(FailableConsumer consumer) { + lockAcceptUnlock(readLockSupplier, consumer); + } /** * Provides write (exclusive) access to the locked (hidden) object. More precisely, what the method will do (in @@ -122,7 +131,9 @@ protected AbstractLockVisitor(final O object) { * @see #acceptReadLocked(FailableConsumer) * @see #applyWriteLocked(FailableFunction) */ - public abstract void acceptWriteLocked(FailableConsumer consumer); + public void acceptWriteLocked(final FailableConsumer consumer) { + lockAcceptUnlock(writeLockSupplier, consumer); + } /** * Provides read (shared, non-exclusive) access to the locked (hidden) object for the purpose of computing a @@ -158,7 +169,9 @@ protected AbstractLockVisitor(final O object) { * @see #acceptReadLocked(FailableConsumer) * @see #applyWriteLocked(FailableFunction) */ - public abstract T applyReadLocked(FailableFunction function); + public T applyReadLocked(FailableFunction function) { + return lockApplyUnlock(readLockSupplier, function); + } /** * Provides write (exclusive) access to the locked (hidden) object for the purpose of computing a result object. @@ -182,156 +195,42 @@ protected AbstractLockVisitor(final O object) { * @see #acceptReadLocked(FailableConsumer) * @see #applyWriteLocked(FailableFunction) */ - public abstract T applyWriteLocked(FailableFunction function); - - } - - /** - * This class implements a wrapper for a locked (hidden) object, and provides the means to access it. The basic - * idea, is that the user code forsakes all references to the locked object, using only the wrapper object, and the - * accessor methods {@link #acceptReadLocked(FailableConsumer)}, {@link #acceptWriteLocked(FailableConsumer)}, - * {@link #applyReadLocked(FailableFunction)}, and {@link #applyWriteLocked(FailableFunction)}. By doing so, the - * necessary protections are guaranteed. - * - * @param The locked (hidden) objects type. - */ - public static class ReadWriteLockVisitor extends AbstractLockVisitor { - private final ReadWriteLock readWriteLock; - - /** - * Creates a new instance with the given locked object. This constructor is supposed to be used for subclassing - * only. In general, it is suggested to use {@link LockingVisitors#stampedLockVisitor(Object)} instead. - * - * @param object The locked (hidden) object. The caller is supposed to drop all references to the locked object. - * @param readWriteLock the lock to use. - */ - public ReadWriteLockVisitor(final O object, final ReadWriteLock readWriteLock) { - super(object); - this.readWriteLock = readWriteLock; + public T applyWriteLocked(final FailableFunction function) { + return lockApplyUnlock(writeLockSupplier, function); } /** - * Provides read (shared, non-exclusive) access to the locked (hidden) object. More precisely, what the method - * will do (in the given order): - *
        - *
      1. Obtain a read (shared) lock on the locked (hidden) object. The current thread may block, until such a - * lock is granted.
      2. - *
      3. Invokes the given {@link FailableConsumer consumer}, passing the locked object as the parameter.
      4. - *
      5. Release the lock, as soon as the consumers invocation is done. If the invocation results in an error, the - * lock will be released anyways.
      6. - *
      + * Gets the lock. * - * @param consumer The consumer, which is being invoked to use the hidden object, which will be passed as the - * consumers parameter. - * @see #acceptWriteLocked(FailableConsumer) - * @see #applyReadLocked(FailableFunction) + * @return the lock. */ - @Override - public void acceptReadLocked(final FailableConsumer consumer) { - lockAcceptUnlock(() -> readWriteLock.readLock(), consumer); + public L getLock() { + return lock; } /** - * Provides write (exclusive) access to the locked (hidden) object. More precisely, what the method will do (in - * the given order): - *
        - *
      1. Obtain a write (shared) lock on the locked (hidden) object. The current thread may block, until such a - * lock is granted.
      2. - *
      3. Invokes the given {@link FailableConsumer consumer}, passing the locked object as the parameter.
      4. - *
      5. Release the lock, as soon as the consumers invocation is done. If the invocation results in an error, the - * lock will be released anyways.
      6. - *
      + * Gets the object. * - * @param consumer The consumer, which is being invoked to use the hidden object, which will be passed as the - * consumers parameter. - * @see #acceptReadLocked(FailableConsumer) - * @see #applyWriteLocked(FailableFunction) + * @return the object. */ - @Override - public void acceptWriteLocked(final FailableConsumer consumer) { - lockAcceptUnlock(() -> readWriteLock.writeLock(), consumer); + public O getObject() { + return object; } /** - * Provides read (shared, non-exclusive) access to the locked (hidden) object for the purpose of computing a - * result object. More precisely, what the method will do (in the given order): - *
        - *
      1. Obtain a read (shared) lock on the locked (hidden) object. The current thread may block, until such a - * lock is granted.
      2. - *
      3. Invokes the given {@link FailableFunction function}, passing the locked object as the parameter, - * receiving the functions result.
      4. - *
      5. Release the lock, as soon as the consumers invocation is done. If the invocation results in an error, the - * lock will be released anyways.
      6. - *
      7. Return the result object, that has been received from the functions invocation.
      8. - *
      - * - * Example: Suggest, that the hidden object is a list, and we wish to know the current size of the - * list. This might be achieved with the following: - * - *
      -         * private Lock<List<Object>> listLock;
      -         *
      -         * public int getCurrentListSize() {
      -         *     final Integer sizeInteger = listLock.applyReadLocked((list) -> Integer.valueOf(list.size));
      -         *     return sizeInteger.intValue();
      -         * }
      -         * 
      - * - * @param The result type (both the functions, and this method's.) - * @param function The function, which is being invoked to compute the result. The function will receive the - * hidden object. - * @return The result object, which has been returned by the functions invocation. - * @throws IllegalStateException The result object would be, in fact, the hidden object. This would extend - * access to the hidden object beyond this methods lifetime and will therefore be prevented. - * @see #acceptReadLocked(FailableConsumer) - * @see #applyWriteLocked(FailableFunction) - */ - @Override - public T applyReadLocked(final FailableFunction function) { - return lockApplyUnlock(() -> readWriteLock.readLock(), function); - } - - /** - * Provides write (exclusive) access to the locked (hidden) object for the purpose of computing a result object. - * More precisely, what the method will do (in the given order): - *
        - *
      1. Obtain a read (shared) lock on the locked (hidden) object. The current thread may block, until such a - * lock is granted.
      2. - *
      3. Invokes the given {@link FailableFunction function}, passing the locked object as the parameter, - * receiving the functions result.
      4. - *
      5. Release the lock, as soon as the consumers invocation is done. If the invocation results in an error, the - * lock will be released anyways.
      6. - *
      7. Return the result object, that has been received from the functions invocation.
      8. - *
      - * - * @param The result type (both the functions, and this method's.) - * @param function The function, which is being invoked to compute the result. The function will receive the - * hidden object. - * @return The result object, which has been returned by the functions invocation. - * @throws IllegalStateException The result object would be, in fact, the hidden object. This would extend - * access to the hidden object beyond this methods lifetime and will therefore be prevented. - * @see #acceptReadLocked(FailableConsumer) - * @see #applyWriteLocked(FailableFunction) - */ - @Override - public T applyWriteLocked(final FailableFunction function) { - return lockApplyUnlock(() -> readWriteLock.writeLock(), function); - } - - /** - * This method provides the actual implementation for {@link #acceptReadLocked(FailableConsumer)}, and + * This method provides the default implementation for {@link #acceptReadLocked(FailableConsumer)}, and * {@link #acceptWriteLocked(FailableConsumer)}. * - * @param lock A supplier for the lock. (This provides, in fact, a long, because a {@link StampedLock} is used + * @param lockSupplier A supplier for the lock. (This provides, in fact, a long, because a {@link StampedLock} is used * internally.) * @param consumer The consumer, which is to be given access to the locked (hidden) object, which will be passed * as a parameter. * @see #acceptReadLocked(FailableConsumer) * @see #acceptWriteLocked(FailableConsumer) - * @see #lockApplyUnlock(LongSupplier, FailableFunction) */ - private void lockAcceptUnlock(final Supplier lockSupplier, final FailableConsumer consumer) { + protected void lockAcceptUnlock(final Supplier lockSupplier, final FailableConsumer consumer) { final Lock lock = lockSupplier.get(); + lock.lock(); try { consumer.accept(object); } catch (Throwable t) { @@ -346,7 +245,7 @@ private void lockAcceptUnlock(final Supplier lockSupplier, final FailableC * {@link #applyWriteLocked(FailableFunction)}. * * @param The result type (both the functions, and this method's.) - * @param lock A supplier for the lock. (This provides, in fact, a long, because a {@link StampedLock} is used + * @param lockSupplier A supplier for the lock. (This provides, in fact, a long, because a {@link StampedLock} is used * internally.) * @param function The function, which is being invoked to compute the result object. This function will receive * the locked (hidden) object as a parameter. @@ -355,10 +254,10 @@ private void lockAcceptUnlock(final Supplier lockSupplier, final FailableC * access to the hidden object beyond this methods lifetime and will therefore be prevented. * @see #applyReadLocked(FailableFunction) * @see #applyWriteLocked(FailableFunction) - * @see #lockAcceptUnlock(LongSupplier, FailableConsumer) */ - private T lockApplyUnlock(final Supplier lockSupplier, final FailableFunction function) { + protected T lockApplyUnlock(final Supplier lockSupplier, final FailableFunction function) { final Lock lock = lockSupplier.get(); + lock.lock(); try { return function.apply(object); } catch (Throwable t) { @@ -367,6 +266,7 @@ private T lockApplyUnlock(final Supplier lockSupplier, final FailableF lock.unlock(); } } + } /** @@ -378,198 +278,63 @@ private T lockApplyUnlock(final Supplier lockSupplier, final FailableF * * @param The locked (hidden) objects type. */ - public static class StampedLockVisitor extends AbstractLockVisitor { - private final StampedLock stampedLock = new StampedLock(); + public static class ReadWriteLockVisitor extends LockVisitor { /** * Creates a new instance with the given locked object. This constructor is supposed to be used for subclassing * only. In general, it is suggested to use {@link LockingVisitors#stampedLockVisitor(Object)} instead. * * @param object The locked (hidden) object. The caller is supposed to drop all references to the locked object. + * @param readWriteLock the lock to use. */ - public StampedLockVisitor(final O object) { - super(object); - } - - /** - * Provides read (shared, non-exclusive) access to the locked (hidden) object. More precisely, what the method - * will do (in the given order): - *
        - *
      1. Obtain a read (shared) lock on the locked (hidden) object. The current thread may block, until such a - * lock is granted.
      2. - *
      3. Invokes the given {@link FailableConsumer consumer}, passing the locked object as the parameter.
      4. - *
      5. Release the lock, as soon as the consumers invocation is done. If the invocation results in an error, the - * lock will be released anyways.
      6. - *
      - * - * @param consumer The consumer, which is being invoked to use the hidden object, which will be passed as the - * consumers parameter. - * @see #acceptWriteLocked(FailableConsumer) - * @see #applyReadLocked(FailableFunction) - */ - @Override - public void acceptReadLocked(final FailableConsumer consumer) { - lockAcceptUnlock(() -> stampedLock.readLock(), consumer); - } - - /** - * Provides write (exclusive) access to the locked (hidden) object. More precisely, what the method will do (in - * the given order): - *
        - *
      1. Obtain a write (shared) lock on the locked (hidden) object. The current thread may block, until such a - * lock is granted.
      2. - *
      3. Invokes the given {@link FailableConsumer consumer}, passing the locked object as the parameter.
      4. - *
      5. Release the lock, as soon as the consumers invocation is done. If the invocation results in an error, the - * lock will be released anyways.
      6. - *
      - * - * @param consumer The consumer, which is being invoked to use the hidden object, which will be passed as the - * consumers parameter. - * @see #acceptReadLocked(FailableConsumer) - * @see #applyWriteLocked(FailableFunction) - */ - @Override - public void acceptWriteLocked(final FailableConsumer consumer) { - lockAcceptUnlock(() -> stampedLock.writeLock(), consumer); - } - - /** - * Provides read (shared, non-exclusive) access to the locked (hidden) object for the purpose of computing a - * result object. More precisely, what the method will do (in the given order): - *
        - *
      1. Obtain a read (shared) lock on the locked (hidden) object. The current thread may block, until such a - * lock is granted.
      2. - *
      3. Invokes the given {@link FailableFunction function}, passing the locked object as the parameter, - * receiving the functions result.
      4. - *
      5. Release the lock, as soon as the consumers invocation is done. If the invocation results in an error, the - * lock will be released anyways.
      6. - *
      7. Return the result object, that has been received from the functions invocation.
      8. - *
      - * - * Example: Suggest, that the hidden object is a list, and we wish to know the current size of the - * list. This might be achieved with the following: - * - *
      -         * private Lock<List<Object>> listLock;
      -         *
      -         * public int getCurrentListSize() {
      -         *     final Integer sizeInteger = listLock.applyReadLocked((list) -> Integer.valueOf(list.size));
      -         *     return sizeInteger.intValue();
      -         * }
      -         * 
      - * - * @param The result type (both the functions, and this method's.) - * @param function The function, which is being invoked to compute the result. The function will receive the - * hidden object. - * @return The result object, which has been returned by the functions invocation. - * @throws IllegalStateException The result object would be, in fact, the hidden object. This would extend - * access to the hidden object beyond this methods lifetime and will therefore be prevented. - * @see #acceptReadLocked(FailableConsumer) - * @see #applyWriteLocked(FailableFunction) - */ - @Override - public T applyReadLocked(final FailableFunction function) { - return lockApplyUnlock(() -> stampedLock.readLock(), function); - } - - /** - * Provides write (exclusive) access to the locked (hidden) object for the purpose of computing a result object. - * More precisely, what the method will do (in the given order): - *
        - *
      1. Obtain a read (shared) lock on the locked (hidden) object. The current thread may block, until such a - * lock is granted.
      2. - *
      3. Invokes the given {@link FailableFunction function}, passing the locked object as the parameter, - * receiving the functions result.
      4. - *
      5. Release the lock, as soon as the consumers invocation is done. If the invocation results in an error, the - * lock will be released anyways.
      6. - *
      7. Return the result object, that has been received from the functions invocation.
      8. - *
      - * - * @param The result type (both the functions, and this method's.) - * @param function The function, which is being invoked to compute the result. The function will receive the - * hidden object. - * @return The result object, which has been returned by the functions invocation. - * @throws IllegalStateException The result object would be, in fact, the hidden object. This would extend - * access to the hidden object beyond this methods lifetime and will therefore be prevented. - * @see #acceptReadLocked(FailableConsumer) - * @see #applyWriteLocked(FailableFunction) - */ - @Override - public T applyWriteLocked(final FailableFunction function) { - return lockApplyUnlock(() -> stampedLock.writeLock(), function); + protected ReadWriteLockVisitor(final O object, final ReadWriteLock readWriteLock) { + super(object, readWriteLock, readWriteLock::readLock, readWriteLock::writeLock); } + } - /** - * This method provides the actual implementation for {@link #acceptReadLocked(FailableConsumer)}, and - * {@link #acceptWriteLocked(FailableConsumer)}. - * - * @param stampSupplier A supplier for the lock. (This provides, in fact, a long, because a {@link StampedLock} - * is used internally.) - * @param consumer The consumer, which is to be given access to the locked (hidden) object, which will be passed - * as a parameter. - * @see #acceptReadLocked(FailableConsumer) - * @see #acceptWriteLocked(FailableConsumer) - * @see #lockApplyUnlock(LongSupplier, FailableFunction) - */ - private void lockAcceptUnlock(final LongSupplier stampSupplier, final FailableConsumer consumer) { - final long stamp = stampSupplier.getAsLong(); - try { - consumer.accept(object); - } catch (Throwable t) { - throw Failable.rethrow(t); - } finally { - stampedLock.unlock(stamp); - } - } + /** + * This class implements a wrapper for a locked (hidden) object, and provides the means to access it. The basic + * idea, is that the user code forsakes all references to the locked object, using only the wrapper object, and the + * accessor methods {@link #acceptReadLocked(FailableConsumer)}, {@link #acceptWriteLocked(FailableConsumer)}, + * {@link #applyReadLocked(FailableFunction)}, and {@link #applyWriteLocked(FailableFunction)}. By doing so, the + * necessary protections are guaranteed. + * + * @param The locked (hidden) objects type. + */ + public static class StampedLockVisitor extends LockVisitor { /** - * This method provides the actual implementation for {@link #applyReadLocked(FailableFunction)}, and - * {@link #applyWriteLocked(FailableFunction)}. + * Creates a new instance with the given locked object. This constructor is supposed to be used for subclassing + * only. In general, it is suggested to use {@link LockingVisitors#stampedLockVisitor(Object)} instead. * - * @param The result type (both the functions, and this method's.) - * @param stampSupplier A supplier for the lock. (This provides, in fact, a long, because a {@link StampedLock} - * is used internally.) - * @param function The function, which is being invoked to compute the result object. This function will receive - * the locked (hidden) object as a parameter. - * @return The result object, which has been returned by the functions invocation. - * @throws IllegalStateException The result object would be, in fact, the hidden object. This would extend - * access to the hidden object beyond this methods lifetime and will therefore be prevented. - * @see #applyReadLocked(FailableFunction) - * @see #applyWriteLocked(FailableFunction) - * @see #lockAcceptUnlock(LongSupplier, FailableConsumer) + * @param object The locked (hidden) object. The caller is supposed to drop all references to the locked object. + * @param stampedLock the lock to use. */ - private T lockApplyUnlock(final LongSupplier stampSupplier, final FailableFunction function) { - final long stamp = stampSupplier.getAsLong(); - try { - return function.apply(object); - } catch (Throwable t) { - throw Failable.rethrow(t); - } finally { - stampedLock.unlock(stamp); - } + protected StampedLockVisitor(final O object, StampedLock stampedLock) { + super(object, stampedLock, stampedLock::asReadLock, stampedLock::asWriteLock); } } /** - * Creates a new instance of {@link StampedLockVisitor} with the given (hidden) object. + * Creates a new instance of {@link ReadWriteLockVisitor} with the given (hidden) object. * * @param The locked objects type. * @param object The locked (hidden) object. * @return The created instance, a {@link StampedLockVisitor lock} for the given object. */ - public static StampedLockVisitor stampedLockVisitor(final O object) { - return new LockingVisitors.StampedLockVisitor<>(object); + public static ReadWriteLockVisitor reentrantReadWriteLockVisitor(final O object) { + return new LockingVisitors.ReadWriteLockVisitor<>(object, new ReentrantReadWriteLock()); } /** - * Creates a new instance of {@link ReadWriteLockVisitor} with the given (hidden) object. + * Creates a new instance of {@link StampedLockVisitor} with the given (hidden) object. * * @param The locked objects type. * @param object The locked (hidden) object. * @return The created instance, a {@link StampedLockVisitor lock} for the given object. */ - public static ReadWriteLockVisitor reentrantReadWriteLockVisitor(final O object) { - return new LockingVisitors.ReadWriteLockVisitor<>(object, new ReentrantReadWriteLock()); + public static StampedLockVisitor stampedLockVisitor(final O object) { + return new LockingVisitors.StampedLockVisitor<>(object, new StampedLock()); } } diff --git a/src/test/java/org/apache/commons/lang3/concurrent/locks/LockingVisitorsTest.java b/src/test/java/org/apache/commons/lang3/concurrent/locks/LockingVisitorsTest.java index bd3a7ffbf0b..df3982ac725 100644 --- a/src/test/java/org/apache/commons/lang3/concurrent/locks/LockingVisitorsTest.java +++ b/src/test/java/org/apache/commons/lang3/concurrent/locks/LockingVisitorsTest.java @@ -22,7 +22,7 @@ import java.util.function.LongConsumer; -import org.apache.commons.lang3.concurrent.locks.LockingVisitors.AbstractLockVisitor; +import org.apache.commons.lang3.concurrent.locks.LockingVisitors.LockVisitor; import org.apache.commons.lang3.concurrent.locks.LockingVisitors.StampedLockVisitor; import org.apache.commons.lang3.function.FailableConsumer; import org.junit.jupiter.api.Test; @@ -91,7 +91,7 @@ public void testResultValidation() { } private void runTest(final long delayMillis, final boolean exclusiveLock, final LongConsumer runTimeCheck, - boolean[] booleanValues, AbstractLockVisitor visitor) throws InterruptedException { + boolean[] booleanValues, LockVisitor visitor) throws InterruptedException { final boolean[] runningValues = new boolean[10]; final long startTime = System.currentTimeMillis(); From 3e86896c13aa51480fbde2a15b2beada9b6f0008 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sat, 11 Jul 2020 16:54:07 -0400 Subject: [PATCH 0270/3230] Format. --- .../apache/commons/lang3/concurrent/locks/LockingVisitors.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/org/apache/commons/lang3/concurrent/locks/LockingVisitors.java b/src/main/java/org/apache/commons/lang3/concurrent/locks/LockingVisitors.java index 41164c006eb..4663e137442 100644 --- a/src/main/java/org/apache/commons/lang3/concurrent/locks/LockingVisitors.java +++ b/src/main/java/org/apache/commons/lang3/concurrent/locks/LockingVisitors.java @@ -87,6 +87,7 @@ public static class LockVisitor { private final O object; private final Supplier readLockSupplier; private final Supplier writeLockSupplier; + protected LockVisitor(final O object, L lock, Supplier readLockSupplier, Supplier writeLockSupplier) { super(); this.object = Objects.requireNonNull(object, "object"); From 5283344927583f0894b79ae93515fd27ec5f9180 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sat, 11 Jul 2020 17:16:31 -0400 Subject: [PATCH 0271/3230] Added missing Javadoc and tweaked another Javadoc. --- .../concurrent/locks/LockingVisitors.java | 27 +++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/concurrent/locks/LockingVisitors.java b/src/main/java/org/apache/commons/lang3/concurrent/locks/LockingVisitors.java index 4663e137442..62868736c17 100644 --- a/src/main/java/org/apache/commons/lang3/concurrent/locks/LockingVisitors.java +++ b/src/main/java/org/apache/commons/lang3/concurrent/locks/LockingVisitors.java @@ -82,12 +82,35 @@ public class LockingVisitors { */ public static class LockVisitor { + /** + * The lock object, untyped, since, for example {@link StampedLock} does not implement a locking interface in + * Java 8. + */ private final L lock; - + + /** + * The guarded object. + */ private final O object; + + /** + * Supplies the read lock, usually from the lock object. + */ private final Supplier readLockSupplier; + + /** + * Supplies the write lock, usually from the lock object. + */ private final Supplier writeLockSupplier; + /** + * Constructs an instance. + * + * @param object The object to guard. + * @param lock The locking object. + * @param readLockSupplier Supplies the read lock, usually from the lock object. + * @param writeLockSupplier Supplies the write lock, usually from the lock object. + */ protected LockVisitor(final O object, L lock, Supplier readLockSupplier, Supplier writeLockSupplier) { super(); this.object = Objects.requireNonNull(object, "object"); @@ -210,7 +233,7 @@ public L getLock() { } /** - * Gets the object. + * Gets the guarded object. * * @return the object. */ From 92d6be66ff13ff452a06f8e2b7d4cc4b056e74dd Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sat, 11 Jul 2020 17:21:25 -0400 Subject: [PATCH 0272/3230] Whitespace and lambda clean ups. --- .../commons/lang3/concurrent/locks/LockingVisitors.java | 4 ++-- .../commons/lang3/concurrent/locks/LockingVisitorsTest.java | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/concurrent/locks/LockingVisitors.java b/src/main/java/org/apache/commons/lang3/concurrent/locks/LockingVisitors.java index 62868736c17..490447232ed 100644 --- a/src/main/java/org/apache/commons/lang3/concurrent/locks/LockingVisitors.java +++ b/src/main/java/org/apache/commons/lang3/concurrent/locks/LockingVisitors.java @@ -87,12 +87,12 @@ public static class LockVisitor { * Java 8. */ private final L lock; - + /** * The guarded object. */ private final O object; - + /** * Supplies the read lock, usually from the lock object. */ diff --git a/src/test/java/org/apache/commons/lang3/concurrent/locks/LockingVisitorsTest.java b/src/test/java/org/apache/commons/lang3/concurrent/locks/LockingVisitorsTest.java index df3982ac725..aba1d20bbc7 100644 --- a/src/test/java/org/apache/commons/lang3/concurrent/locks/LockingVisitorsTest.java +++ b/src/test/java/org/apache/commons/lang3/concurrent/locks/LockingVisitorsTest.java @@ -80,11 +80,11 @@ public void testReentrantReadWriteLockExclusive() throws Exception { public void testResultValidation() { final Object hidden = new Object(); final StampedLockVisitor lock = LockingVisitors.stampedLockVisitor(hidden); - final Object o1 = lock.applyReadLocked((h) -> { + final Object o1 = lock.applyReadLocked(h -> { return new Object(); }); assertNotNull(o1); assertNotSame(hidden, o1); - final Object o2 = lock.applyWriteLocked((h) -> { + final Object o2 = lock.applyWriteLocked(h -> { return new Object(); }); assertNotNull(o2); assertNotSame(hidden, o2); From 669f6833e3356f210dd463c56d2f6544bda7439b Mon Sep 17 00:00:00 2001 From: Rob Tompkins Date: Sat, 11 Jul 2020 17:24:29 -0400 Subject: [PATCH 0273/3230] (docs) formatting nit --- .../apache/commons/lang3/concurrent/locks/LockingVisitors.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/apache/commons/lang3/concurrent/locks/LockingVisitors.java b/src/main/java/org/apache/commons/lang3/concurrent/locks/LockingVisitors.java index 490447232ed..c3dce37ea3c 100644 --- a/src/main/java/org/apache/commons/lang3/concurrent/locks/LockingVisitors.java +++ b/src/main/java/org/apache/commons/lang3/concurrent/locks/LockingVisitors.java @@ -32,7 +32,7 @@ * objects are an alternative to synchronization. * * Locking is preferable, if there is a distinction between read access (multiple threads may have read access - * concurrently), and write access (only one thread may have write access at any given time. In comparison, + * concurrently), and write access (only one thread may have write access at any given time). In comparison, * synchronization doesn't support read access, because synchronized access is exclusive. * * Using this class is fairly straightforward: From 19f5632919d500f56234674846ca05918f91c778 Mon Sep 17 00:00:00 2001 From: Rob Tompkins Date: Sun, 12 Jul 2020 08:14:24 -0400 Subject: [PATCH 0274/3230] (docs) Add citations to LockingVisitors javadoc --- .../lang3/concurrent/locks/LockingVisitors.java | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/concurrent/locks/LockingVisitors.java b/src/main/java/org/apache/commons/lang3/concurrent/locks/LockingVisitors.java index c3dce37ea3c..1df6152c302 100644 --- a/src/main/java/org/apache/commons/lang3/concurrent/locks/LockingVisitors.java +++ b/src/main/java/org/apache/commons/lang3/concurrent/locks/LockingVisitors.java @@ -28,17 +28,23 @@ import org.apache.commons.lang3.function.FailableFunction; /** + *

      * Combines the monitor and visitor pattern to work with {@link java.util.concurrent.locks.Lock locked objects}. Locked - * objects are an alternative to synchronization. - * + * objects are an alternative to synchronization. This, on Wikipedia, is known as the Visitor pattern + * (https://en.wikipedia.org/wiki/Visitor_pattern), and from the "Gang of Four" "Design Patterns" book's Visitor pattern + * [Gamma, E., Helm, R., & Johnson, R. (1998). Visitor. In Design patterns elements of reusable object oriented software (pp. 331-344). Reading: Addison Wesley.]. + *

      + *

      * Locking is preferable, if there is a distinction between read access (multiple threads may have read access * concurrently), and write access (only one thread may have write access at any given time). In comparison, * synchronization doesn't support read access, because synchronized access is exclusive. - * + *

      + *

      * Using this class is fairly straightforward: + *

      *
        *
      1. While still in single thread mode, create an instance of {@link LockingVisitors.StampedLockVisitor} by calling - * {@link #stampedLockVisitor(Object)}, passing the object, which needs to be locked. Discard all references to the + * {@link #stampedLockVisitor(Object)}, passing the object which needs to be locked. Discard all references to the * locked object. Instead, use references to the lock.
      2. *
      3. If you want to access the locked object, create a {@link FailableConsumer}. The consumer will receive the locked * object as a parameter. For convenience, the consumer may be implemented as a Lambda. Then invoke @@ -49,8 +55,9 @@ * {@link LockingVisitors.StampedLockVisitor#applyReadLocked(FailableFunction)}, or * {@link LockingVisitors.StampedLockVisitor#applyWriteLocked(FailableFunction)}.
      4. *
      - * + *

      * Example: A thread safe logger class. + *

      * *
        *   public class SimpleLogger {
      
      From 3d8408776ea4d281fc68680c4d87483a4ed66883 Mon Sep 17 00:00:00 2001
      From: Rob Tompkins 
      Date: Sun, 12 Jul 2020 08:43:32 -0400
      Subject: [PATCH 0275/3230] (docs) minor nits and whitespace addions for
       readability
      
      ---
       .../lang3/concurrent/locks/LockingVisitors.java  | 16 ++++++++++++----
       1 file changed, 12 insertions(+), 4 deletions(-)
      
      diff --git a/src/main/java/org/apache/commons/lang3/concurrent/locks/LockingVisitors.java b/src/main/java/org/apache/commons/lang3/concurrent/locks/LockingVisitors.java
      index 1df6152c302..98d3218ea66 100644
      --- a/src/main/java/org/apache/commons/lang3/concurrent/locks/LockingVisitors.java
      +++ b/src/main/java/org/apache/commons/lang3/concurrent/locks/LockingVisitors.java
      @@ -127,8 +127,10 @@ protected LockVisitor(final O object, L lock, Supplier readLockSupplier, S
               }
       
               /**
      +         * 

      * Provides read (shared, non-exclusive) access to the locked (hidden) object. More precisely, what the method * will do (in the given order): + *

      *
        *
      1. Obtain a read (shared) lock on the locked (hidden) object. The current thread may block, until such a * lock is granted.
      2. @@ -147,8 +149,10 @@ public void acceptReadLocked(FailableConsumer consumer) { } /** + *

        * Provides write (exclusive) access to the locked (hidden) object. More precisely, what the method will do (in * the given order): + *

        *
          *
        1. Obtain a write (shared) lock on the locked (hidden) object. The current thread may block, until such a * lock is granted.
        2. @@ -167,8 +171,10 @@ public void acceptWriteLocked(final FailableConsumer consumer) { } /** + *

          * Provides read (shared, non-exclusive) access to the locked (hidden) object for the purpose of computing a * result object. More precisely, what the method will do (in the given order): + *

          *
            *
          1. Obtain a read (shared) lock on the locked (hidden) object. The current thread may block, until such a * lock is granted.
          2. @@ -178,10 +184,10 @@ public void acceptWriteLocked(final FailableConsumer consumer) { * lock will be released anyways. *
          3. Return the result object, that has been received from the functions invocation.
          4. *
          - * - * Example: Suggest, that the hidden object is a list, and we wish to know the current size of the + *

          + * Example: Consider that the hidden object is a list, and we wish to know the current size of the * list. This might be achieved with the following: - * + *

          *
                    * private Lock<List<Object>> listLock;
                    *
          @@ -205,8 +211,10 @@ public  T applyReadLocked(FailableFunction function) {
                   }
           
                   /**
          +         * 

          * Provides write (exclusive) access to the locked (hidden) object for the purpose of computing a result object. * More precisely, what the method will do (in the given order): + *

          *
            *
          1. Obtain a read (shared) lock on the locked (hidden) object. The current thread may block, until such a * lock is granted.
          2. @@ -325,7 +333,7 @@ protected ReadWriteLockVisitor(final O object, final ReadWriteLock readWriteLock /** * This class implements a wrapper for a locked (hidden) object, and provides the means to access it. The basic - * idea, is that the user code forsakes all references to the locked object, using only the wrapper object, and the + * idea is that the user code forsakes all references to the locked object, using only the wrapper object, and the * accessor methods {@link #acceptReadLocked(FailableConsumer)}, {@link #acceptWriteLocked(FailableConsumer)}, * {@link #applyReadLocked(FailableFunction)}, and {@link #applyWriteLocked(FailableFunction)}. By doing so, the * necessary protections are guaranteed. From fe95edd45ffe8d4ffcec17cd8d7741687374c17f Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sun, 12 Jul 2020 08:59:56 -0400 Subject: [PATCH 0276/3230] Prepare for 3.11-RC2. --- src/changes/changes.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 2d616613e5e..74b49eb384d 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -45,7 +45,7 @@ The type attribute can be add,update,fix,remove. - + Refine test output for FastDateParserTest CharSequenceUtils.lastIndexOf : remake it remove encoding and docEncoding and use inherited values from commons-parent From f62f0f59a33d2c42bd4236ea7122735de30d91fc Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sun, 12 Jul 2020 09:19:13 -0400 Subject: [PATCH 0277/3230] Prepare for 3.11-RC2. --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index bf5656604a8..d9760d8c5cb 100644 --- a/pom.xml +++ b/pom.xml @@ -625,7 +625,7 @@ 3.10 - RC1 + RC2 true scm:svn:https://dist.apache.org/repos/dist/dev/commons/lang Gary Gregory From bc4b945bde0a54571126296146dcbbc175c9f63b Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Thu, 16 Jul 2020 09:07:00 -0400 Subject: [PATCH 0278/3230] Prepare for 3.11 site. --- src/site/xdoc/index.xml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/site/xdoc/index.xml b/src/site/xdoc/index.xml index 7f7667a28cf..148195d9811 100644 --- a/src/site/xdoc/index.xml +++ b/src/site/xdoc/index.xml @@ -61,10 +61,10 @@ The git repository can be
            -

            The latest stable release of Lang is 3.10. You may:

            +

            The latest stable release of Lang is 3.11. You may:

            @@ -74,7 +74,7 @@ Alternatively you can pull it from the central Maven repositories: <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> - <version>3.10</version> + <version>3.11</version> </dependency>

          From c56be9c3ddbcaefac9dcc720238462cfc529fc06 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Thu, 16 Jul 2020 19:23:10 -0400 Subject: [PATCH 0279/3230] Format tweak. --- src/main/java/org/apache/commons/lang3/ClassUtils.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/main/java/org/apache/commons/lang3/ClassUtils.java b/src/main/java/org/apache/commons/lang3/ClassUtils.java index a6d1d1ddbd8..11c71bd7577 100644 --- a/src/main/java/org/apache/commons/lang3/ClassUtils.java +++ b/src/main/java/org/apache/commons/lang3/ClassUtils.java @@ -82,6 +82,7 @@ public enum Interfaces { * Maps names of primitives to their corresponding primitive {@code Class}es. */ private static final Map> namePrimitiveMap = new HashMap<>(); + static { namePrimitiveMap.put("boolean", Boolean.TYPE); namePrimitiveMap.put("byte", Byte.TYPE); @@ -98,6 +99,7 @@ public enum Interfaces { * Maps primitive {@code Class}es to their corresponding wrapper {@code Class}. */ private static final Map, Class> primitiveWrapperMap = new HashMap<>(); + static { primitiveWrapperMap.put(Boolean.TYPE, Boolean.class); primitiveWrapperMap.put(Byte.TYPE, Byte.class); @@ -114,6 +116,7 @@ public enum Interfaces { * Maps wrapper {@code Class}es to their corresponding primitive types. */ private static final Map, Class> wrapperPrimitiveMap = new HashMap<>(); + static { for (final Map.Entry, Class> entry : primitiveWrapperMap.entrySet()) { final Class primitiveClass = entry.getKey(); @@ -133,6 +136,7 @@ public enum Interfaces { * Maps an abbreviation used in array class names to corresponding primitive class name. */ private static final Map reverseAbbreviationMap; + // Feed abbreviation maps static { final Map m = new HashMap<>(); From 6d9102ab92fe95c837b20e50534352145f680d55 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Fri, 17 Jul 2020 08:51:55 -0400 Subject: [PATCH 0280/3230] Revert "Format tweak." This reverts commit c56be9c3ddbcaefac9dcc720238462cfc529fc06. --- src/main/java/org/apache/commons/lang3/ClassUtils.java | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/ClassUtils.java b/src/main/java/org/apache/commons/lang3/ClassUtils.java index 11c71bd7577..a6d1d1ddbd8 100644 --- a/src/main/java/org/apache/commons/lang3/ClassUtils.java +++ b/src/main/java/org/apache/commons/lang3/ClassUtils.java @@ -82,7 +82,6 @@ public enum Interfaces { * Maps names of primitives to their corresponding primitive {@code Class}es. */ private static final Map> namePrimitiveMap = new HashMap<>(); - static { namePrimitiveMap.put("boolean", Boolean.TYPE); namePrimitiveMap.put("byte", Byte.TYPE); @@ -99,7 +98,6 @@ public enum Interfaces { * Maps primitive {@code Class}es to their corresponding wrapper {@code Class}. */ private static final Map, Class> primitiveWrapperMap = new HashMap<>(); - static { primitiveWrapperMap.put(Boolean.TYPE, Boolean.class); primitiveWrapperMap.put(Byte.TYPE, Byte.class); @@ -116,7 +114,6 @@ public enum Interfaces { * Maps wrapper {@code Class}es to their corresponding primitive types. */ private static final Map, Class> wrapperPrimitiveMap = new HashMap<>(); - static { for (final Map.Entry, Class> entry : primitiveWrapperMap.entrySet()) { final Class primitiveClass = entry.getKey(); @@ -136,7 +133,6 @@ public enum Interfaces { * Maps an abbreviation used in array class names to corresponding primitive class name. */ private static final Map reverseAbbreviationMap; - // Feed abbreviation maps static { final Map m = new HashMap<>(); From f17274ef5b147a38b766c861d648fd4d563f9355 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Fri, 17 Jul 2020 09:43:05 -0400 Subject: [PATCH 0281/3230] Bump to next development version --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index d9760d8c5cb..965781ad756 100644 --- a/pom.xml +++ b/pom.xml @@ -26,7 +26,7 @@ 4.0.0 commons-lang3 - 3.11 + 3.12-SNAPSHOT Apache Commons Lang 2001 From 031c1d0b8c5c183cda8de2cf20cbd3a2ae662dc7 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sat, 18 Jul 2020 08:37:57 -0400 Subject: [PATCH 0282/3230] Fix download link. --- src/changes/release-notes.vm | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/changes/release-notes.vm b/src/changes/release-notes.vm index 42349082977..9e311eb7dd3 100644 --- a/src/changes/release-notes.vm +++ b/src/changes/release-notes.vm @@ -138,7 +138,7 @@ patches, or suggestions for improvement, see the Apache ${project.name} website: ${project.url} -Download page: ${project.url}download_csv.cgi +Download page: ${project.url}download_lang.cgi Have fun! -Apache Commons Team From e80339626333396a216d7e81a7d7ab6a8ea2de6f Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sat, 18 Jul 2020 17:31:56 -0400 Subject: [PATCH 0283/3230] Add slot for next release. --- src/changes/changes.xml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 74b49eb384d..e83bbacdb4d 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -45,6 +45,9 @@ The type attribute can be add,update,fix,remove. + + + Refine test output for FastDateParserTest CharSequenceUtils.lastIndexOf : remake it From 61c575afacfda092d433ef2211e704e7a7ebdeb7 Mon Sep 17 00:00:00 2001 From: B Sharma <94sharmabhawna@gmail.com> Date: Mon, 20 Jul 2020 10:41:09 +0530 Subject: [PATCH 0284/3230] Remove redudant argument from substring call --- .../commons/lang3/math/NumberUtils.java | 21 ++++++++++--------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/math/NumberUtils.java b/src/main/java/org/apache/commons/lang3/math/NumberUtils.java index c9ea0695649..9fcf0cf85ab 100644 --- a/src/main/java/org/apache/commons/lang3/math/NumberUtils.java +++ b/src/main/java/org/apache/commons/lang3/math/NumberUtils.java @@ -656,6 +656,7 @@ public static Number createNumber(final String str) { } // Need to deal with all possible hex prefixes here final String[] hex_prefixes = {"0x", "0X", "-0x", "-0X", "#", "-#"}; + final int length = str.length(); int pfxLen = 0; for (final String pfx : hex_prefixes) { if (str.startsWith(pfx)) { @@ -665,7 +666,7 @@ public static Number createNumber(final String str) { } if (pfxLen > 0) { // we have a hex number char firstSigDigit = 0; // strip leading zeroes - for (int i = pfxLen; i < str.length(); i++) { + for (int i = pfxLen; i < length; i++) { firstSigDigit = str.charAt(i); if (firstSigDigit == '0') { // count leading zeroes pfxLen++; @@ -673,7 +674,7 @@ public static Number createNumber(final String str) { break; } } - final int hexDigits = str.length() - pfxLen; + final int hexDigits = length - pfxLen; if (hexDigits > 16 || hexDigits == 16 && firstSigDigit > '7') { // too many for Long return createBigInteger(str); } @@ -682,7 +683,7 @@ public static Number createNumber(final String str) { } return createInteger(str); } - final char lastChar = str.charAt(str.length() - 1); + final char lastChar = str.charAt(length - 1); String mant; String dec; String exp; @@ -693,7 +694,7 @@ public static Number createNumber(final String str) { if (decPos > -1) { // there is a decimal point if (expPos > -1) { // there is an exponent - if (expPos < decPos || expPos > str.length()) { // prevents double exponent causing IOOBE + if (expPos < decPos || expPos > length) { // prevents double exponent causing IOOBE throw new NumberFormatException(str + " is not a valid number."); } dec = str.substring(decPos + 1, expPos); @@ -703,7 +704,7 @@ public static Number createNumber(final String str) { mant = getMantissa(str, decPos); } else { if (expPos > -1) { - if (expPos > str.length()) { // prevents double exponent causing IOOBE + if (expPos > length) { // prevents double exponent causing IOOBE throw new NumberFormatException(str + " is not a valid number."); } mant = getMantissa(str, expPos); @@ -713,13 +714,13 @@ public static Number createNumber(final String str) { dec = null; } if (!Character.isDigit(lastChar) && lastChar != '.') { - if (expPos > -1 && expPos < str.length() - 1) { - exp = str.substring(expPos + 1, str.length() - 1); + if (expPos > -1 && expPos < length - 1) { + exp = str.substring(expPos + 1, length - 1); } else { exp = null; } //Requesting a specific type.. - final String numeric = str.substring(0, str.length() - 1); + final String numeric = str.substring(0, length - 1); final boolean allZeros = isAllZeros(mant) && isAllZeros(exp); switch (lastChar) { case 'l' : @@ -773,8 +774,8 @@ public static Number createNumber(final String str) { } //User doesn't have a preference on the return type, so let's start //small and go from there... - if (expPos > -1 && expPos < str.length() - 1) { - exp = str.substring(expPos + 1, str.length()); + if (expPos > -1 && expPos < length - 1) { + exp = str.substring(expPos + 1); } else { exp = null; } From 53529d8f498f892d2b94803b91e1d4fd2b885b38 Mon Sep 17 00:00:00 2001 From: "Bruno P. Kinoshita" Date: Mon, 20 Jul 2020 21:19:44 +1200 Subject: [PATCH 0285/3230] [LANG-1591]: add changes.xml entry --- src/changes/changes.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index e83bbacdb4d..dbb1c6418d8 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -46,7 +46,7 @@ The type attribute can be add,update,fix,remove. - + Remove redudant argument from substring call Refine test output for FastDateParserTest From 1bf70c5c9637305d210795f3d5866decf340f68e Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Mon, 20 Jul 2020 11:15:44 -0400 Subject: [PATCH 0286/3230] Use Maven generated changes-report for the release history. --- .../resources/lang2-lang3-clirr-report.html | 2 +- src/site/site.xml | 1 - src/site/xdoc/index.xml | 4 +- src/site/xdoc/release-history.xml | 131 ------------------ 4 files changed, 3 insertions(+), 135 deletions(-) delete mode 100644 src/site/xdoc/release-history.xml diff --git a/src/site/resources/lang2-lang3-clirr-report.html b/src/site/resources/lang2-lang3-clirr-report.html index e0bb65da44f..e2aaf12b531 100644 --- a/src/site/resources/lang2-lang3-clirr-report.html +++ b/src/site/resources/lang2-lang3-clirr-report.html @@ -87,7 +87,7 @@
          Lang
          Users guide
        3. - Release History + Release History
        4. Javadoc (3.0 release) diff --git a/src/site/site.xml b/src/site/site.xml index 46d8a3d61ea..b51b788f7fa 100644 --- a/src/site/site.xml +++ b/src/site/site.xml @@ -27,7 +27,6 @@ - diff --git a/src/site/xdoc/index.xml b/src/site/xdoc/index.xml index 148195d9811..4461670ba5e 100644 --- a/src/site/xdoc/index.xml +++ b/src/site/xdoc/index.xml @@ -52,7 +52,7 @@ The Javadoc API documents are available online:

          The git repository can be @@ -80,7 +80,7 @@ Alternatively you can pull it from the central Maven repositories:

          -For information on previous releases see the Release History, and to download previous releases see the Commons Lang Archive. +For information on previous releases see the Release History, and to download previous releases see the Commons Lang Archive.

          diff --git a/src/site/xdoc/release-history.xml b/src/site/xdoc/release-history.xml deleted file mode 100644 index 0fd2de16041..00000000000 --- a/src/site/xdoc/release-history.xml +++ /dev/null @@ -1,131 +0,0 @@ - - - - - Release History - Commons Documentation Team - - - -
          - - This page contains information about all Apache Commons Lang releases. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
          VersionRelease dateRequired Java VersionJavadocRelease notes
          3.102020-03-228api-3.10release notes for 3.10
          3.92019-04-098api-3.9release notes for 3.9
          3.8.12018-09-197api-3.8.1release notes for 3.8.1
          3.82018-08-157api-3.8release notes for 3.8
          3.72017-10-047api-3.7release notes for 3.7
          3.62016-04-177api-3.6release notes for 3.6
          3.52016-10-026api-3.5release notes for 3.5
          3.42014-04-066api-3.4release notes for 3.4
          3.3.22014-04-096api-3.3.2release notes for 3.3.2
          3.3.12014-03-186api-3.3.1release notes for 3.3.1
          3.32014-03-046api-3.3release notes for 3.3
          3.2.12014-01-056api-3.2.1release notes for 3.2.1
          3.22014-01-016api-3.2release notes for 3.2
          3.12011-11-145.0api-3.1release notes for 3.1
          3.0.12011-08-095.0api-3.0.1release notes for 3.0.1
          3.02011-07-185.0api-3.0release notes for 3.0
          -
          - - - - - - - - - - - - - - - - - - - - - - - - - - - -
          VersionRelease dateRequired Java VersionJavadocRelease notes
          2.62011-01-161.3api-2.6release notes for 2.6
          2.52010-02-231.3api-2.5release notes for 2.5
          2.42008-03-181.2api-2.4release notes for 2.4
          2.32007-02-131.1api-2.3release notes for 2.3
          2.22006-10-041.1api-2.2release notes for 2.2
          2.12006-06-131.1api-2.1release notes for 2.1
          2.02003-09-021.1api-2.0release notes for 2.0
          -
          - - - - - - - - - - - - -
          VersionRelease dateRequired Java VersionJavadocRelease notes
          1.0.12002-11-251.1api-1.0.1release notes for 1.0.1
          1.02002-10-041.1api-1.0release notes for 1.0
          -
          - -
          - - -
          From dfec50030ff74fe5324b0a743f4388c29f9f6f53 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Mon, 20 Jul 2020 11:34:45 -0400 Subject: [PATCH 0287/3230] Use Maven generated changes-report for the release history. --- .../resources/lang2-lang3-clirr-report.html | 2 +- src/site/site.xml | 2 +- src/site/xdoc/index.xml | 4 +- src/site/xdoc/release-history.xml | 131 ------------------ 4 files changed, 4 insertions(+), 135 deletions(-) delete mode 100644 src/site/xdoc/release-history.xml diff --git a/src/site/resources/lang2-lang3-clirr-report.html b/src/site/resources/lang2-lang3-clirr-report.html index e0bb65da44f..e2aaf12b531 100644 --- a/src/site/resources/lang2-lang3-clirr-report.html +++ b/src/site/resources/lang2-lang3-clirr-report.html @@ -87,7 +87,7 @@
          Lang
          Users guide
        5. - Release History + Release History
        6. Javadoc (3.0 release) diff --git a/src/site/site.xml b/src/site/site.xml index 46d8a3d61ea..4ac8d771601 100644 --- a/src/site/site.xml +++ b/src/site/site.xml @@ -27,7 +27,7 @@ - + diff --git a/src/site/xdoc/index.xml b/src/site/xdoc/index.xml index 148195d9811..4461670ba5e 100644 --- a/src/site/xdoc/index.xml +++ b/src/site/xdoc/index.xml @@ -52,7 +52,7 @@ The Javadoc API documents are available online:

          The git repository can be @@ -80,7 +80,7 @@ Alternatively you can pull it from the central Maven repositories:

          -For information on previous releases see the Release History, and to download previous releases see the Commons Lang Archive. +For information on previous releases see the Release History, and to download previous releases see the Commons Lang Archive.

          diff --git a/src/site/xdoc/release-history.xml b/src/site/xdoc/release-history.xml deleted file mode 100644 index 0fd2de16041..00000000000 --- a/src/site/xdoc/release-history.xml +++ /dev/null @@ -1,131 +0,0 @@ - - - - - Release History - Commons Documentation Team - - - -
          - - This page contains information about all Apache Commons Lang releases. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
          VersionRelease dateRequired Java VersionJavadocRelease notes
          3.102020-03-228api-3.10release notes for 3.10
          3.92019-04-098api-3.9release notes for 3.9
          3.8.12018-09-197api-3.8.1release notes for 3.8.1
          3.82018-08-157api-3.8release notes for 3.8
          3.72017-10-047api-3.7release notes for 3.7
          3.62016-04-177api-3.6release notes for 3.6
          3.52016-10-026api-3.5release notes for 3.5
          3.42014-04-066api-3.4release notes for 3.4
          3.3.22014-04-096api-3.3.2release notes for 3.3.2
          3.3.12014-03-186api-3.3.1release notes for 3.3.1
          3.32014-03-046api-3.3release notes for 3.3
          3.2.12014-01-056api-3.2.1release notes for 3.2.1
          3.22014-01-016api-3.2release notes for 3.2
          3.12011-11-145.0api-3.1release notes for 3.1
          3.0.12011-08-095.0api-3.0.1release notes for 3.0.1
          3.02011-07-185.0api-3.0release notes for 3.0
          -
          - - - - - - - - - - - - - - - - - - - - - - - - - - - -
          VersionRelease dateRequired Java VersionJavadocRelease notes
          2.62011-01-161.3api-2.6release notes for 2.6
          2.52010-02-231.3api-2.5release notes for 2.5
          2.42008-03-181.2api-2.4release notes for 2.4
          2.32007-02-131.1api-2.3release notes for 2.3
          2.22006-10-041.1api-2.2release notes for 2.2
          2.12006-06-131.1api-2.1release notes for 2.1
          2.02003-09-021.1api-2.0release notes for 2.0
          -
          - - - - - - - - - - - - -
          VersionRelease dateRequired Java VersionJavadocRelease notes
          1.0.12002-11-251.1api-1.0.1release notes for 1.0.1
          1.02002-10-041.1api-1.0release notes for 1.0
          -
          - -
          - - -
          From deaed63d51cc19b390fd6ae4b0f04efe73a6c201 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Mon, 20 Jul 2020 11:37:23 -0400 Subject: [PATCH 0288/3230] Update versions for 3.12. --- pom.xml | 4 ++-- src/site/xdoc/index.xml | 10 +++++----- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/pom.xml b/pom.xml index 965781ad756..5e599262b04 100644 --- a/pom.xml +++ b/pom.xml @@ -47,7 +47,7 @@ scm:git:http://gitbox.apache.org/repos/asf/commons-lang.git scm:git:https://gitbox.apache.org/repos/asf/commons-lang.git https://gitbox.apache.org/repos/asf?p=commons-lang.git - commons-lang-3.11 + commons-lang-3.12 @@ -587,7 +587,7 @@ lang3 org.apache.commons.lang3 - 3.11 + 3.12 (Java 8+) 2.6 diff --git a/src/site/xdoc/index.xml b/src/site/xdoc/index.xml index 4461670ba5e..c4c368520ce 100644 --- a/src/site/xdoc/index.xml +++ b/src/site/xdoc/index.xml @@ -50,7 +50,7 @@ and various project reports are provided. The Javadoc API documents are available online:

          @@ -61,10 +61,10 @@ The git repository can be
          -

          The latest stable release of Lang is 3.11. You may:

          +

          The latest stable release of Lang is 3.12. You may:

          @@ -74,7 +74,7 @@ Alternatively you can pull it from the central Maven repositories: <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> - <version>3.11</version> + <version>3.12</version> </dependency>

      From 2242b6f2ca69768aac954696e6dd67842b1ea4d6 Mon Sep 17 00:00:00 2001 From: Alex Herbert Date: Tue, 21 Jul 2020 08:20:23 +0100 Subject: [PATCH 0289/3230] Remove javadoc reference to private constructor --- .../java/org/apache/commons/lang3/CharRange.java | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/CharRange.java b/src/main/java/org/apache/commons/lang3/CharRange.java index 0504bedaa17..90977fb246e 100644 --- a/src/main/java/org/apache/commons/lang3/CharRange.java +++ b/src/main/java/org/apache/commons/lang3/CharRange.java @@ -81,7 +81,6 @@ private CharRange(char start, char end, final boolean negated) { * * @param ch only character in this range * @return the new CharRange object - * @see CharRange#CharRange(char, char, boolean) * @since 2.5 */ public static CharRange is(final char ch) { @@ -91,9 +90,11 @@ public static CharRange is(final char ch) { /** *

      Constructs a negated {@code CharRange} over a single character.

      * + *

      A negated range includes everything except that defined by the + * single character.

      + * * @param ch only character in this range * @return the new CharRange object - * @see CharRange#CharRange(char, char, boolean) * @since 2.5 */ public static CharRange isNot(final char ch) { @@ -103,10 +104,12 @@ public static CharRange isNot(final char ch) { /** *

      Constructs a {@code CharRange} over a set of characters.

      * + *

      If start and end are in the wrong order, they are reversed. + * Thus {@code a-e} is the same as {@code e-a}.

      + * * @param start first character, inclusive, in this range * @param end last character, inclusive, in this range * @return the new CharRange object - * @see CharRange#CharRange(char, char, boolean) * @since 2.5 */ public static CharRange isIn(final char start, final char end) { @@ -116,10 +119,15 @@ public static CharRange isIn(final char start, final char end) { /** *

      Constructs a negated {@code CharRange} over a set of characters.

      * + *

      A negated range includes everything except that defined by the + * start and end characters.

      + * + *

      If start and end are in the wrong order, they are reversed. + * Thus {@code a-e} is the same as {@code e-a}.

      + * * @param start first character, inclusive, in this range * @param end last character, inclusive, in this range * @return the new CharRange object - * @see CharRange#CharRange(char, char, boolean) * @since 2.5 */ public static CharRange isNotIn(final char start, final char end) { From 2957f33b6f63634b5acb9d04a4733d4581e9c7a3 Mon Sep 17 00:00:00 2001 From: Alex Herbert Date: Tue, 21 Jul 2020 08:21:55 +0100 Subject: [PATCH 0290/3230] Javadoc fix --- src/test/java/org/apache/commons/lang3/ObjectUtilsTest.java | 2 +- .../apache/commons/lang3/builder/JsonToStringStyleTest.java | 6 ++---- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/src/test/java/org/apache/commons/lang3/ObjectUtilsTest.java b/src/test/java/org/apache/commons/lang3/ObjectUtilsTest.java index aa235bbeb23..8f9797d0f7b 100644 --- a/src/test/java/org/apache/commons/lang3/ObjectUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/ObjectUtilsTest.java @@ -727,7 +727,7 @@ static final class NonComparableCharSequence implements CharSequence { /** * Create a new NonComparableCharSequence instance. * - * @param value + * @param value the CharSequence value */ NonComparableCharSequence(final String value) { super(); diff --git a/src/test/java/org/apache/commons/lang3/builder/JsonToStringStyleTest.java b/src/test/java/org/apache/commons/lang3/builder/JsonToStringStyleTest.java index b8d9f6e701d..4cf5136f768 100644 --- a/src/test/java/org/apache/commons/lang3/builder/JsonToStringStyleTest.java +++ b/src/test/java/org/apache/commons/lang3/builder/JsonToStringStyleTest.java @@ -599,8 +599,7 @@ public void testMapSkipNullKey() { } /** - * An object with nested object structures used to test {@link ToStringStyle.JsonToStringStyle}. - * + * An object with nested object structures used to test {@code ToStringStyle.JsonToStringStyle}. */ static class NestingPerson { /** @@ -684,8 +683,7 @@ public String toString() { } /** - * An object with a Map field used to test {@link ToStringStyle.JsonToStringStyle}. - * + * An object with a Map field used to test {@code ToStringStyle.JsonToStringStyle}. */ static class InnerMapObject { /** From 35495dc8d98e21eb7ff55ba3f175506276f94fe7 Mon Sep 17 00:00:00 2001 From: "Sean C. Sullivan" Date: Wed, 22 Jul 2020 07:00:59 -0700 Subject: [PATCH 0291/3230] enable Dependabot v2 --- .github/dependabot.yml | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 .github/dependabot.yml diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 00000000000..b76b8957033 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,10 @@ +version: 2 +updates: + - package-ecosystem: "maven" + directory: "/" + schedule: + interval: "daily" + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "daily" From b99969ca8ab6d0f86ae00a385fee16d70639a963 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Wed, 22 Jul 2020 10:10:07 -0400 Subject: [PATCH 0292/3230] Enable Dependabot #587. --- src/changes/changes.xml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index dbb1c6418d8..8c1ad6746b9 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -46,7 +46,8 @@ The type attribute can be add,update,fix,remove. - Remove redudant argument from substring call + Remove redundant argument from substring call. + Enable Dependabot #587. Refine test output for FastDateParserTest From a8c4c01366d10ccac8028df20f5c9599109b0341 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Wed, 22 Jul 2020 10:29:37 -0400 Subject: [PATCH 0293/3230] Add missing header. --- .github/dependabot.yml | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/.github/dependabot.yml b/.github/dependabot.yml index b76b8957033..5b4750958a4 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -1,3 +1,18 @@ +# 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. + version: 2 updates: - package-ecosystem: "maven" From d0e22083ca8b48043b4aeeab451c97461ac89867 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Wed, 22 Jul 2020 10:36:02 -0400 Subject: [PATCH 0294/3230] Drop Java 12 and 13 from GitHub builds. --- .github/workflows/maven.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml index 055919f1458..ffaa22ee05c 100644 --- a/.github/workflows/maven.yml +++ b/.github/workflows/maven.yml @@ -23,7 +23,7 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - java: [ 8, 11, 12, 13, 14 ] + java: [ 8, 11, 14 ] steps: - uses: actions/checkout@v1 From 88dbef45ae9d14a8139ee87e4cbc41b364b70e74 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Wed, 22 Jul 2020 10:36:44 -0400 Subject: [PATCH 0295/3230] Add early access builds to GitHub builds. --- .github/workflows/maven.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml index ffaa22ee05c..c723da0daf5 100644 --- a/.github/workflows/maven.yml +++ b/.github/workflows/maven.yml @@ -23,7 +23,7 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - java: [ 8, 11, 14 ] + java: [ 8, 11, 14, 15-ea, 16-ea ] steps: - uses: actions/checkout@v1 From eb3d1f5da5f80cf22447cc03ac3fa55c06fb77b3 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Wed, 22 Jul 2020 10:59:54 -0400 Subject: [PATCH 0296/3230] Allow Java early access builds to fail. --- .github/workflows/maven.yml | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml index c723da0daf5..585c5901243 100644 --- a/.github/workflows/maven.yml +++ b/.github/workflows/maven.yml @@ -21,9 +21,16 @@ jobs: build: runs-on: ubuntu-latest + continue-on-error: ${{ matrix.experimental }} strategy: matrix: java: [ 8, 11, 14, 15-ea, 16-ea ] + experimental: [false] + include: + - node: 15-ea + experimental: true + - node: 16-ea + experimental: true steps: - uses: actions/checkout@v1 From 4e9460413a01846265831129eae856cb75ba9edb Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Wed, 22 Jul 2020 11:14:21 -0400 Subject: [PATCH 0297/3230] Java 16-ea appears to not be supported by GitHub yet. --- .github/workflows/maven.yml | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml index 585c5901243..01eb5e5e0d2 100644 --- a/.github/workflows/maven.yml +++ b/.github/workflows/maven.yml @@ -24,13 +24,11 @@ jobs: continue-on-error: ${{ matrix.experimental }} strategy: matrix: - java: [ 8, 11, 14, 15-ea, 16-ea ] + java: [ 8, 11, 14, 15-ea ] experimental: [false] include: - node: 15-ea experimental: true - - node: 16-ea - experimental: true steps: - uses: actions/checkout@v1 From ba7505d9a91be02088e1309f172f3dc55823c9c0 Mon Sep 17 00:00:00 2001 From: Alex Herbert Date: Tue, 21 Jul 2020 08:45:03 +0100 Subject: [PATCH 0298/3230] LANG-1592: Correct implementation of RandomUtils.nextLong(long, long) The method has been changed to use exclusively the long datatype to generate the value. The implementation is taken from the Commons RNG project. --- src/changes/changes.xml | 1 + .../org/apache/commons/lang3/RandomUtils.java | 24 ++++++++++++++++-- .../apache/commons/lang3/RandomUtilsTest.java | 25 +++++++++++++++++++ 3 files changed, 48 insertions(+), 2 deletions(-) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 8c1ad6746b9..fa59134ca63 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -48,6 +48,7 @@ The type attribute can be add,update,fix,remove. Remove redundant argument from substring call. Enable Dependabot #587. + Correct implementation of RandomUtils.nextLong(long, long) Refine test output for FastDateParserTest diff --git a/src/main/java/org/apache/commons/lang3/RandomUtils.java b/src/main/java/org/apache/commons/lang3/RandomUtils.java index 571cece995a..b1c7f0fb147 100644 --- a/src/main/java/org/apache/commons/lang3/RandomUtils.java +++ b/src/main/java/org/apache/commons/lang3/RandomUtils.java @@ -145,7 +145,7 @@ public static long nextLong(final long startInclusive, final long endExclusive) return startInclusive; } - return (long) nextDouble(startInclusive, endExclusive); + return startInclusive + nextLong(endExclusive - startInclusive); } /** @@ -156,7 +156,27 @@ public static long nextLong(final long startInclusive, final long endExclusive) * @since 3.5 */ public static long nextLong() { - return nextLong(0, Long.MAX_VALUE); + return nextLong(Long.MAX_VALUE); + } + + /** + * Generates a {@code long} value between 0 (inclusive) and the specified + * value (exclusive). + * + * @param n Bound on the random number to be returned. Must be positive. + * @return a random {@code long} value between 0 (inclusive) and {@code n} + * (exclusive). + */ + private static long nextLong(long n) { + // Extracted from o.a.c.rng.core.BaseProvider.nextLong(long) + long bits; + long val; + do { + bits = RANDOM.nextLong() >>> 1; + val = bits % n; + } while (bits - val + (n - 1) < 0); + + return val; } /** diff --git a/src/test/java/org/apache/commons/lang3/RandomUtilsTest.java b/src/test/java/org/apache/commons/lang3/RandomUtilsTest.java index b05c71906e2..0c8d609920f 100644 --- a/src/test/java/org/apache/commons/lang3/RandomUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/RandomUtilsTest.java @@ -19,6 +19,7 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -262,4 +263,28 @@ public void testExtremeRangeDouble() { final double result = RandomUtils.nextDouble(0, Double.MAX_VALUE); assertTrue(result >= 0 && result <= Double.MAX_VALUE); } + + /** + * Test a large value for long. A previous implementation using + * {@link RandomUtils#nextDouble(double, double)} could generate a value equal + * to the upper limit. + * + *
      +     * return (long) nextDouble(startInclusive, endExclusive);
      +     * 
      + * + *

      See LANG-1592.

      + */ + @Test + public void testLargeValueRangeLong() { + final long startInclusive = 12900000000001L; + final long endExclusive = 12900000000016L; + // Note: The method using 'return (long) nextDouble(startInclusive, endExclusive)' + // takes thousands of calls to generate an error. This size loop fails most + // of the time with the previous method. + final int n = (int) (endExclusive - startInclusive) * 1000; + for (int i = 0; i < n; i++) { + assertNotEquals(endExclusive, RandomUtils.nextLong(startInclusive, endExclusive)); + } + } } From 3276da82f0b592741088ff0181c0c89df7d279cc Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Thu, 23 Jul 2020 09:24:53 -0400 Subject: [PATCH 0299/3230] Better names in test. Use final. Sort members. --- .../concurrent/locks/LockingVisitorsTest.java | 140 +++++++++--------- 1 file changed, 70 insertions(+), 70 deletions(-) diff --git a/src/test/java/org/apache/commons/lang3/concurrent/locks/LockingVisitorsTest.java b/src/test/java/org/apache/commons/lang3/concurrent/locks/LockingVisitorsTest.java index aba1d20bbc7..8a9234359af 100644 --- a/src/test/java/org/apache/commons/lang3/concurrent/locks/LockingVisitorsTest.java +++ b/src/test/java/org/apache/commons/lang3/concurrent/locks/LockingVisitorsTest.java @@ -28,51 +28,80 @@ import org.junit.jupiter.api.Test; public class LockingVisitorsTest { - private static final int NUMBER_OF_THREADS = 10; private static final long DELAY_MILLIS = 3000; + private static final int NUMBER_OF_THREADS = 10; private static final long TOTAL_DELAY_MILLIS = NUMBER_OF_THREADS * DELAY_MILLIS; - @Test - public void testStampedLockNotExclusive() throws Exception { - - /* - * If our threads are running concurrently, then we expect to be faster than running one after the other. - */ - boolean[] booleanValues = new boolean[10]; - runTest(DELAY_MILLIS, false, l -> assertTrue(l < TOTAL_DELAY_MILLIS), booleanValues, - LockingVisitors.stampedLockVisitor(booleanValues)); + protected boolean containsTrue(final boolean[] booleanArray) { + synchronized (booleanArray) { + for (final boolean element : booleanArray) { + if (element) { + return true; + } + } + return false; + } } - @Test - public void testReentrantReadWriteLockNotExclusive() throws Exception { + private void runTest(final long delayMillis, final boolean exclusiveLock, final LongConsumer runTimeCheck, + final boolean[] booleanValues, final LockVisitor visitor) throws InterruptedException { + final boolean[] runningValues = new boolean[10]; - /* - * If our threads are running concurrently, then we expect to be faster than running one after the other. - */ - boolean[] booleanValues = new boolean[10]; - runTest(DELAY_MILLIS, false, l -> assertTrue(l < TOTAL_DELAY_MILLIS), booleanValues, - LockingVisitors.reentrantReadWriteLockVisitor(booleanValues)); + final long startTime = System.currentTimeMillis(); + for (int i = 0; i < booleanValues.length; i++) { + final int index = i; + final FailableConsumer consumer = b -> { + b[index] = false; + Thread.sleep(delayMillis); + b[index] = true; + set(runningValues, index, false); + }; + final Thread t = new Thread(() -> { + if (exclusiveLock) { + visitor.acceptWriteLocked(consumer); + } else { + visitor.acceptReadLocked(consumer); + } + }); + set(runningValues, i, true); + t.start(); + } + while (containsTrue(runningValues)) { + Thread.sleep(100); + } + final long endTime = System.currentTimeMillis(); + for (final boolean booleanValue : booleanValues) { + assertTrue(booleanValue); + } + // WRONG assumption + // runTimeCheck.accept(endTime - startTime); + } + + protected void set(final boolean[] booleanArray, final int offset, final boolean value) { + synchronized (booleanArray) { + booleanArray[offset] = value; + } } @Test - public void testStampedLockExclusive() throws Exception { + public void testReentrantReadWriteLockExclusive() throws Exception { /* * If our threads are running concurrently, then we expect to be no faster than running one after the other. */ - boolean[] booleanValues = new boolean[10]; + final boolean[] booleanValues = new boolean[10]; runTest(DELAY_MILLIS, true, l -> assertTrue(l >= TOTAL_DELAY_MILLIS), booleanValues, - LockingVisitors.stampedLockVisitor(booleanValues)); + LockingVisitors.reentrantReadWriteLockVisitor(booleanValues)); } @Test - public void testReentrantReadWriteLockExclusive() throws Exception { + public void testReentrantReadWriteLockNotExclusive() throws Exception { /* - * If our threads are running concurrently, then we expect to be no faster than running one after the other. + * If our threads are running concurrently, then we expect to be faster than running one after the other. */ - boolean[] booleanValues = new boolean[10]; - runTest(DELAY_MILLIS, true, l -> assertTrue(l >= TOTAL_DELAY_MILLIS), booleanValues, + final boolean[] booleanValues = new boolean[10]; + runTest(DELAY_MILLIS, false, l -> assertTrue(l < TOTAL_DELAY_MILLIS), booleanValues, LockingVisitors.reentrantReadWriteLockVisitor(booleanValues)); } @@ -90,54 +119,25 @@ public void testResultValidation() { assertNotSame(hidden, o2); } - private void runTest(final long delayMillis, final boolean exclusiveLock, final LongConsumer runTimeCheck, - boolean[] booleanValues, LockVisitor visitor) throws InterruptedException { - final boolean[] runningValues = new boolean[10]; + @Test + public void testStampedLockExclusive() throws Exception { - final long startTime = System.currentTimeMillis(); - for (int i = 0; i < booleanValues.length; i++) { - final int index = i; - final FailableConsumer consumer = b -> { - b[index] = false; - Thread.sleep(delayMillis); - b[index] = true; - modify(runningValues, index, false); - }; - final Thread t = new Thread(() -> { - if (exclusiveLock) { - visitor.acceptWriteLocked(consumer); - } else { - visitor.acceptReadLocked(consumer); - } - }); - modify(runningValues, i, true); - t.start(); - } - while (someValueIsTrue(runningValues)) { - Thread.sleep(100); - } - final long endTime = System.currentTimeMillis(); - for (int i = 0; i < booleanValues.length; i++) { - assertTrue(booleanValues[i]); - } - // WRONG assumption - // runTimeCheck.accept(endTime - startTime); + /* + * If our threads are running concurrently, then we expect to be no faster than running one after the other. + */ + final boolean[] booleanValues = new boolean[10]; + runTest(DELAY_MILLIS, true, l -> assertTrue(l >= TOTAL_DELAY_MILLIS), booleanValues, + LockingVisitors.stampedLockVisitor(booleanValues)); } - protected void modify(final boolean[] booleanArray, final int offset, final boolean value) { - synchronized (booleanArray) { - booleanArray[offset] = value; - } - } + @Test + public void testStampedLockNotExclusive() throws Exception { - protected boolean someValueIsTrue(final boolean[] booleanArray) { - synchronized (booleanArray) { - for (int i = 0; i < booleanArray.length; i++) { - if (booleanArray[i]) { - return true; - } - } - return false; - } + /* + * If our threads are running concurrently, then we expect to be faster than running one after the other. + */ + final boolean[] booleanValues = new boolean[10]; + runTest(DELAY_MILLIS, false, l -> assertTrue(l < TOTAL_DELAY_MILLIS), booleanValues, + LockingVisitors.stampedLockVisitor(booleanValues)); } } From c24701ed3b3d2f178b2ba55b281c4e8d4ca5a3f9 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 23 Jul 2020 09:26:45 -0400 Subject: [PATCH 0300/3230] Bump spotbugs-maven-plugin from 4.0.0 to 4.0.4 (#593) Bumps [spotbugs-maven-plugin](https://github.com/spotbugs/spotbugs-maven-plugin) from 4.0.0 to 4.0.4. - [Release notes](https://github.com/spotbugs/spotbugs-maven-plugin/releases) - [Commits](https://github.com/spotbugs/spotbugs-maven-plugin/compare/spotbugs-maven-plugin-4.0.0...spotbugs-maven-plugin-4.0.4) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 5e599262b04..7caec90440b 100644 --- a/pom.xml +++ b/pom.xml @@ -606,7 +606,7 @@ 8.34 src/site/resources/checkstyle - 4.0.0 + 4.0.4 4.0.6 false true From cb9a59cabbd021a54ebc1e629481d864dd4426c9 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Thu, 23 Jul 2020 09:27:47 -0400 Subject: [PATCH 0301/3230] Update spotbugs-maven-plugin from 4.0.0 to 4.0.4. --- src/changes/changes.xml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index fa59134ca63..5e888491aef 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -46,9 +46,10 @@ The type attribute can be add,update,fix,remove. + Correct implementation of RandomUtils.nextLong(long, long) Remove redundant argument from substring call. Enable Dependabot #587. - Correct implementation of RandomUtils.nextLong(long, long) + Update spotbugs-maven-plugin from 4.0.0 to 4.0.4. Refine test output for FastDateParserTest From ff3d7c2325aac03e1deb79eb343b5536029f4b15 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Thu, 23 Jul 2020 10:05:52 -0400 Subject: [PATCH 0302/3230] Reduce wait time in test. --- .../commons/lang3/concurrent/locks/LockingVisitorsTest.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/test/java/org/apache/commons/lang3/concurrent/locks/LockingVisitorsTest.java b/src/test/java/org/apache/commons/lang3/concurrent/locks/LockingVisitorsTest.java index 8a9234359af..06944e38a1a 100644 --- a/src/test/java/org/apache/commons/lang3/concurrent/locks/LockingVisitorsTest.java +++ b/src/test/java/org/apache/commons/lang3/concurrent/locks/LockingVisitorsTest.java @@ -28,7 +28,8 @@ import org.junit.jupiter.api.Test; public class LockingVisitorsTest { - private static final long DELAY_MILLIS = 3000; + + private static final long DELAY_MILLIS = 1500; private static final int NUMBER_OF_THREADS = 10; private static final long TOTAL_DELAY_MILLIS = NUMBER_OF_THREADS * DELAY_MILLIS; From 3480d214bd65322bf62a5ae1879574b72b6c69bd Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 23 Jul 2020 10:06:44 -0400 Subject: [PATCH 0303/3230] Bump biz.aQute.bndlib from 5.1.1 to 5.1.2 (#592) Bumps [biz.aQute.bndlib](https://github.com/bndtools/bnd) from 5.1.1 to 5.1.2. - [Release notes](https://github.com/bndtools/bnd/releases) - [Changelog](https://github.com/bndtools/bnd/blob/master/docs/ADDING_RELEASE_DOCS.md) - [Commits](https://github.com/bndtools/bnd/commits) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 7caec90440b..d37a5501242 100644 --- a/pom.xml +++ b/pom.xml @@ -782,7 +782,7 @@ biz.aQute.bnd biz.aQute.bndlib - 5.1.1 + 5.1.2 From 8333f7e7ba494789ef781dacb638838742bcefaf Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Thu, 23 Jul 2020 10:08:44 -0400 Subject: [PATCH 0304/3230] Update biz.aQute.bndlib from 5.1.1 to 5.1.2 #592. --- src/changes/changes.xml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 5e888491aef..695cb60908b 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -48,8 +48,9 @@ The type attribute can be add,update,fix,remove. Correct implementation of RandomUtils.nextLong(long, long) Remove redundant argument from substring call. - Enable Dependabot #587. - Update spotbugs-maven-plugin from 4.0.0 to 4.0.4. + Enable Dependabot #587. + Update spotbugs-maven-plugin from 4.0.0 to 4.0.4 #593. + Update biz.aQute.bndlib from 5.1.1 to 5.1.2 #592. Refine test output for FastDateParserTest From 7474e5db7af30c05336182b4faaeaf92c8e9e10f Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Thu, 23 Jul 2020 10:49:38 -0400 Subject: [PATCH 0305/3230] Trying to let Java 15-ea be only 'experimental'. --- .github/workflows/maven.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml index 01eb5e5e0d2..1ca593d37ec 100644 --- a/.github/workflows/maven.yml +++ b/.github/workflows/maven.yml @@ -24,7 +24,7 @@ jobs: continue-on-error: ${{ matrix.experimental }} strategy: matrix: - java: [ 8, 11, 14, 15-ea ] + java: [ 8, 11, 14 ] experimental: [false] include: - node: 15-ea From 7a23f1422928bbcd2bd92cc9b53e0bbbc5ec2fe0 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 23 Jul 2020 10:59:23 -0400 Subject: [PATCH 0306/3230] Bump actions/checkout from v1 to v2.3.1 (#588) Bumps [actions/checkout](https://github.com/actions/checkout) from v1 to v2.3.1. - [Release notes](https://github.com/actions/checkout/releases) - [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md) - [Commits](https://github.com/actions/checkout/compare/v1...28c7f3d2b5162b5ddd3dfd9a45aa55eaf396478b) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/maven.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml index 1ca593d37ec..52bdc819c63 100644 --- a/.github/workflows/maven.yml +++ b/.github/workflows/maven.yml @@ -31,7 +31,7 @@ jobs: experimental: true steps: - - uses: actions/checkout@v1 + - uses: actions/checkout@v2.3.1 - name: Set up JDK ${{ matrix.java }} uses: actions/setup-java@v1 with: From fed91a0559bae51c3e79ac6a067138b5f3bb090c Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Thu, 23 Jul 2020 11:11:51 -0400 Subject: [PATCH 0307/3230] Format JUnit failure message. Tweaks. --- .../lang3/concurrent/EventCountCircuitBreakerTest.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/test/java/org/apache/commons/lang3/concurrent/EventCountCircuitBreakerTest.java b/src/test/java/org/apache/commons/lang3/concurrent/EventCountCircuitBreakerTest.java index 9e486952c2b..02a929005f1 100644 --- a/src/test/java/org/apache/commons/lang3/concurrent/EventCountCircuitBreakerTest.java +++ b/src/test/java/org/apache/commons/lang3/concurrent/EventCountCircuitBreakerTest.java @@ -96,9 +96,9 @@ public void testInitiallyClosed() { public void testNow() { final EventCountCircuitBreaker breaker = new EventCountCircuitBreaker(OPENING_THRESHOLD, 1, TimeUnit.SECONDS); - final long now = breaker.now(); - final long delta = Math.abs(System.nanoTime() - now); - assertTrue(delta < 100000, String.format("Delta %d ns to current time too large", delta)); + final long nowNanos = breaker.now(); + final long deltaNanos = Math.abs(System.nanoTime() - nowNanos); + assertTrue(deltaNanos < 100_000, String.format("Delta %,d ns to current time too large", deltaNanos)); } /** From 1f0ea934246750be78b15c7a72192c4a7835b7f3 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 23 Jul 2020 11:13:35 -0400 Subject: [PATCH 0308/3230] Bump junit-pioneer from 0.6.0 to 0.7.0 (#589) Bumps [junit-pioneer](https://github.com/junit-pioneer/junit-pioneer) from 0.6.0 to 0.7.0. - [Release notes](https://github.com/junit-pioneer/junit-pioneer/releases) - [Changelog](https://github.com/junit-pioneer/junit-pioneer/blob/master/docs/release-notes.md) - [Commits](https://github.com/junit-pioneer/junit-pioneer/compare/v0.6.0...v0.7.0) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index d37a5501242..58c54c5237a 100644 --- a/pom.xml +++ b/pom.xml @@ -525,7 +525,7 @@ org.junit-pioneer junit-pioneer - 0.6.0 + 0.7.0 test From f22f659321662b3dc04fab0c5e2a1e878f6d303f Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Thu, 23 Jul 2020 11:14:40 -0400 Subject: [PATCH 0309/3230] Document recent change. --- src/changes/changes.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 695cb60908b..3ca3f8b3c7e 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -51,6 +51,7 @@ The type attribute can be add,update,fix,remove. Enable Dependabot #587. Update spotbugs-maven-plugin from 4.0.0 to 4.0.4 #593. Update biz.aQute.bndlib from 5.1.1 to 5.1.2 #592. + Update junit-pioneer from 0.6.0 to 0.7.0 #589. Refine test output for FastDateParserTest From cb4d8afe4542bb043f6e8a267ea88438489dcf8e Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sun, 26 Jul 2020 17:06:27 -0400 Subject: [PATCH 0310/3230] GitHub actions/setup-java@v1 -> actions/setup-java@v1.4.0 --- .github/workflows/maven.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml index 52bdc819c63..5c8b1b3243a 100644 --- a/.github/workflows/maven.yml +++ b/.github/workflows/maven.yml @@ -33,7 +33,7 @@ jobs: steps: - uses: actions/checkout@v2.3.1 - name: Set up JDK ${{ matrix.java }} - uses: actions/setup-java@v1 + uses: actions/setup-java@v1.4.0 with: java-version: ${{ matrix.java }} - name: Build with Maven From ccca0a017961d6ad6ec58f5565f3291088072cd0 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sun, 26 Jul 2020 17:18:56 -0400 Subject: [PATCH 0311/3230] GitHub action for Java 15-ea. --- .github/workflows/maven.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml index 5c8b1b3243a..86bbf63ac31 100644 --- a/.github/workflows/maven.yml +++ b/.github/workflows/maven.yml @@ -27,7 +27,7 @@ jobs: java: [ 8, 11, 14 ] experimental: [false] include: - - node: 15-ea + - java: 15-ea experimental: true steps: From 5bc1287eae43f30afd483162c1e12694c8ea01b9 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sun, 26 Jul 2020 17:27:27 -0400 Subject: [PATCH 0312/3230] Add Java 16-ea. --- .github/workflows/maven.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml index 86bbf63ac31..691df80f92b 100644 --- a/.github/workflows/maven.yml +++ b/.github/workflows/maven.yml @@ -29,6 +29,9 @@ jobs: include: - java: 15-ea experimental: true + include: + - java: 16-ea + experimental: true steps: - uses: actions/checkout@v2.3.1 From cf0bc2b5dbb08ee1f5c0c8d54df307e23345544d Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sun, 26 Jul 2020 17:28:00 -0400 Subject: [PATCH 0313/3230] Add Java 16-ea. --- .github/workflows/maven.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml index 691df80f92b..ec976dc2ec2 100644 --- a/.github/workflows/maven.yml +++ b/.github/workflows/maven.yml @@ -29,7 +29,6 @@ jobs: include: - java: 15-ea experimental: true - include: - java: 16-ea experimental: true From dbe022e64600a41fabb4d621c6a9809bc9189990 Mon Sep 17 00:00:00 2001 From: aherbert Date: Wed, 29 Jul 2020 11:47:46 +0100 Subject: [PATCH 0314/3230] LANG-1579: Improve stripAccents conversion of remaining accents Single characters can be changed in place to avoid delete then insert. Closes #568 --- src/changes/changes.xml | 1 + src/main/java/org/apache/commons/lang3/StringUtils.java | 6 ++---- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 3ca3f8b3c7e..384aab0a5be 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -52,6 +52,7 @@ The type attribute can be add,update,fix,remove. Update spotbugs-maven-plugin from 4.0.0 to 4.0.4 #593. Update biz.aQute.bndlib from 5.1.1 to 5.1.2 #592. Update junit-pioneer from 0.6.0 to 0.7.0 #589. + Improve stripAccents conversion of remaining accents. Refine test output for FastDateParserTest diff --git a/src/main/java/org/apache/commons/lang3/StringUtils.java b/src/main/java/org/apache/commons/lang3/StringUtils.java index 0cb10e6753c..a93d34a7ff6 100644 --- a/src/main/java/org/apache/commons/lang3/StringUtils.java +++ b/src/main/java/org/apache/commons/lang3/StringUtils.java @@ -1382,11 +1382,9 @@ public static boolean containsWhitespace(final CharSequence seq) { private static void convertRemainingAccentCharacters(final StringBuilder decomposed) { for (int i = 0; i < decomposed.length(); i++) { if (decomposed.charAt(i) == '\u0141') { - decomposed.deleteCharAt(i); - decomposed.insert(i, 'L'); + decomposed.setCharAt(i, 'L'); } else if (decomposed.charAt(i) == '\u0142') { - decomposed.deleteCharAt(i); - decomposed.insert(i, 'l'); + decomposed.setCharAt(i, 'l'); } } } From c3b4e22562df9517064844caa13416e5771b2eb3 Mon Sep 17 00:00:00 2001 From: aherbert Date: Wed, 29 Jul 2020 11:50:55 +0100 Subject: [PATCH 0315/3230] Fix changes description to include class name --- src/changes/changes.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 384aab0a5be..120587997b3 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -52,7 +52,7 @@ The type attribute can be add,update,fix,remove. Update spotbugs-maven-plugin from 4.0.0 to 4.0.4 #593. Update biz.aQute.bndlib from 5.1.1 to 5.1.2 #592. Update junit-pioneer from 0.6.0 to 0.7.0 #589. - Improve stripAccents conversion of remaining accents. + Improve StringUtils.stripAccents conversion of remaining accents. Refine test output for FastDateParserTest From 3eb8facea0c9079cfaeee7c6292b107f02c7bf81 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 31 Jul 2020 09:10:52 -0400 Subject: [PATCH 0316/3230] Bump spotbugs from 4.0.6 to 4.1.1 (#596) Bumps [spotbugs](https://github.com/spotbugs/spotbugs) from 4.0.6 to 4.1.1. - [Release notes](https://github.com/spotbugs/spotbugs/releases) - [Changelog](https://github.com/spotbugs/spotbugs/blob/master/CHANGELOG.md) - [Commits](https://github.com/spotbugs/spotbugs/compare/4.0.6...4.1.1) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 58c54c5237a..28062778497 100644 --- a/pom.xml +++ b/pom.xml @@ -607,7 +607,7 @@ src/site/resources/checkstyle 4.0.4 - 4.0.6 + 4.1.1 false true From 26dc0118d486ef89f463a0da0837cca86950dcbf Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 31 Jul 2020 09:12:54 -0400 Subject: [PATCH 0317/3230] Bump checkstyle from 8.34 to 8.35 (#594) Bumps [checkstyle](https://github.com/checkstyle/checkstyle) from 8.34 to 8.35. - [Release notes](https://github.com/checkstyle/checkstyle/releases) - [Commits](https://github.com/checkstyle/checkstyle/compare/checkstyle-8.34...checkstyle-8.35) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 28062778497..6d23b73bb27 100644 --- a/pom.xml +++ b/pom.xml @@ -603,7 +603,7 @@ utf-8 3.1.1 - 8.34 + 8.35 src/site/resources/checkstyle 4.0.4 From 03ae16503990764ced213063e9bbb35289f65270 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Fri, 31 Jul 2020 09:13:40 -0400 Subject: [PATCH 0318/3230] Document recent changes. --- src/changes/changes.xml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 120587997b3..6c82d8672d9 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -48,11 +48,12 @@ The type attribute can be add,update,fix,remove. Correct implementation of RandomUtils.nextLong(long, long) Remove redundant argument from substring call. + Improve StringUtils.stripAccents conversion of remaining accents. Enable Dependabot #587. - Update spotbugs-maven-plugin from 4.0.0 to 4.0.4 #593. + Update spotbugs-maven-plugin from 4.0.0 to 4.1.1, #593, #596. Update biz.aQute.bndlib from 5.1.1 to 5.1.2 #592. Update junit-pioneer from 0.6.0 to 0.7.0 #589. - Improve StringUtils.stripAccents conversion of remaining accents. + Update checkstyle from 8.34 to 8.35 #594. Refine test output for FastDateParserTest From 3b7d72e6cfdf3ea74e5de89412637079dbe3ed37 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Fri, 31 Jul 2020 09:16:50 -0400 Subject: [PATCH 0319/3230] Use the POM defaultGoal so that Travis and GitHub run the same builds. --- .github/workflows/maven.yml | 2 +- pom.xml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml index ec976dc2ec2..7ebed4c8d31 100644 --- a/.github/workflows/maven.yml +++ b/.github/workflows/maven.yml @@ -39,4 +39,4 @@ jobs: with: java-version: ${{ matrix.java }} - name: Build with Maven - run: mvn -V apache-rat:check spotbugs:check javadoc:javadoc -Ddoclint=all package --file pom.xml + run: mvn -V -Ddoclint=all --file pom.xml diff --git a/pom.xml b/pom.xml index 28062778497..ea9df57338e 100644 --- a/pom.xml +++ b/pom.xml @@ -634,7 +634,7 @@ - clean verify apache-rat:check checkstyle:check japicmp:cmp spotbugs:check javadoc:javadoc + clean package apache-rat:check checkstyle:check japicmp:cmp spotbugs:check javadoc:javadoc From 4897c8869b7050ba98b19c743762c10a56581ee4 Mon Sep 17 00:00:00 2001 From: Gilles Sadowski Date: Mon, 3 Aug 2020 12:24:13 +0200 Subject: [PATCH 0320/3230] LANG-1593: Add unit test with OP's use-case that shows unexpected difference in behaviour. Unit test is set to "@Disabled" to not fail the build. --- .../java/org/apache/commons/lang3/StringUtilsTest.java | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/test/java/org/apache/commons/lang3/StringUtilsTest.java b/src/test/java/org/apache/commons/lang3/StringUtilsTest.java index 7c657d0f861..99ebed700d6 100644 --- a/src/test/java/org/apache/commons/lang3/StringUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/StringUtilsTest.java @@ -45,6 +45,7 @@ import org.apache.commons.lang3.mutable.MutableInt; import org.apache.commons.lang3.text.WordUtils; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Disabled; /** * Unit tests for methods of {@link org.apache.commons.lang3.StringUtils} @@ -1341,6 +1342,15 @@ public void testJoin_Objectarray() { assertEquals("foo2", StringUtils.join(MIXED_TYPE_LIST)); } + @Disabled + @Test + public void testLang1593() { + final int[] arr = new int[] {1, 2, 3, 4, 5, 6, 7}; + final String expected = StringUtils.join(arr, '-'); + final String actual = StringUtils.join(arr, "-"); + assertEquals(expected, actual); + } + //----------------------------------------------------------------------- @Test public void testJoin_Objects() { From bc9612872904f6d375f73b308a43add8bf203879 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 3 Aug 2020 09:26:43 -0400 Subject: [PATCH 0321/3230] Bump junit-pioneer from 0.7.0 to 0.8.0 (#597) Bumps [junit-pioneer](https://github.com/junit-pioneer/junit-pioneer) from 0.7.0 to 0.8.0. - [Release notes](https://github.com/junit-pioneer/junit-pioneer/releases) - [Changelog](https://github.com/junit-pioneer/junit-pioneer/blob/master/docs/release-notes.md) - [Commits](https://github.com/junit-pioneer/junit-pioneer/compare/v0.7.0...v0.8.0) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 6d23b73bb27..bf8309ebfa5 100644 --- a/pom.xml +++ b/pom.xml @@ -525,7 +525,7 @@ org.junit-pioneer junit-pioneer - 0.7.0 + 0.8.0 test From 8a877ec12e0209e5928b8cae806ba83c8fe5ed79 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Mon, 3 Aug 2020 09:29:10 -0400 Subject: [PATCH 0322/3230] Describe recent change. --- src/changes/changes.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 6c82d8672d9..dde041b24b3 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -52,7 +52,7 @@ The type attribute can be add,update,fix,remove. Enable Dependabot #587. Update spotbugs-maven-plugin from 4.0.0 to 4.1.1, #593, #596. Update biz.aQute.bndlib from 5.1.1 to 5.1.2 #592. - Update junit-pioneer from 0.6.0 to 0.7.0 #589. + Update junit-pioneer from 0.6.0 to 0.8.0, #589, #597. Update checkstyle from 8.34 to 8.35 #594. From c5af087b58dd087be48813bc6bbe95689a784411 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Wed, 5 Aug 2020 09:39:05 -0400 Subject: [PATCH 0323/3230] Add --no-transfer-progress to CI builds. --- .github/workflows/maven.yml | 2 +- .travis.yml | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml index 7ebed4c8d31..e07bb9b41d8 100644 --- a/.github/workflows/maven.yml +++ b/.github/workflows/maven.yml @@ -39,4 +39,4 @@ jobs: with: java-version: ${{ matrix.java }} - name: Build with Maven - run: mvn -V -Ddoclint=all --file pom.xml + run: mvn -V -Ddoclint=all --file pom.xml --no-transfer-progress diff --git a/.travis.yml b/.travis.yml index 7432cc48251..25e27d731aa 100644 --- a/.travis.yml +++ b/.travis.yml @@ -29,6 +29,6 @@ matrix: allow_failures: - jdk: openjdk-ea script: - - mvn + - mvn -V --no-transfer-progress after_success: - - mvn clean test jacoco:report coveralls:report -Ptravis-jacoco javadoc:javadoc -Ddoclint=all + - mvn -V --no-transfer-progress clean test jacoco:report coveralls:report -Ptravis-jacoco javadoc:javadoc -Ddoclint=all From ba09f94d970837abe778bd57c69fc7fc4a58f162 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 5 Aug 2020 11:11:06 -0400 Subject: [PATCH 0324/3230] Bump commons-parent from 51 to 52 (#598) Bumps commons-parent from 51 to 52. Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 91ca87b21c0..47fb56f71c4 100644 --- a/pom.xml +++ b/pom.xml @@ -22,7 +22,7 @@ org.apache.commons commons-parent - 51 + 52 4.0.0 commons-lang3 From c147084647c53626d4100ae7b643a557f47be34e Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sat, 8 Aug 2020 19:09:42 -0400 Subject: [PATCH 0325/3230] No reason to build specifically on linux-ppc64le. Format. --- .travis.yml | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/.travis.yml b/.travis.yml index 25e27d731aa..f395853512d 100644 --- a/.travis.yml +++ b/.travis.yml @@ -14,21 +14,23 @@ # limitations under the License. language: java + cache: directories: - $HOME/.m2 + jdk: - openjdk8 - openjdk11 - openjdk14 - openjdk-ea + matrix: - include: - - os: linux-ppc64le - jdk: openjdk8 allow_failures: - jdk: openjdk-ea + script: - - mvn -V --no-transfer-progress + - mvn -V --no-transfer-progress + after_success: - mvn -V --no-transfer-progress clean test jacoco:report coveralls:report -Ptravis-jacoco javadoc:javadoc -Ddoclint=all From 301c91f6e6342d5ee16dd9588dd396d74f7c9ac4 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 10 Aug 2020 12:01:27 -0400 Subject: [PATCH 0326/3230] Bump actions/checkout from v2.3.1 to v2.3.2 (#601) Bumps [actions/checkout](https://github.com/actions/checkout) from v2.3.1 to v2.3.2. - [Release notes](https://github.com/actions/checkout/releases) - [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md) - [Commits](https://github.com/actions/checkout/compare/v2.3.1...2036a08e25fa78bbd946711a407b529a0a1204bf) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/maven.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml index e07bb9b41d8..0736d00ad8b 100644 --- a/.github/workflows/maven.yml +++ b/.github/workflows/maven.yml @@ -33,7 +33,7 @@ jobs: experimental: true steps: - - uses: actions/checkout@v2.3.1 + - uses: actions/checkout@v2.3.2 - name: Set up JDK ${{ matrix.java }} uses: actions/setup-java@v1.4.0 with: From 17e1f408f77cf320b48f91371d2f5c120783f5fa Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Mon, 10 Aug 2020 12:02:06 -0400 Subject: [PATCH 0327/3230] actions/checkout from v2.3.1 to v2.3.2 #601. --- src/changes/changes.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index dde041b24b3..1fa7b9c5222 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -54,6 +54,7 @@ The type attribute can be add,update,fix,remove. Update biz.aQute.bndlib from 5.1.1 to 5.1.2 #592. Update junit-pioneer from 0.6.0 to 0.8.0, #589, #597. Update checkstyle from 8.34 to 8.35 #594. + Update actions/checkout from v2.3.1 to v2.3.2 #601. Refine test output for FastDateParserTest From 67d23532e5f035f9bd79705cb4753fcd0d80ff45 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 10 Aug 2020 12:02:26 -0400 Subject: [PATCH 0328/3230] Bump junit-pioneer from 0.8.0 to 0.9.0 (#600) Bumps [junit-pioneer](https://github.com/junit-pioneer/junit-pioneer) from 0.8.0 to 0.9.0. - [Release notes](https://github.com/junit-pioneer/junit-pioneer/releases) - [Changelog](https://github.com/junit-pioneer/junit-pioneer/blob/master/docs/release-notes.md) - [Commits](https://github.com/junit-pioneer/junit-pioneer/compare/v0.8.0...v0.9.0) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 47fb56f71c4..e833726536e 100644 --- a/pom.xml +++ b/pom.xml @@ -525,7 +525,7 @@ org.junit-pioneer junit-pioneer - 0.8.0 + 0.9.0 test From 9f52471fab5bf82db3d2f9e0086bf3c56c894ec6 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Mon, 10 Aug 2020 12:03:02 -0400 Subject: [PATCH 0329/3230] junit-pioneer from 0.8.0 to 0.9.0 #600. --- src/changes/changes.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 1fa7b9c5222..161f7d8f688 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -52,7 +52,7 @@ The type attribute can be add,update,fix,remove. Enable Dependabot #587. Update spotbugs-maven-plugin from 4.0.0 to 4.1.1, #593, #596. Update biz.aQute.bndlib from 5.1.1 to 5.1.2 #592. - Update junit-pioneer from 0.6.0 to 0.8.0, #589, #597. + Update junit-pioneer from 0.6.0 to 0.9.0, #589, #597, #600. Update checkstyle from 8.34 to 8.35 #594. Update actions/checkout from v2.3.1 to v2.3.2 #601. From 600f0c8a1d9f4b1884cafb7cf6f0e43da1742fe9 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Mon, 10 Aug 2020 21:16:35 -0400 Subject: [PATCH 0330/3230] Cache ~/.m2 dir for GitHub builds. --- .github/workflows/maven.yml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml index 0736d00ad8b..b1543a37b7e 100644 --- a/.github/workflows/maven.yml +++ b/.github/workflows/maven.yml @@ -34,6 +34,12 @@ jobs: steps: - uses: actions/checkout@v2.3.2 + - uses: actions/cache@v2 + with: + path: ~/.m2/repository + key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} + restore-keys: | + ${{ runner.os }}-maven- - name: Set up JDK ${{ matrix.java }} uses: actions/setup-java@v1.4.0 with: From 6996806101b69a87ffcfc4fa9237c075105d722f Mon Sep 17 00:00:00 2001 From: Richard Eckart de Castilho Date: Sat, 15 Aug 2020 05:25:54 +0200 Subject: [PATCH 0331/3230] [LANG-1596] ArrayUtils.toPrimitive(Object) does not support boolean and other types (#607) - Add support for the missing types to toPrimitive(Object) - Added tests for toPrimitive methods which did not have test coverage yet - Added explicit test for the toPrimitive(Object) method for all primitive types --- .../org/apache/commons/lang3/ArrayUtils.java | 9 +++++++++ .../org/apache/commons/lang3/ArrayUtilsTest.java | 16 ++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/src/main/java/org/apache/commons/lang3/ArrayUtils.java b/src/main/java/org/apache/commons/lang3/ArrayUtils.java index 1fe9dd47c26..f620fd93038 100644 --- a/src/main/java/org/apache/commons/lang3/ArrayUtils.java +++ b/src/main/java/org/apache/commons/lang3/ArrayUtils.java @@ -9478,6 +9478,15 @@ public static Object toPrimitive(final Object array) { } final Class ct = array.getClass().getComponentType(); final Class pt = ClassUtils.wrapperToPrimitive(ct); + if (Boolean.TYPE.equals(pt)) { + return toPrimitive((Boolean[]) array); + } + if (Character.TYPE.equals(pt)) { + return toPrimitive((Character[]) array); + } + if (Byte.TYPE.equals(pt)) { + return toPrimitive((Byte[]) array); + } if (Integer.TYPE.equals(pt)) { return toPrimitive((Integer[]) array); } diff --git a/src/test/java/org/apache/commons/lang3/ArrayUtilsTest.java b/src/test/java/org/apache/commons/lang3/ArrayUtilsTest.java index f5b40ad126f..46bb1042e10 100644 --- a/src/test/java/org/apache/commons/lang3/ArrayUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/ArrayUtilsTest.java @@ -341,6 +341,9 @@ public void testContainsShort() { @Test public void testCreatePrimitiveArray() { assertNull(ArrayUtils.toPrimitive((Object[]) null)); + assertArrayEquals(new boolean[]{true}, ArrayUtils.toPrimitive(new Boolean[]{true})); + assertArrayEquals(new char[]{'a'}, ArrayUtils.toPrimitive(new Character[]{'a'})); + assertArrayEquals(new byte[]{1}, ArrayUtils.toPrimitive(new Byte[]{1})); assertArrayEquals(new int[]{}, ArrayUtils.toPrimitive(new Integer[]{})); assertArrayEquals(new short[]{2}, ArrayUtils.toPrimitive(new Short[]{2})); assertArrayEquals(new long[]{2, 3}, ArrayUtils.toPrimitive(new Long[]{2L, 3L})); @@ -348,6 +351,19 @@ public void testCreatePrimitiveArray() { assertArrayEquals(new double[]{2.718}, ArrayUtils.toPrimitive(new Double[]{2.718}), 0.1); } + @Test + public void testCreatePrimitiveArrayViaObjectArray() { + assertNull(ArrayUtils.toPrimitive((Object) null)); + assertArrayEquals(new boolean[]{true}, (boolean[]) ArrayUtils.toPrimitive((Object) new Boolean[]{true})); + assertArrayEquals(new char[]{'a'}, (char[]) ArrayUtils.toPrimitive((Object) new Character[]{'a'})); + assertArrayEquals(new byte[]{1}, (byte[]) ArrayUtils.toPrimitive((Object) new Byte[]{1})); + assertArrayEquals(new int[]{}, (int[]) ArrayUtils.toPrimitive((Object) new Integer[]{})); + assertArrayEquals(new short[]{2}, (short[]) ArrayUtils.toPrimitive((Object) new Short[]{2})); + assertArrayEquals(new long[]{2, 3}, (long[]) ArrayUtils.toPrimitive((Object) new Long[]{2L, 3L})); + assertArrayEquals(new float[]{3.14f}, (float[]) ArrayUtils.toPrimitive((Object) new Float[]{3.14f}), 0.1f); + assertArrayEquals(new double[]{2.718}, (double[]) ArrayUtils.toPrimitive((Object) new Double[]{2.718}), 0.1); + } + /** * Tests generic empty array creation with generic type. */ From 348cf477411421809e7f89dfaa4338e96236a9cf Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Fri, 14 Aug 2020 23:27:31 -0400 Subject: [PATCH 0332/3230] [LANG-1596] ArrayUtils.toPrimitive(Object) does not support boolean and other types #607. --- src/changes/changes.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 161f7d8f688..145c89b4daa 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -49,6 +49,7 @@ The type attribute can be add,update,fix,remove. Correct implementation of RandomUtils.nextLong(long, long) Remove redundant argument from substring call. Improve StringUtils.stripAccents conversion of remaining accents. + ArrayUtils.toPrimitive(Object) does not support boolean and other types #607. Enable Dependabot #587. Update spotbugs-maven-plugin from 4.0.0 to 4.1.1, #593, #596. Update biz.aQute.bndlib from 5.1.1 to 5.1.2 #592. From 5d05df0f9e7a7658cd4a8aa6edbb07cc2a8331b4 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Fri, 14 Aug 2020 23:35:42 -0400 Subject: [PATCH 0333/3230] Simplify lambdas. --- .../commons/lang3/concurrent/locks/LockingVisitorsTest.java | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/test/java/org/apache/commons/lang3/concurrent/locks/LockingVisitorsTest.java b/src/test/java/org/apache/commons/lang3/concurrent/locks/LockingVisitorsTest.java index 06944e38a1a..ab06e6a53aa 100644 --- a/src/test/java/org/apache/commons/lang3/concurrent/locks/LockingVisitorsTest.java +++ b/src/test/java/org/apache/commons/lang3/concurrent/locks/LockingVisitorsTest.java @@ -110,12 +110,10 @@ public void testReentrantReadWriteLockNotExclusive() throws Exception { public void testResultValidation() { final Object hidden = new Object(); final StampedLockVisitor lock = LockingVisitors.stampedLockVisitor(hidden); - final Object o1 = lock.applyReadLocked(h -> { - return new Object(); }); + final Object o1 = lock.applyReadLocked(h -> new Object()); assertNotNull(o1); assertNotSame(hidden, o1); - final Object o2 = lock.applyWriteLocked(h -> { - return new Object(); }); + final Object o2 = lock.applyWriteLocked(h -> new Object()); assertNotNull(o2); assertNotSame(hidden, o2); } From 5e085b72ec08121f2acefaa9110a0464ebd40e67 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sun, 16 Aug 2020 13:35:56 -0400 Subject: [PATCH 0334/3230] JApiCmp is already configured in the parent and enabled with a property. --- pom.xml | 8 -------- 1 file changed, 8 deletions(-) diff --git a/pom.xml b/pom.xml index e833726536e..f44aae70940 100644 --- a/pom.xml +++ b/pom.xml @@ -650,14 +650,6 @@ - - - com.github.siom79.japicmp - japicmp-maven-plugin - - false - - From 31dc5c700e1a08f4af33d94301ff06790533099b Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Thu, 20 Aug 2020 13:50:23 -0400 Subject: [PATCH 0335/3230] Remove old comments. --- src/main/java/org/apache/commons/lang3/Range.java | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/Range.java b/src/main/java/org/apache/commons/lang3/Range.java index a17254118d7..2c9e4b7060d 100644 --- a/src/main/java/org/apache/commons/lang3/Range.java +++ b/src/main/java/org/apache/commons/lang3/Range.java @@ -32,7 +32,6 @@ */ public final class Range implements Serializable { - //----------------------------------------------------------------------- @SuppressWarnings({"rawtypes", "unchecked"}) private enum ComparableComparator implements Comparator { INSTANCE; @@ -155,9 +154,6 @@ public static Range is(final T element, final Comparator comparator) { */ private transient String toString; - // Accessors - //-------------------------------------------------------------------- - /** * Creates an instance. * @@ -332,9 +328,6 @@ public Range intersectionWith(final Range other) { return between(min, max, getComparator()); } - // Range tests - //-------------------------------------------------------------------- - /** *

      Checks whether this range is after the specified element.

      * @@ -406,9 +399,6 @@ public boolean isEndedBy(final T element) { return comparator.compare(element, maximum) == 0; } - // Basics - //-------------------------------------------------------------------- - /** *

      Whether or not the Range is using the natural ordering of the elements.

      * From 2f19010c7a0812abde352e3060712425d06db949 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sun, 30 Aug 2020 11:27:37 -0400 Subject: [PATCH 0336/3230] Fix a Javadoc link to always point to the current release and not mention a specific version label. --- src/site/xdoc/index.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/site/xdoc/index.xml b/src/site/xdoc/index.xml index 4461670ba5e..bd8bd3303d6 100644 --- a/src/site/xdoc/index.xml +++ b/src/site/xdoc/index.xml @@ -50,7 +50,7 @@ and various project reports are provided. The Javadoc API documents are available online:

      From 0823b7568f55afee2a423485ae615fff7437be80 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sun, 30 Aug 2020 11:33:46 -0400 Subject: [PATCH 0337/3230] Bump actions/setup-java from v1.4.0 to v1.4.2 (#612) Bumps [actions/setup-java](https://github.com/actions/setup-java) from v1.4.0 to v1.4.2. - [Release notes](https://github.com/actions/setup-java/releases) - [Commits](https://github.com/actions/setup-java/compare/v1.4.0...8bb50d97d6b4d316daf284fdf8eafbfc988421fc) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/maven.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml index b1543a37b7e..0b867fc7d85 100644 --- a/.github/workflows/maven.yml +++ b/.github/workflows/maven.yml @@ -41,7 +41,7 @@ jobs: restore-keys: | ${{ runner.os }}-maven- - name: Set up JDK ${{ matrix.java }} - uses: actions/setup-java@v1.4.0 + uses: actions/setup-java@v1.4.2 with: java-version: ${{ matrix.java }} - name: Build with Maven From fb341305209dd75367553f13ee902a2248cbe9f7 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sun, 30 Aug 2020 11:34:48 -0400 Subject: [PATCH 0338/3230] actions/setup-java from v1.4.0 to v1.4.2 #612. --- src/changes/changes.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 145c89b4daa..d51424e42ee 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -56,6 +56,7 @@ The type attribute can be add,update,fix,remove. Update junit-pioneer from 0.6.0 to 0.9.0, #589, #597, #600. Update checkstyle from 8.34 to 8.35 #594. Update actions/checkout from v2.3.1 to v2.3.2 #601. + Update actions/setup-java from v1.4.0 to v1.4.2 #612. Refine test output for FastDateParserTest From 0131cc31fc5f367813781e84dea215630955301f Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sun, 30 Aug 2020 11:36:41 -0400 Subject: [PATCH 0339/3230] Bump spotbugs from 4.1.1 to 4.1.2 (#609) Bumps [spotbugs](https://github.com/spotbugs/spotbugs) from 4.1.1 to 4.1.2. - [Release notes](https://github.com/spotbugs/spotbugs/releases) - [Changelog](https://github.com/spotbugs/spotbugs/blob/master/CHANGELOG.md) - [Commits](https://github.com/spotbugs/spotbugs/compare/4.1.1...4.1.2) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index f44aae70940..37fd96ee42a 100644 --- a/pom.xml +++ b/pom.xml @@ -607,7 +607,7 @@ src/site/resources/checkstyle 4.0.4 - 4.1.1 + 4.1.2 false true From 5512896585392d3b15f568ef261062dd0eb7e13c Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sun, 30 Aug 2020 11:37:31 -0400 Subject: [PATCH 0340/3230] spotbugs from 4.1.1 to 4.1.2 #609. --- src/changes/changes.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index d51424e42ee..c0b479d3729 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -51,7 +51,7 @@ The type attribute can be add,update,fix,remove. Improve StringUtils.stripAccents conversion of remaining accents. ArrayUtils.toPrimitive(Object) does not support boolean and other types #607. Enable Dependabot #587. - Update spotbugs-maven-plugin from 4.0.0 to 4.1.1, #593, #596. + Update spotbugs-maven-plugin from 4.0.0 to 4.1.2, #593, #596, #609. Update biz.aQute.bndlib from 5.1.1 to 5.1.2 #592. Update junit-pioneer from 0.6.0 to 0.9.0, #589, #597, #600. Update checkstyle from 8.34 to 8.35 #594. From b1a66d2da97297c4a0b4c64c6911fa121526a9f9 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sun, 30 Aug 2020 18:12:26 -0400 Subject: [PATCH 0341/3230] Better link. --- src/site/xdoc/userguide.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/site/xdoc/userguide.xml b/src/site/xdoc/userguide.xml index 7e5a25e7777..ea14c829a4f 100644 --- a/src/site/xdoc/userguide.xml +++ b/src/site/xdoc/userguide.xml @@ -26,7 +26,7 @@ limitations under the License.
      - Looking for the User Guide? It has been moved to the package Javadoc + Looking for the User Guide? It has been moved to the package Javadoc.
      From 0683ab262d7d7a6fc74e1ec6da4ac910bcc2b5da Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sun, 30 Aug 2020 18:13:18 -0400 Subject: [PATCH 0342/3230] Revert "Better link." This reverts commit b1a66d2da97297c4a0b4c64c6911fa121526a9f9. --- src/site/xdoc/userguide.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/site/xdoc/userguide.xml b/src/site/xdoc/userguide.xml index ea14c829a4f..7e5a25e7777 100644 --- a/src/site/xdoc/userguide.xml +++ b/src/site/xdoc/userguide.xml @@ -26,7 +26,7 @@ limitations under the License.
      - Looking for the User Guide? It has been moved to the package Javadoc. + Looking for the User Guide? It has been moved to the package Javadoc
      From 47f96a3c95fa24c42ad842f49768f6c9529430fe Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sun, 30 Aug 2020 18:13:45 -0400 Subject: [PATCH 0343/3230] End sentence with a period. --- src/site/xdoc/userguide.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/site/xdoc/userguide.xml b/src/site/xdoc/userguide.xml index 7e5a25e7777..1e39ec861e4 100644 --- a/src/site/xdoc/userguide.xml +++ b/src/site/xdoc/userguide.xml @@ -26,7 +26,7 @@ limitations under the License.
      - Looking for the User Guide? It has been moved to the package Javadoc + Looking for the User Guide? It has been moved to the package Javadoc.
      From 772f97c4378613d241ecacc2076fdda20d59e982 Mon Sep 17 00:00:00 2001 From: Michael F Date: Sun, 30 Aug 2020 15:27:17 -0700 Subject: [PATCH 0344/3230] [LANG-1600] Restore handling of collections for non-JSON ToStringStyle (#610) * [LANG-1600] add test cases for non-empty collections, maps, and arrays * break out those test cases into separate methods for legibility * addresses issue introduced in LANG-1542 with commit 1dddec8 * [LANG-1600] restore non-json-style handling of appendDetail() for Collection * addresses issue introduced in LANG-1542 with commit 1dddec8 --- .../commons/lang3/builder/ToStringStyle.java | 25 ++++++----- .../builder/DefaultToStringStyleTest.java | 42 +++++++++++++++---- .../builder/MultiLineToStringStyleTest.java | 42 +++++++++++++++---- .../builder/NoClassNameToStringStyleTest.java | 42 +++++++++++++++---- .../NoFieldNamesToStringStyleTest.java | 42 +++++++++++++++---- .../builder/ShortPrefixToStringStyleTest.java | 42 +++++++++++++++---- .../builder/SimpleToStringStyleTest.java | 42 +++++++++++++++---- .../builder/StandardToStringStyleTest.java | 42 +++++++++++++++---- 8 files changed, 253 insertions(+), 66 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/builder/ToStringStyle.java b/src/main/java/org/apache/commons/lang3/builder/ToStringStyle.java index 02c4231e609..7e43baa0a52 100644 --- a/src/main/java/org/apache/commons/lang3/builder/ToStringStyle.java +++ b/src/main/java/org/apache/commons/lang3/builder/ToStringStyle.java @@ -626,16 +626,6 @@ protected void appendDetail(final StringBuffer buffer, final String fieldName, f * {@code toString}, not {@code null} */ protected void appendDetail(final StringBuffer buffer, final String fieldName, final Collection coll) { - if (coll != null && !coll.isEmpty()) { - buffer.append(arrayStart); - int i = 0; - for (final Object item : coll) { - appendDetail(buffer, fieldName, i++, item); - } - buffer.append(arrayEnd); - return; - } - buffer.append(coll); } @@ -2597,6 +2587,21 @@ protected void appendDetail(final StringBuffer buffer, final String fieldName, f appendDetail(buffer, fieldName, valueAsString); } + @Override + protected void appendDetail(final StringBuffer buffer, final String fieldName, final Collection coll) { + if (coll != null && !coll.isEmpty()) { + buffer.append(getArrayStart()); + int i = 0; + for (final Object item : coll) { + appendDetail(buffer, fieldName, i++, item); + } + buffer.append(getArrayEnd()); + return; + } + + buffer.append(coll); + } + @Override protected void appendDetail(final StringBuffer buffer, final String fieldName, final Map map) { if (map != null && !map.isEmpty()) { diff --git a/src/test/java/org/apache/commons/lang3/builder/DefaultToStringStyleTest.java b/src/test/java/org/apache/commons/lang3/builder/DefaultToStringStyleTest.java index 5fe5e46b1c6..dc8dede392f 100644 --- a/src/test/java/org/apache/commons/lang3/builder/DefaultToStringStyleTest.java +++ b/src/test/java/org/apache/commons/lang3/builder/DefaultToStringStyleTest.java @@ -18,8 +18,8 @@ import static org.junit.jupiter.api.Assertions.assertEquals; -import java.util.ArrayList; -import java.util.HashMap; +import java.util.Arrays; +import java.util.Collections; import org.apache.commons.lang3.builder.ToStringStyleTest.Person; import org.junit.jupiter.api.AfterEach; @@ -71,12 +71,38 @@ public void testObject() { assertEquals(baseStr + "[a=3]", new ToStringBuilder(base).append("a", i3).toString()); assertEquals(baseStr + "[a=3,b=4]", new ToStringBuilder(base).append("a", i3).append("b", i4).toString()); assertEquals(baseStr + "[a=]", new ToStringBuilder(base).append("a", i3, false).toString()); - assertEquals(baseStr + "[a=]", new ToStringBuilder(base).append("a", new ArrayList<>(), false).toString()); - assertEquals(baseStr + "[a=[]]", new ToStringBuilder(base).append("a", new ArrayList<>(), true).toString()); - assertEquals(baseStr + "[a=]", new ToStringBuilder(base).append("a", new HashMap<>(), false).toString()); - assertEquals(baseStr + "[a={}]", new ToStringBuilder(base).append("a", new HashMap<>(), true).toString()); - assertEquals(baseStr + "[a=]", new ToStringBuilder(base).append("a", (Object) new String[0], false).toString()); - assertEquals(baseStr + "[a={}]", new ToStringBuilder(base).append("a", (Object) new String[0], true).toString()); + } + + @Test + public void testCollection() { + final Integer i3 = Integer.valueOf(3); + final Integer i4 = Integer.valueOf(4); + assertEquals(baseStr + "[a=]", new ToStringBuilder(base).append("a", Collections.emptyList(), false).toString()); + assertEquals(baseStr + "[a=[]]", new ToStringBuilder(base).append("a", Collections.emptyList(), true).toString()); + assertEquals(baseStr + "[a=]", new ToStringBuilder(base).append("a", Collections.singletonList(i3), false).toString()); + assertEquals(baseStr + "[a=[3]]", new ToStringBuilder(base).append("a", Collections.singletonList(i3), true).toString()); + assertEquals(baseStr + "[a=]", new ToStringBuilder(base).append("a", Arrays.asList(i3, i4), false).toString()); + assertEquals(baseStr + "[a=[3, 4]]", new ToStringBuilder(base).append("a", Arrays.asList(i3, i4), true).toString()); + } + + @Test + public void testMap() { + assertEquals(baseStr + "[a=]", new ToStringBuilder(base).append("a", Collections.emptyMap(), false).toString()); + assertEquals(baseStr + "[a={}]", new ToStringBuilder(base).append("a", Collections.emptyMap(), true).toString()); + assertEquals(baseStr + "[a=]", new ToStringBuilder(base).append("a", Collections.singletonMap("k", "v"), false).toString()); + assertEquals(baseStr + "[a={k=v}]", new ToStringBuilder(base).append("a", Collections.singletonMap("k", "v"), true).toString()); + } + + @Test + public void testArray() { + final Integer i3 = Integer.valueOf(3); + final Integer i4 = Integer.valueOf(4); + assertEquals(baseStr + "[a=]", new ToStringBuilder(base).append("a", (Object) new Integer[0], false).toString()); + assertEquals(baseStr + "[a={}]", new ToStringBuilder(base).append("a", (Object) new Integer[0], true).toString()); + assertEquals(baseStr + "[a=]", new ToStringBuilder(base).append("a", (Object) new Integer[] {i3}, false).toString()); + assertEquals(baseStr + "[a={3}]", new ToStringBuilder(base).append("a", (Object) new Integer[] {i3}, true).toString()); + assertEquals(baseStr + "[a=]", new ToStringBuilder(base).append("a", (Object) new Integer[] {i3, i4}, false).toString()); + assertEquals(baseStr + "[a={3,4}]", new ToStringBuilder(base).append("a", (Object) new Integer[] {i3, i4}, true).toString()); } @Test diff --git a/src/test/java/org/apache/commons/lang3/builder/MultiLineToStringStyleTest.java b/src/test/java/org/apache/commons/lang3/builder/MultiLineToStringStyleTest.java index bce681dd9fb..41f2794fe77 100644 --- a/src/test/java/org/apache/commons/lang3/builder/MultiLineToStringStyleTest.java +++ b/src/test/java/org/apache/commons/lang3/builder/MultiLineToStringStyleTest.java @@ -18,8 +18,8 @@ import static org.junit.jupiter.api.Assertions.assertEquals; -import java.util.ArrayList; -import java.util.HashMap; +import java.util.Arrays; +import java.util.Collections; import org.apache.commons.lang3.builder.ToStringStyleTest.Person; import org.junit.jupiter.api.AfterEach; @@ -71,12 +71,38 @@ public void testObject() { assertEquals(baseStr + "[" + System.lineSeparator() + " a=3" + System.lineSeparator() + "]", new ToStringBuilder(base).append("a", i3).toString()); assertEquals(baseStr + "[" + System.lineSeparator() + " a=3" + System.lineSeparator() + " b=4" + System.lineSeparator() + "]", new ToStringBuilder(base).append("a", i3).append("b", i4).toString()); assertEquals(baseStr + "[" + System.lineSeparator() + " a=" + System.lineSeparator() + "]", new ToStringBuilder(base).append("a", i3, false).toString()); - assertEquals(baseStr + "[" + System.lineSeparator() + " a=" + System.lineSeparator() + "]", new ToStringBuilder(base).append("a", new ArrayList<>(), false).toString()); - assertEquals(baseStr + "[" + System.lineSeparator() + " a=[]" + System.lineSeparator() + "]", new ToStringBuilder(base).append("a", new ArrayList<>(), true).toString()); - assertEquals(baseStr + "[" + System.lineSeparator() + " a=" + System.lineSeparator() + "]", new ToStringBuilder(base).append("a", new HashMap<>(), false).toString()); - assertEquals(baseStr + "[" + System.lineSeparator() + " a={}" + System.lineSeparator() + "]", new ToStringBuilder(base).append("a", new HashMap<>(), true).toString()); - assertEquals(baseStr + "[" + System.lineSeparator() + " a=" + System.lineSeparator() + "]", new ToStringBuilder(base).append("a", (Object) new String[0], false).toString()); - assertEquals(baseStr + "[" + System.lineSeparator() + " a={}" + System.lineSeparator() + "]", new ToStringBuilder(base).append("a", (Object) new String[0], true).toString()); + } + + @Test + public void testCollection() { + final Integer i3 = Integer.valueOf(3); + final Integer i4 = Integer.valueOf(4); + assertEquals(baseStr + "[" + System.lineSeparator() + " a=" + System.lineSeparator() + "]", new ToStringBuilder(base).append("a", Collections.emptyList(), false).toString()); + assertEquals(baseStr + "[" + System.lineSeparator() + " a=[]" + System.lineSeparator() + "]", new ToStringBuilder(base).append("a", Collections.emptyList(), true).toString()); + assertEquals(baseStr + "[" + System.lineSeparator() + " a=" + System.lineSeparator() + "]", new ToStringBuilder(base).append("a", Collections.singletonList(i3), false).toString()); + assertEquals(baseStr + "[" + System.lineSeparator() + " a=[3]" + System.lineSeparator() + "]", new ToStringBuilder(base).append("a", Collections.singletonList(i3), true).toString()); + assertEquals(baseStr + "[" + System.lineSeparator() + " a=" + System.lineSeparator() + "]", new ToStringBuilder(base).append("a", Arrays.asList(i3, i4), false).toString()); + assertEquals(baseStr + "[" + System.lineSeparator() + " a=[3, 4]" + System.lineSeparator() + "]", new ToStringBuilder(base).append("a", Arrays.asList(i3, i4), true).toString()); + } + + @Test + public void testMap() { + assertEquals(baseStr + "[" + System.lineSeparator() + " a=" + System.lineSeparator() + "]", new ToStringBuilder(base).append("a", Collections.emptyMap(), false).toString()); + assertEquals(baseStr + "[" + System.lineSeparator() + " a={}" + System.lineSeparator() + "]", new ToStringBuilder(base).append("a", Collections.emptyMap(), true).toString()); + assertEquals(baseStr + "[" + System.lineSeparator() + " a=" + System.lineSeparator() + "]", new ToStringBuilder(base).append("a", Collections.singletonMap("k", "v"), false).toString()); + assertEquals(baseStr + "[" + System.lineSeparator() + " a={k=v}" + System.lineSeparator() + "]", new ToStringBuilder(base).append("a", Collections.singletonMap("k", "v"), true).toString()); + } + + @Test + public void testArray() { + final Integer i3 = Integer.valueOf(3); + final Integer i4 = Integer.valueOf(4); + assertEquals(baseStr + "[" + System.lineSeparator() + " a=" + System.lineSeparator() + "]", new ToStringBuilder(base).append("a", (Object) new Integer[0], false).toString()); + assertEquals(baseStr + "[" + System.lineSeparator() + " a={}" + System.lineSeparator() + "]", new ToStringBuilder(base).append("a", (Object) new Integer[0], true).toString()); + assertEquals(baseStr + "[" + System.lineSeparator() + " a=" + System.lineSeparator() + "]", new ToStringBuilder(base).append("a", (Object) new Integer[] {i3}, false).toString()); + assertEquals(baseStr + "[" + System.lineSeparator() + " a={3}" + System.lineSeparator() + "]", new ToStringBuilder(base).append("a", (Object) new Integer[] {i3}, true).toString()); + assertEquals(baseStr + "[" + System.lineSeparator() + " a=" + System.lineSeparator() + "]", new ToStringBuilder(base).append("a", (Object) new Integer[] {i3, i4}, false).toString()); + assertEquals(baseStr + "[" + System.lineSeparator() + " a={3,4}" + System.lineSeparator() + "]", new ToStringBuilder(base).append("a", (Object) new Integer[] {i3, i4}, true).toString()); } @Test diff --git a/src/test/java/org/apache/commons/lang3/builder/NoClassNameToStringStyleTest.java b/src/test/java/org/apache/commons/lang3/builder/NoClassNameToStringStyleTest.java index bd950009b9c..b5c2d927573 100644 --- a/src/test/java/org/apache/commons/lang3/builder/NoClassNameToStringStyleTest.java +++ b/src/test/java/org/apache/commons/lang3/builder/NoClassNameToStringStyleTest.java @@ -18,8 +18,8 @@ import static org.junit.jupiter.api.Assertions.assertEquals; -import java.util.ArrayList; -import java.util.HashMap; +import java.util.Arrays; +import java.util.Collections; import org.apache.commons.lang3.builder.ToStringStyleTest.Person; import org.junit.jupiter.api.AfterEach; @@ -70,12 +70,38 @@ public void testObject() { assertEquals("[a=3]", new ToStringBuilder(base).append("a", i3).toString()); assertEquals("[a=3,b=4]", new ToStringBuilder(base).append("a", i3).append("b", i4).toString()); assertEquals("[a=]", new ToStringBuilder(base).append("a", i3, false).toString()); - assertEquals("[a=]", new ToStringBuilder(base).append("a", new ArrayList<>(), false).toString()); - assertEquals("[a=[]]", new ToStringBuilder(base).append("a", new ArrayList<>(), true).toString()); - assertEquals("[a=]", new ToStringBuilder(base).append("a", new HashMap<>(), false).toString()); - assertEquals("[a={}]", new ToStringBuilder(base).append("a", new HashMap<>(), true).toString()); - assertEquals("[a=]", new ToStringBuilder(base).append("a", (Object) new String[0], false).toString()); - assertEquals("[a={}]", new ToStringBuilder(base).append("a", (Object) new String[0], true).toString()); + } + + @Test + public void testCollection() { + final Integer i3 = Integer.valueOf(3); + final Integer i4 = Integer.valueOf(4); + assertEquals("[a=]", new ToStringBuilder(base).append("a", Collections.emptyList(), false).toString()); + assertEquals("[a=[]]", new ToStringBuilder(base).append("a", Collections.emptyList(), true).toString()); + assertEquals("[a=]", new ToStringBuilder(base).append("a", Collections.singletonList(i3), false).toString()); + assertEquals("[a=[3]]", new ToStringBuilder(base).append("a", Collections.singletonList(i3), true).toString()); + assertEquals("[a=]", new ToStringBuilder(base).append("a", Arrays.asList(i3, i4), false).toString()); + assertEquals("[a=[3, 4]]", new ToStringBuilder(base).append("a", Arrays.asList(i3, i4), true).toString()); + } + + @Test + public void testMap() { + assertEquals("[a=]", new ToStringBuilder(base).append("a", Collections.emptyMap(), false).toString()); + assertEquals("[a={}]", new ToStringBuilder(base).append("a", Collections.emptyMap(), true).toString()); + assertEquals("[a=]", new ToStringBuilder(base).append("a", Collections.singletonMap("k", "v"), false).toString()); + assertEquals("[a={k=v}]", new ToStringBuilder(base).append("a", Collections.singletonMap("k", "v"), true).toString()); + } + + @Test + public void testArray() { + final Integer i3 = Integer.valueOf(3); + final Integer i4 = Integer.valueOf(4); + assertEquals("[a=]", new ToStringBuilder(base).append("a", (Object) new Integer[0], false).toString()); + assertEquals("[a={}]", new ToStringBuilder(base).append("a", (Object) new Integer[0], true).toString()); + assertEquals("[a=]", new ToStringBuilder(base).append("a", (Object) new Integer[] {i3}, false).toString()); + assertEquals("[a={3}]", new ToStringBuilder(base).append("a", (Object) new Integer[] {i3}, true).toString()); + assertEquals("[a=]", new ToStringBuilder(base).append("a", (Object) new Integer[] {i3, i4}, false).toString()); + assertEquals("[a={3,4}]", new ToStringBuilder(base).append("a", (Object) new Integer[] {i3, i4}, true).toString()); } @Test diff --git a/src/test/java/org/apache/commons/lang3/builder/NoFieldNamesToStringStyleTest.java b/src/test/java/org/apache/commons/lang3/builder/NoFieldNamesToStringStyleTest.java index 12caa73f29b..04ac8e67d2a 100644 --- a/src/test/java/org/apache/commons/lang3/builder/NoFieldNamesToStringStyleTest.java +++ b/src/test/java/org/apache/commons/lang3/builder/NoFieldNamesToStringStyleTest.java @@ -18,8 +18,8 @@ import static org.junit.jupiter.api.Assertions.assertEquals; -import java.util.ArrayList; -import java.util.HashMap; +import java.util.Arrays; +import java.util.Collections; import org.apache.commons.lang3.builder.ToStringStyleTest.Person; import org.junit.jupiter.api.AfterEach; @@ -71,12 +71,38 @@ public void testObject() { assertEquals(baseStr + "[3]", new ToStringBuilder(base).append("a", i3).toString()); assertEquals(baseStr + "[3,4]", new ToStringBuilder(base).append("a", i3).append("b", i4).toString()); assertEquals(baseStr + "[]", new ToStringBuilder(base).append("a", i3, false).toString()); - assertEquals(baseStr + "[]", new ToStringBuilder(base).append("a", new ArrayList<>(), false).toString()); - assertEquals(baseStr + "[[]]", new ToStringBuilder(base).append("a", new ArrayList<>(), true).toString()); - assertEquals(baseStr + "[]", new ToStringBuilder(base).append("a", new HashMap<>(), false).toString()); - assertEquals(baseStr + "[{}]", new ToStringBuilder(base).append("a", new HashMap<>(), true).toString()); - assertEquals(baseStr + "[]", new ToStringBuilder(base).append("a", (Object) new String[0], false).toString()); - assertEquals(baseStr + "[{}]", new ToStringBuilder(base).append("a", (Object) new String[0], true).toString()); + } + + @Test + public void testCollection() { + final Integer i3 = Integer.valueOf(3); + final Integer i4 = Integer.valueOf(4); + assertEquals(baseStr + "[]", new ToStringBuilder(base).append("a", Collections.emptyList(), false).toString()); + assertEquals(baseStr + "[[]]", new ToStringBuilder(base).append("a", Collections.emptyList(), true).toString()); + assertEquals(baseStr + "[]", new ToStringBuilder(base).append("a", Collections.singletonList(i3), false).toString()); + assertEquals(baseStr + "[[3]]", new ToStringBuilder(base).append("a", Collections.singletonList(i3), true).toString()); + assertEquals(baseStr + "[]", new ToStringBuilder(base).append("a", Arrays.asList(i3, i4), false).toString()); + assertEquals(baseStr + "[[3, 4]]", new ToStringBuilder(base).append("a", Arrays.asList(i3, i4), true).toString()); + } + + @Test + public void testMap() { + assertEquals(baseStr + "[]", new ToStringBuilder(base).append("a", Collections.emptyMap(), false).toString()); + assertEquals(baseStr + "[{}]", new ToStringBuilder(base).append("a", Collections.emptyMap(), true).toString()); + assertEquals(baseStr + "[]", new ToStringBuilder(base).append("a", Collections.singletonMap("k", "v"), false).toString()); + assertEquals(baseStr + "[{k=v}]", new ToStringBuilder(base).append("a", Collections.singletonMap("k", "v"), true).toString()); + } + + @Test + public void testArray() { + final Integer i3 = Integer.valueOf(3); + final Integer i4 = Integer.valueOf(4); + assertEquals(baseStr + "[]", new ToStringBuilder(base).append("a", (Object) new Integer[0], false).toString()); + assertEquals(baseStr + "[{}]", new ToStringBuilder(base).append("a", (Object) new Integer[0], true).toString()); + assertEquals(baseStr + "[]", new ToStringBuilder(base).append("a", (Object) new Integer[] {i3}, false).toString()); + assertEquals(baseStr + "[{3}]", new ToStringBuilder(base).append("a", (Object) new Integer[] {i3}, true).toString()); + assertEquals(baseStr + "[]", new ToStringBuilder(base).append("a", (Object) new Integer[] {i3, i4}, false).toString()); + assertEquals(baseStr + "[{3,4}]", new ToStringBuilder(base).append("a", (Object) new Integer[] {i3, i4}, true).toString()); } @Test diff --git a/src/test/java/org/apache/commons/lang3/builder/ShortPrefixToStringStyleTest.java b/src/test/java/org/apache/commons/lang3/builder/ShortPrefixToStringStyleTest.java index c39939f1841..4d60dc4a375 100644 --- a/src/test/java/org/apache/commons/lang3/builder/ShortPrefixToStringStyleTest.java +++ b/src/test/java/org/apache/commons/lang3/builder/ShortPrefixToStringStyleTest.java @@ -18,8 +18,8 @@ import static org.junit.jupiter.api.Assertions.assertEquals; -import java.util.ArrayList; -import java.util.HashMap; +import java.util.Arrays; +import java.util.Collections; import org.apache.commons.lang3.builder.ToStringStyleTest.Person; import org.junit.jupiter.api.AfterEach; @@ -71,12 +71,38 @@ public void testObject() { assertEquals(baseStr + "[a=3]", new ToStringBuilder(base).append("a", i3).toString()); assertEquals(baseStr + "[a=3,b=4]", new ToStringBuilder(base).append("a", i3).append("b", i4).toString()); assertEquals(baseStr + "[a=]", new ToStringBuilder(base).append("a", i3, false).toString()); - assertEquals(baseStr + "[a=]", new ToStringBuilder(base).append("a", new ArrayList<>(), false).toString()); - assertEquals(baseStr + "[a=[]]", new ToStringBuilder(base).append("a", new ArrayList<>(), true).toString()); - assertEquals(baseStr + "[a=]", new ToStringBuilder(base).append("a", new HashMap<>(), false).toString()); - assertEquals(baseStr + "[a={}]", new ToStringBuilder(base).append("a", new HashMap<>(), true).toString()); - assertEquals(baseStr + "[a=]", new ToStringBuilder(base).append("a", (Object) new String[0], false).toString()); - assertEquals(baseStr + "[a={}]", new ToStringBuilder(base).append("a", (Object) new String[0], true).toString()); + } + + @Test + public void testCollection() { + final Integer i3 = Integer.valueOf(3); + final Integer i4 = Integer.valueOf(4); + assertEquals(baseStr + "[a=]", new ToStringBuilder(base).append("a", Collections.emptyList(), false).toString()); + assertEquals(baseStr + "[a=[]]", new ToStringBuilder(base).append("a", Collections.emptyList(), true).toString()); + assertEquals(baseStr + "[a=]", new ToStringBuilder(base).append("a", Collections.singletonList(i3), false).toString()); + assertEquals(baseStr + "[a=[3]]", new ToStringBuilder(base).append("a", Collections.singletonList(i3), true).toString()); + assertEquals(baseStr + "[a=]", new ToStringBuilder(base).append("a", Arrays.asList(i3, i4), false).toString()); + assertEquals(baseStr + "[a=[3, 4]]", new ToStringBuilder(base).append("a", Arrays.asList(i3, i4), true).toString()); + } + + @Test + public void testMap() { + assertEquals(baseStr + "[a=]", new ToStringBuilder(base).append("a", Collections.emptyMap(), false).toString()); + assertEquals(baseStr + "[a={}]", new ToStringBuilder(base).append("a", Collections.emptyMap(), true).toString()); + assertEquals(baseStr + "[a=]", new ToStringBuilder(base).append("a", Collections.singletonMap("k", "v"), false).toString()); + assertEquals(baseStr + "[a={k=v}]", new ToStringBuilder(base).append("a", Collections.singletonMap("k", "v"), true).toString()); + } + + @Test + public void testArray() { + final Integer i3 = Integer.valueOf(3); + final Integer i4 = Integer.valueOf(4); + assertEquals(baseStr + "[a=]", new ToStringBuilder(base).append("a", (Object) new Integer[0], false).toString()); + assertEquals(baseStr + "[a={}]", new ToStringBuilder(base).append("a", (Object) new Integer[0], true).toString()); + assertEquals(baseStr + "[a=]", new ToStringBuilder(base).append("a", (Object) new Integer[] {i3}, false).toString()); + assertEquals(baseStr + "[a={3}]", new ToStringBuilder(base).append("a", (Object) new Integer[] {i3}, true).toString()); + assertEquals(baseStr + "[a=]", new ToStringBuilder(base).append("a", (Object) new Integer[] {i3, i4}, false).toString()); + assertEquals(baseStr + "[a={3,4}]", new ToStringBuilder(base).append("a", (Object) new Integer[] {i3, i4}, true).toString()); } @Test diff --git a/src/test/java/org/apache/commons/lang3/builder/SimpleToStringStyleTest.java b/src/test/java/org/apache/commons/lang3/builder/SimpleToStringStyleTest.java index f44433a2247..edc8ed9acd8 100644 --- a/src/test/java/org/apache/commons/lang3/builder/SimpleToStringStyleTest.java +++ b/src/test/java/org/apache/commons/lang3/builder/SimpleToStringStyleTest.java @@ -18,8 +18,8 @@ import static org.junit.jupiter.api.Assertions.assertEquals; -import java.util.ArrayList; -import java.util.HashMap; +import java.util.Arrays; +import java.util.Collections; import org.apache.commons.lang3.builder.ToStringStyleTest.Person; import org.junit.jupiter.api.AfterEach; @@ -70,12 +70,38 @@ public void testObject() { assertEquals("3", new ToStringBuilder(base).append("a", i3).toString()); assertEquals("3,4", new ToStringBuilder(base).append("a", i3).append("b", i4).toString()); assertEquals("", new ToStringBuilder(base).append("a", i3, false).toString()); - assertEquals("", new ToStringBuilder(base).append("a", new ArrayList<>(), false).toString()); - assertEquals("[]", new ToStringBuilder(base).append("a", new ArrayList<>(), true).toString()); - assertEquals("", new ToStringBuilder(base).append("a", new HashMap<>(), false).toString()); - assertEquals("{}", new ToStringBuilder(base).append("a", new HashMap<>(), true).toString()); - assertEquals("", new ToStringBuilder(base).append("a", (Object) new String[0], false).toString()); - assertEquals("{}", new ToStringBuilder(base).append("a", (Object) new String[0], true).toString()); + } + + @Test + public void testCollection() { + final Integer i3 = Integer.valueOf(3); + final Integer i4 = Integer.valueOf(4); + assertEquals("", new ToStringBuilder(base).append("a", Collections.emptyList(), false).toString()); + assertEquals("[]", new ToStringBuilder(base).append("a", Collections.emptyList(), true).toString()); + assertEquals("", new ToStringBuilder(base).append("a", Collections.singletonList(i3), false).toString()); + assertEquals("[3]", new ToStringBuilder(base).append("a", Collections.singletonList(i3), true).toString()); + assertEquals("", new ToStringBuilder(base).append("a", Arrays.asList(i3, i4), false).toString()); + assertEquals("[3, 4]", new ToStringBuilder(base).append("a", Arrays.asList(i3, i4), true).toString()); + } + + @Test + public void testMap() { + assertEquals("", new ToStringBuilder(base).append("a", Collections.emptyMap(), false).toString()); + assertEquals("{}", new ToStringBuilder(base).append("a", Collections.emptyMap(), true).toString()); + assertEquals("", new ToStringBuilder(base).append("a", Collections.singletonMap("k", "v"), false).toString()); + assertEquals("{k=v}", new ToStringBuilder(base).append("a", Collections.singletonMap("k", "v"), true).toString()); + } + + @Test + public void testArray() { + final Integer i3 = Integer.valueOf(3); + final Integer i4 = Integer.valueOf(4); + assertEquals("", new ToStringBuilder(base).append("a", (Object) new Integer[0], false).toString()); + assertEquals("{}", new ToStringBuilder(base).append("a", (Object) new Integer[0], true).toString()); + assertEquals("", new ToStringBuilder(base).append("a", (Object) new Integer[]{i3}, false).toString()); + assertEquals("{3}", new ToStringBuilder(base).append("a", (Object) new Integer[]{i3}, true).toString()); + assertEquals("", new ToStringBuilder(base).append("a", (Object) new Integer[]{i3, i4}, false).toString()); + assertEquals("{3,4}", new ToStringBuilder(base).append("a", (Object) new Integer[]{i3, i4}, true).toString()); } @Test diff --git a/src/test/java/org/apache/commons/lang3/builder/StandardToStringStyleTest.java b/src/test/java/org/apache/commons/lang3/builder/StandardToStringStyleTest.java index 8e8ebe0e069..cdca05ee632 100644 --- a/src/test/java/org/apache/commons/lang3/builder/StandardToStringStyleTest.java +++ b/src/test/java/org/apache/commons/lang3/builder/StandardToStringStyleTest.java @@ -20,8 +20,8 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.util.ArrayList; -import java.util.HashMap; +import java.util.Arrays; +import java.util.Collections; import org.apache.commons.lang3.builder.ToStringStyleTest.Person; import org.junit.jupiter.api.AfterEach; @@ -88,12 +88,38 @@ public void testObject() { assertEquals(baseStr + "[a=3]", new ToStringBuilder(base).append("a", i3).toString()); assertEquals(baseStr + "[a=3,b=4]", new ToStringBuilder(base).append("a", i3).append("b", i4).toString()); assertEquals(baseStr + "[a=%Integer%]", new ToStringBuilder(base).append("a", i3, false).toString()); - assertEquals(baseStr + "[a=%SIZE=0%]", new ToStringBuilder(base).append("a", new ArrayList<>(), false).toString()); - assertEquals(baseStr + "[a=[]]", new ToStringBuilder(base).append("a", new ArrayList<>(), true).toString()); - assertEquals(baseStr + "[a=%SIZE=0%]", new ToStringBuilder(base).append("a", new HashMap<>(), false).toString()); - assertEquals(baseStr + "[a={}]", new ToStringBuilder(base).append("a", new HashMap<>(), true).toString()); - assertEquals(baseStr + "[a=%SIZE=0%]", new ToStringBuilder(base).append("a", (Object) new String[0], false).toString()); - assertEquals(baseStr + "[a=[]]", new ToStringBuilder(base).append("a", (Object) new String[0], true).toString()); + } + + @Test + public void testCollection() { + final Integer i3 = Integer.valueOf(3); + final Integer i4 = Integer.valueOf(4); + assertEquals(baseStr + "[a=%SIZE=0%]", new ToStringBuilder(base).append("a", Collections.emptyList(), false).toString()); + assertEquals(baseStr + "[a=[]]", new ToStringBuilder(base).append("a", Collections.emptyList(), true).toString()); + assertEquals(baseStr + "[a=%SIZE=1%]", new ToStringBuilder(base).append("a", Collections.singletonList(i3), false).toString()); + assertEquals(baseStr + "[a=[3]]", new ToStringBuilder(base).append("a", Collections.singletonList(i3), true).toString()); + assertEquals(baseStr + "[a=%SIZE=2%]", new ToStringBuilder(base).append("a", Arrays.asList(i3, i4), false).toString()); + assertEquals(baseStr + "[a=[3, 4]]", new ToStringBuilder(base).append("a", Arrays.asList(i3, i4), true).toString()); + } + + @Test + public void testMap() { + assertEquals(baseStr + "[a=%SIZE=0%]", new ToStringBuilder(base).append("a", Collections.emptyMap(), false).toString()); + assertEquals(baseStr + "[a={}]", new ToStringBuilder(base).append("a", Collections.emptyMap(), true).toString()); + assertEquals(baseStr + "[a=%SIZE=1%]", new ToStringBuilder(base).append("a", Collections.singletonMap("k", "v"), false).toString()); + assertEquals(baseStr + "[a={k=v}]", new ToStringBuilder(base).append("a", Collections.singletonMap("k", "v"), true).toString()); + } + + @Test + public void testArray() { + final Integer i3 = Integer.valueOf(3); + final Integer i4 = Integer.valueOf(4); + assertEquals(baseStr + "[a=%SIZE=0%]", new ToStringBuilder(base).append("a", (Object) new Integer[0], false).toString()); + assertEquals(baseStr + "[a=[]]", new ToStringBuilder(base).append("a", (Object) new Integer[0], true).toString()); + assertEquals(baseStr + "[a=%SIZE=1%]", new ToStringBuilder(base).append("a", (Object) new Integer[] {i3}, false).toString()); + assertEquals(baseStr + "[a=[3]]", new ToStringBuilder(base).append("a", (Object) new Integer[] {i3}, true).toString()); + assertEquals(baseStr + "[a=%SIZE=2%]", new ToStringBuilder(base).append("a", (Object) new Integer[] {i3, i4}, false).toString()); + assertEquals(baseStr + "[a=[3, 4]]", new ToStringBuilder(base).append("a", (Object) new Integer[] {i3, i4}, true).toString()); } @Test From 81efeaacadbdb541715edf13751df791c3892fb5 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sun, 30 Aug 2020 18:29:54 -0400 Subject: [PATCH 0345/3230] [LANG-1600] Restore handling of collections for non-JSON ToStringStyle #610. --- src/changes/changes.xml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index c0b479d3729..f83aff54d9f 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -46,7 +46,10 @@ The type attribute can be add,update,fix,remove. + Correct implementation of RandomUtils.nextLong(long, long) + Restore handling of collections for non-JSON ToStringStyle #610. + Remove redundant argument from substring call. Improve StringUtils.stripAccents conversion of remaining accents. ArrayUtils.toPrimitive(Object) does not support boolean and other types #607. From ddac01fc9a00d8b70b7a679c0abd89dc861573d6 Mon Sep 17 00:00:00 2001 From: iamchao1129 Date: Mon, 31 Aug 2020 06:31:34 +0800 Subject: [PATCH 0346/3230] Add semicolon (#581) Co-authored-by: zhangchao36 --- .../org/apache/commons/lang3/exception/ContextedException.java | 2 +- .../commons/lang3/exception/ContextedRuntimeException.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/exception/ContextedException.java b/src/main/java/org/apache/commons/lang3/exception/ContextedException.java index 02b2b225b5d..1a6825d0114 100644 --- a/src/main/java/org/apache/commons/lang3/exception/ContextedException.java +++ b/src/main/java/org/apache/commons/lang3/exception/ContextedException.java @@ -45,7 +45,7 @@ * throw new ContextedException("Error posting account transaction", e) * .addContextValue("Account Number", accountNumber) * .addContextValue("Amount Posted", amountPosted) - * .addContextValue("Previous Balance", previousBalance) + * .addContextValue("Previous Balance", previousBalance); * } * } * diff --git a/src/main/java/org/apache/commons/lang3/exception/ContextedRuntimeException.java b/src/main/java/org/apache/commons/lang3/exception/ContextedRuntimeException.java index 12db259dc3a..394b070f2b3 100644 --- a/src/main/java/org/apache/commons/lang3/exception/ContextedRuntimeException.java +++ b/src/main/java/org/apache/commons/lang3/exception/ContextedRuntimeException.java @@ -45,7 +45,7 @@ * throw new ContextedRuntimeException("Error posting account transaction", e) * .addContextValue("Account Number", accountNumber) * .addContextValue("Amount Posted", amountPosted) - * .addContextValue("Previous Balance", previousBalance) + * .addContextValue("Previous Balance", previousBalance); * } * } * From 3621a65051f8c93059b113037cdf0a0ed32c9088 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sun, 30 Aug 2020 18:33:34 -0400 Subject: [PATCH 0347/3230] ContextedException Javadoc add missing semicolon #581. --- src/changes/changes.xml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index f83aff54d9f..cc64952ba45 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -48,7 +48,8 @@ The type attribute can be add,update,fix,remove. Correct implementation of RandomUtils.nextLong(long, long) - Restore handling of collections for non-JSON ToStringStyle #610. + Restore handling of collections for non-JSON ToStringStyle #610. + ContextedException Javadoc add missing semicolon #581. Remove redundant argument from substring call. Improve StringUtils.stripAccents conversion of remaining accents. From 649dedbbe8b6ab61fb3c4792c86b7e0af7ec4a73 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Mon, 31 Aug 2020 21:25:40 -0400 Subject: [PATCH 0348/3230] Trigger a GitHub build on pull requests. --- .github/workflows/maven.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml index 0b867fc7d85..d99ca79bace 100644 --- a/.github/workflows/maven.yml +++ b/.github/workflows/maven.yml @@ -15,7 +15,7 @@ name: Java CI -on: [push] +on: [push, pull_request] jobs: build: From af95fdaa2d9765baaa4b809034a53b2e523b789c Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 8 Sep 2020 11:46:04 -0400 Subject: [PATCH 0349/3230] Bump checkstyle from 8.35 to 8.36 (#614) Bumps [checkstyle](https://github.com/checkstyle/checkstyle) from 8.35 to 8.36. - [Release notes](https://github.com/checkstyle/checkstyle/releases) - [Commits](https://github.com/checkstyle/checkstyle/compare/checkstyle-8.35...checkstyle-8.36) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 37fd96ee42a..ad1e6e81ea6 100644 --- a/pom.xml +++ b/pom.xml @@ -603,7 +603,7 @@ utf-8 3.1.1 - 8.35 + 8.36 src/site/resources/checkstyle 4.0.4 From 0054e51500f1f39135bd691a7d80a76f32a9f3fb Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Tue, 8 Sep 2020 11:47:02 -0400 Subject: [PATCH 0350/3230] checkstyle from 8.35 to 8.36 #614. --- src/changes/changes.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index cc64952ba45..f876ca4e6bb 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -58,7 +58,7 @@ The type attribute can be add,update,fix,remove. Update spotbugs-maven-plugin from 4.0.0 to 4.1.2, #593, #596, #609. Update biz.aQute.bndlib from 5.1.1 to 5.1.2 #592. Update junit-pioneer from 0.6.0 to 0.9.0, #589, #597, #600. - Update checkstyle from 8.34 to 8.35 #594. + Update checkstyle from 8.34 to 8.36 #594, #614. Update actions/checkout from v2.3.1 to v2.3.2 #601. Update actions/setup-java from v1.4.0 to v1.4.2 #612. From 38a9209456be83a4ec65e7c69993ddb8748145be Mon Sep 17 00:00:00 2001 From: Sebb Date: Sat, 12 Sep 2020 23:23:18 +0100 Subject: [PATCH 0351/3230] LANG-1606 StringUtils.countMatches - fix Javadoc --- src/changes/changes.xml | 1 + src/main/java/org/apache/commons/lang3/StringUtils.java | 4 +++- .../apache/commons/lang3/StringUtilsSubstringTest.java | 8 ++++++++ 3 files changed, 12 insertions(+), 1 deletion(-) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index f876ca4e6bb..25d0ee02b5b 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -51,6 +51,7 @@ The type attribute can be add,update,fix,remove. Restore handling of collections for non-JSON ToStringStyle #610. ContextedException Javadoc add missing semicolon #581. + StringUtils.countMatches - clarify Javadoc. Remove redundant argument from substring call. Improve StringUtils.stripAccents conversion of remaining accents. ArrayUtils.toPrimitive(Object) does not support boolean and other types #607. diff --git a/src/main/java/org/apache/commons/lang3/StringUtils.java b/src/main/java/org/apache/commons/lang3/StringUtils.java index a93d34a7ff6..0949398adbc 100644 --- a/src/main/java/org/apache/commons/lang3/StringUtils.java +++ b/src/main/java/org/apache/commons/lang3/StringUtils.java @@ -1425,7 +1425,8 @@ public static int countMatches(final CharSequence str, final char ch) { // Count matches //----------------------------------------------------------------------- /** - *

      Counts how many times the substring appears in the larger string.

      + *

      Counts how many times the substring appears in the larger string. + * Note that the code only counts non-overlapping matches.

      * *

      A {@code null} or empty ("") String input returns {@code 0}.

      * @@ -1437,6 +1438,7 @@ public static int countMatches(final CharSequence str, final char ch) { * StringUtils.countMatches("abba", "a") = 2 * StringUtils.countMatches("abba", "ab") = 1 * StringUtils.countMatches("abba", "xxx") = 0 + * StringUtils.countMatches("ababa", "aba") = 1 * * * @param str the CharSequence to check, may be null diff --git a/src/test/java/org/apache/commons/lang3/StringUtilsSubstringTest.java b/src/test/java/org/apache/commons/lang3/StringUtilsSubstringTest.java index 9a1c014fe61..d876d7c9452 100644 --- a/src/test/java/org/apache/commons/lang3/StringUtilsSubstringTest.java +++ b/src/test/java/org/apache/commons/lang3/StringUtilsSubstringTest.java @@ -349,6 +349,14 @@ public void testCountMatches_String() { StringUtils.countMatches("one long someone sentence of one", "two")); assertEquals(4, StringUtils.countMatches("oooooooooooo", "ooo")); + assertEquals(0, StringUtils.countMatches(null, "?")); + assertEquals(0, StringUtils.countMatches("", "?")); + assertEquals(0, StringUtils.countMatches("abba", null)); + assertEquals(0, StringUtils.countMatches("abba", "")); + assertEquals(2, StringUtils.countMatches("abba", "a")); + assertEquals(1, StringUtils.countMatches("abba", "ab")); + assertEquals(0, StringUtils.countMatches("abba", "xxx")); + assertEquals(1, StringUtils.countMatches("ababa", "aba")); } @Test From 7ab21126a07ad438841e30da7875553866c79fd6 Mon Sep 17 00:00:00 2001 From: Sebb Date: Sat, 12 Sep 2020 23:31:44 +0100 Subject: [PATCH 0352/3230] Docs --- src/main/java/org/apache/commons/lang3/StringUtils.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/StringUtils.java b/src/main/java/org/apache/commons/lang3/StringUtils.java index 0949398adbc..5e3a9a23bbf 100644 --- a/src/main/java/org/apache/commons/lang3/StringUtils.java +++ b/src/main/java/org/apache/commons/lang3/StringUtils.java @@ -869,7 +869,7 @@ public static int compare(final String str1, final String str2) { * @since 3.5 */ public static int compare(final String str1, final String str2, final boolean nullIsLess) { - if (str1 == str2) { + if (str1 == str2) { // NOSONARLINT this intentionally uses == to allow for both null return 0; } if (str1 == null) { @@ -962,7 +962,7 @@ public static int compareIgnoreCase(final String str1, final String str2) { * @since 3.5 */ public static int compareIgnoreCase(final String str1, final String str2, final boolean nullIsLess) { - if (str1 == str2) { + if (str1 == str2) { // NOSONARLINT this intentionally uses == to allow for both null return 0; } if (str1 == null) { From 875d1054c04104a0ce7eecf250a021512fe5f057 Mon Sep 17 00:00:00 2001 From: Sebb Date: Sat, 12 Sep 2020 23:32:56 +0100 Subject: [PATCH 0353/3230] Useless parentheses --- src/main/java/org/apache/commons/lang3/StringUtils.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/apache/commons/lang3/StringUtils.java b/src/main/java/org/apache/commons/lang3/StringUtils.java index 5e3a9a23bbf..71dcd5a3c26 100644 --- a/src/main/java/org/apache/commons/lang3/StringUtils.java +++ b/src/main/java/org/apache/commons/lang3/StringUtils.java @@ -2252,7 +2252,7 @@ public static double getJaroWinklerDistance(final CharSequence first, final Char if (m == 0) { return 0D; } - final double j = ((m / first.length() + m / second.length() + (m - mtp[1]) / m)) / 3; + final double j = (m / first.length() + m / second.length() + (m - mtp[1]) / m) / 3; final double jw = j < 0.7D ? j : j + Math.min(DEFAULT_SCALING_FACTOR, 1D / mtp[3]) * mtp[2] * (1D - j); return Math.round(jw * 100.0D) / 100.0D; } From 693e5129e80843bfaba82720fe29299196372928 Mon Sep 17 00:00:00 2001 From: Sebb Date: Sat, 12 Sep 2020 23:34:29 +0100 Subject: [PATCH 0354/3230] Useless assignment --- src/main/java/org/apache/commons/lang3/StringUtils.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/org/apache/commons/lang3/StringUtils.java b/src/main/java/org/apache/commons/lang3/StringUtils.java index 71dcd5a3c26..06de23625dc 100644 --- a/src/main/java/org/apache/commons/lang3/StringUtils.java +++ b/src/main/java/org/apache/commons/lang3/StringUtils.java @@ -6781,7 +6781,6 @@ private static String replaceEach( textIndex = -1; replaceIndex = -1; - tempIndex = -1; // find the next earliest match // NOTE: logic mostly duplicated above START for (int i = 0; i < searchLength; i++) { From 433700ea801e5ec01c6ac2d3a48e872684c9ba77 Mon Sep 17 00:00:00 2001 From: Sebb Date: Sat, 12 Sep 2020 23:37:12 +0100 Subject: [PATCH 0355/3230] One per line --- src/main/java/org/apache/commons/lang3/StringUtils.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/StringUtils.java b/src/main/java/org/apache/commons/lang3/StringUtils.java index 06de23625dc..6956226a222 100644 --- a/src/main/java/org/apache/commons/lang3/StringUtils.java +++ b/src/main/java/org/apache/commons/lang3/StringUtils.java @@ -5393,7 +5393,8 @@ public static String lowerCase(final String str, final Locale locale) { } private static int[] matches(final CharSequence first, final CharSequence second) { - CharSequence max, min; + CharSequence max; + CharSequence min; if (first.length() > second.length()) { max = first; min = second; @@ -8430,7 +8431,7 @@ public static String stripToNull(String str) { return null; } str = strip(str, null); - return str.isEmpty() ? null : str; + return str.isEmpty() ? null : str; // NOSONARLINT str cannot be null here } // Substring From 4b5f1cf57dee74a23a6cb942b0acaa73150edc99 Mon Sep 17 00:00:00 2001 From: Sebb Date: Sat, 12 Sep 2020 23:38:51 +0100 Subject: [PATCH 0356/3230] One per line --- src/main/java/org/apache/commons/lang3/StringUtils.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/StringUtils.java b/src/main/java/org/apache/commons/lang3/StringUtils.java index 6956226a222..3089082778e 100644 --- a/src/main/java/org/apache/commons/lang3/StringUtils.java +++ b/src/main/java/org/apache/commons/lang3/StringUtils.java @@ -7907,7 +7907,8 @@ private static String[] splitWorker(final String str, final char separatorChar, return ArrayUtils.EMPTY_STRING_ARRAY; } final List list = new ArrayList<>(); - int i = 0, start = 0; + int i = 0; + int start = 0; boolean match = false; boolean lastMatch = false; while (i < len) { @@ -7958,7 +7959,8 @@ private static String[] splitWorker(final String str, final String separatorChar } final List list = new ArrayList<>(); int sizePlus1 = 1; - int i = 0, start = 0; + int i = 0; + int start = 0; boolean match = false; boolean lastMatch = false; if (separatorChars == null) { From a498962a0bf5d36a60ce17fdd2720607e97689c9 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 14 Sep 2020 05:53:45 +0000 Subject: [PATCH 0357/3230] Bump junit-jupiter from 5.6.2 to 5.7.0 Bumps [junit-jupiter](https://github.com/junit-team/junit5) from 5.6.2 to 5.7.0. - [Release notes](https://github.com/junit-team/junit5/releases) - [Commits](https://github.com/junit-team/junit5/compare/r5.6.2...r5.7.0) Signed-off-by: dependabot[bot] --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index ad1e6e81ea6..506c5c3db99 100644 --- a/pom.xml +++ b/pom.xml @@ -519,7 +519,7 @@ org.junit.jupiter junit-jupiter - 5.6.2 + 5.7.0 test From 8e0a8f2298315e977b206c437ef5dcf65fe545a8 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sat, 19 Sep 2020 15:46:59 -0400 Subject: [PATCH 0358/3230] Replace Java 14 with Java 15 as the latest Java version to test. Use Jaav 16 EA as the EA version to test. --- .github/workflows/maven.yml | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml index d99ca79bace..5f89c7c8060 100644 --- a/.github/workflows/maven.yml +++ b/.github/workflows/maven.yml @@ -24,11 +24,9 @@ jobs: continue-on-error: ${{ matrix.experimental }} strategy: matrix: - java: [ 8, 11, 14 ] + java: [ 8, 11, 15 ] experimental: [false] include: - - java: 15-ea - experimental: true - java: 16-ea experimental: true From bae0e42fac5c2d7e7b4cb73b6f5552e7a60a1055 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sat, 19 Sep 2020 16:05:16 -0400 Subject: [PATCH 0359/3230] Update commons.jacoco.version 0.8.5 to 0.8.6 (Fixes Java 15 builds). --- pom.xml | 2 +- src/changes/changes.xml | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index ad1e6e81ea6..e3c2f7042fd 100644 --- a/pom.xml +++ b/pom.xml @@ -615,7 +615,7 @@ 1.21 benchmarks - 0.8.5 + 0.8.6 3.0.0-M5 3.2.0 diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 25d0ee02b5b..90fa7f55410 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -62,6 +62,7 @@ The type attribute can be add,update,fix,remove. Update checkstyle from 8.34 to 8.36 #594, #614. Update actions/checkout from v2.3.1 to v2.3.2 #601. Update actions/setup-java from v1.4.0 to v1.4.2 #612. + Update commons.jacoco.version 0.8.5 to 0.8.6 (Fixes Java 15 builds).
      Refine test output for FastDateParserTest From 4a5cfd336855bbda6d69ca2355a40cefdbaf74b3 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 24 Sep 2020 05:53:46 +0000 Subject: [PATCH 0360/3230] Bump actions/checkout from v2.3.2 to v2.3.3 Bumps [actions/checkout](https://github.com/actions/checkout) from v2.3.2 to v2.3.3. - [Release notes](https://github.com/actions/checkout/releases) - [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md) - [Commits](https://github.com/actions/checkout/compare/v2.3.2...a81bbbf8298c0fa03ea29cdc473d45769f953675) Signed-off-by: dependabot[bot] --- .github/workflows/maven.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml index 5f89c7c8060..35dcb38a79d 100644 --- a/.github/workflows/maven.yml +++ b/.github/workflows/maven.yml @@ -31,7 +31,7 @@ jobs: experimental: true steps: - - uses: actions/checkout@v2.3.2 + - uses: actions/checkout@v2.3.3 - uses: actions/cache@v2 with: path: ~/.m2/repository From 101e988aabc6b213535426aa343cc194613b5035 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 25 Sep 2020 05:50:12 +0000 Subject: [PATCH 0361/3230] Bump spotbugs from 4.1.2 to 4.1.3 Bumps [spotbugs](https://github.com/spotbugs/spotbugs) from 4.1.2 to 4.1.3. - [Release notes](https://github.com/spotbugs/spotbugs/releases) - [Changelog](https://github.com/spotbugs/spotbugs/blob/master/CHANGELOG.md) - [Commits](https://github.com/spotbugs/spotbugs/compare/4.1.2...4.1.3) Signed-off-by: dependabot[bot] --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index e3c2f7042fd..1017495ee39 100644 --- a/pom.xml +++ b/pom.xml @@ -607,7 +607,7 @@ src/site/resources/checkstyle 4.0.4 - 4.1.2 + 4.1.3 false true From 98e7ea68cec0b03acd08f28d0c67d7698f03af60 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 28 Sep 2020 06:32:08 +0000 Subject: [PATCH 0362/3230] Bump checkstyle from 8.36 to 8.36.2 Bumps [checkstyle](https://github.com/checkstyle/checkstyle) from 8.36 to 8.36.2. - [Release notes](https://github.com/checkstyle/checkstyle/releases) - [Commits](https://github.com/checkstyle/checkstyle/compare/checkstyle-8.36...checkstyle-8.36.2) Signed-off-by: dependabot[bot] --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index e3c2f7042fd..da072d61313 100644 --- a/pom.xml +++ b/pom.xml @@ -603,7 +603,7 @@ utf-8 3.1.1 - 8.36 + 8.36.2 src/site/resources/checkstyle 4.0.4 From 218eae4c3af792c84fd93513ba9870e9759e70c3 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Mon, 28 Sep 2020 15:13:28 -0400 Subject: [PATCH 0363/3230] Sort members. --- .../apache/commons/lang3/BooleanUtils.java | 947 +++++++++--------- 1 file changed, 464 insertions(+), 483 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/BooleanUtils.java b/src/main/java/org/apache/commons/lang3/BooleanUtils.java index 5bfcea29d68..39338538975 100644 --- a/src/main/java/org/apache/commons/lang3/BooleanUtils.java +++ b/src/main/java/org/apache/commons/lang3/BooleanUtils.java @@ -31,78 +31,89 @@ public class BooleanUtils { /** - *

      {@code BooleanUtils} instances should NOT be constructed in standard programming. - * Instead, the class should be used as {@code BooleanUtils.negate(true);}.

      - * - *

      This constructor is public to permit tools that require a JavaBean instance - * to operate.

      - */ - public BooleanUtils() { - super(); - } - - // Boolean utilities - //-------------------------------------------------------------------------- - /** - *

      Negates the specified boolean.

      - * - *

      If {@code null} is passed in, {@code null} will be returned.

      - * - *

      NOTE: This returns {@code null} and will throw a {@code NullPointerException} - * if unboxed to a boolean.

      + *

      Performs an 'and' operation on a set of booleans.

      * *
      -     *   BooleanUtils.negate(Boolean.TRUE)  = Boolean.FALSE;
      -     *   BooleanUtils.negate(Boolean.FALSE) = Boolean.TRUE;
      -     *   BooleanUtils.negate(null)          = null;
      +     *   BooleanUtils.and(true, true)         = true
      +     *   BooleanUtils.and(false, false)       = false
      +     *   BooleanUtils.and(true, false)        = false
      +     *   BooleanUtils.and(true, true, false)  = false
      +     *   BooleanUtils.and(true, true, true)   = true
            * 
      * - * @param bool the Boolean to negate, may be null - * @return the negated Boolean, or {@code null} if {@code null} input + * @param array an array of {@code boolean}s + * @return the result of the logical 'and' operation. That is {@code false} + * if any of the parameters is {@code false} and {@code true} otherwise. + * @throws IllegalArgumentException if {@code array} is {@code null} + * @throws IllegalArgumentException if {@code array} is empty. + * @since 3.0.1 */ - public static Boolean negate(final Boolean bool) { - if (bool == null) { - return null; + public static boolean and(final boolean... array) { + // Validates input + if (array == null) { + throw new IllegalArgumentException("The Array must not be null"); } - return bool.booleanValue() ? Boolean.FALSE : Boolean.TRUE; + if (array.length == 0) { + throw new IllegalArgumentException("Array is empty"); + } + for (final boolean element : array) { + if (!element) { + return false; + } + } + return true; } - // boolean Boolean methods - //----------------------------------------------------------------------- /** - *

      Checks if a {@code Boolean} value is {@code true}, - * handling {@code null} by returning {@code false}.

      + *

      Performs an 'and' operation on an array of Booleans.

      * *
      -     *   BooleanUtils.isTrue(Boolean.TRUE)  = true
      -     *   BooleanUtils.isTrue(Boolean.FALSE) = false
      -     *   BooleanUtils.isTrue(null)          = false
      +     *   BooleanUtils.and(Boolean.TRUE, Boolean.TRUE)                 = Boolean.TRUE
      +     *   BooleanUtils.and(Boolean.FALSE, Boolean.FALSE)               = Boolean.FALSE
      +     *   BooleanUtils.and(Boolean.TRUE, Boolean.FALSE)                = Boolean.FALSE
      +     *   BooleanUtils.and(Boolean.TRUE, Boolean.TRUE, Boolean.TRUE)   = Boolean.TRUE
      +     *   BooleanUtils.and(Boolean.FALSE, Boolean.FALSE, Boolean.TRUE) = Boolean.FALSE
      +     *   BooleanUtils.and(Boolean.TRUE, Boolean.FALSE, Boolean.TRUE)  = Boolean.FALSE
            * 
      * - * @param bool the boolean to check, {@code null} returns {@code false} - * @return {@code true} only if the input is non-null and true - * @since 2.1 + * @param array an array of {@code Boolean}s + * @return the result of the logical 'and' operation. That is {@code false} + * if any of the parameters is {@code false} and {@code true} otherwise. + * @throws IllegalArgumentException if {@code array} is {@code null} + * @throws IllegalArgumentException if {@code array} is empty. + * @throws IllegalArgumentException if {@code array} contains a {@code null} + * @since 3.0.1 */ - public static boolean isTrue(final Boolean bool) { - return Boolean.TRUE.equals(bool); + public static Boolean and(final Boolean... array) { + if (array == null) { + throw new IllegalArgumentException("The Array must not be null"); + } + if (array.length == 0) { + throw new IllegalArgumentException("Array is empty"); + } + try { + final boolean[] primitive = ArrayUtils.toPrimitive(array); + return and(primitive) ? Boolean.TRUE : Boolean.FALSE; + } catch (final NullPointerException ex) { + throw new IllegalArgumentException("The array must not contain any null elements"); + } } /** - *

      Checks if a {@code Boolean} value is not {@code true}, - * handling {@code null} by returning {@code true}.

      - * - *
      -     *   BooleanUtils.isNotTrue(Boolean.TRUE)  = false
      -     *   BooleanUtils.isNotTrue(Boolean.FALSE) = true
      -     *   BooleanUtils.isNotTrue(null)          = true
      -     * 
      + *

      Compares two {@code boolean} values. This is the same functionality as provided in Java 7.

      * - * @param bool the boolean to check, null returns {@code true} - * @return {@code true} if the input is null or false - * @since 2.3 + * @param x the first {@code boolean} to compare + * @param y the second {@code boolean} to compare + * @return the value {@code 0} if {@code x == y}; + * a value less than {@code 0} if {@code !x && y}; and + * a value greater than {@code 0} if {@code x && !y} + * @since 3.4 */ - public static boolean isNotTrue(final Boolean bool) { - return !isTrue(bool); + public static int compare(final boolean x, final boolean y) { + if (x == y) { + return 0; + } + return x ? 1 : -1; } /** @@ -141,109 +152,167 @@ public static boolean isNotFalse(final Boolean bool) { return !isFalse(bool); } - //----------------------------------------------------------------------- /** - *

      Converts a Boolean to a boolean handling {@code null} - * by returning {@code false}.

      + *

      Checks if a {@code Boolean} value is not {@code true}, + * handling {@code null} by returning {@code true}.

      * *
      -     *   BooleanUtils.toBoolean(Boolean.TRUE)  = true
      -     *   BooleanUtils.toBoolean(Boolean.FALSE) = false
      -     *   BooleanUtils.toBoolean(null)          = false
      +     *   BooleanUtils.isNotTrue(Boolean.TRUE)  = false
      +     *   BooleanUtils.isNotTrue(Boolean.FALSE) = true
      +     *   BooleanUtils.isNotTrue(null)          = true
            * 
      * - * @param bool the boolean to convert - * @return {@code true} or {@code false}, {@code null} returns {@code false} + * @param bool the boolean to check, null returns {@code true} + * @return {@code true} if the input is null or false + * @since 2.3 */ - public static boolean toBoolean(final Boolean bool) { - return bool != null && bool.booleanValue(); + public static boolean isNotTrue(final Boolean bool) { + return !isTrue(bool); } /** - *

      Converts a Boolean to a boolean handling {@code null}.

      + *

      Checks if a {@code Boolean} value is {@code true}, + * handling {@code null} by returning {@code false}.

      * *
      -     *   BooleanUtils.toBooleanDefaultIfNull(Boolean.TRUE, false)  = true
      -     *   BooleanUtils.toBooleanDefaultIfNull(Boolean.TRUE, true)   = true
      -     *   BooleanUtils.toBooleanDefaultIfNull(Boolean.FALSE, true)  = false
      -     *   BooleanUtils.toBooleanDefaultIfNull(Boolean.FALSE, false) = false
      -     *   BooleanUtils.toBooleanDefaultIfNull(null, true)           = true
      -     *   BooleanUtils.toBooleanDefaultIfNull(null, false)          = false
      +     *   BooleanUtils.isTrue(Boolean.TRUE)  = true
      +     *   BooleanUtils.isTrue(Boolean.FALSE) = false
      +     *   BooleanUtils.isTrue(null)          = false
            * 
      * - * @param bool the boolean object to convert to primitive - * @param valueIfNull the boolean value to return if the parameter {@code bool} is {@code null} - * @return {@code true} or {@code false} + * @param bool the boolean to check, {@code null} returns {@code false} + * @return {@code true} only if the input is non-null and true + * @since 2.1 */ - public static boolean toBooleanDefaultIfNull(final Boolean bool, final boolean valueIfNull) { + public static boolean isTrue(final Boolean bool) { + return Boolean.TRUE.equals(bool); + } + + /** + *

      Negates the specified boolean.

      + * + *

      If {@code null} is passed in, {@code null} will be returned.

      + * + *

      NOTE: This returns {@code null} and will throw a {@code NullPointerException} + * if unboxed to a boolean.

      + * + *
      +     *   BooleanUtils.negate(Boolean.TRUE)  = Boolean.FALSE;
      +     *   BooleanUtils.negate(Boolean.FALSE) = Boolean.TRUE;
      +     *   BooleanUtils.negate(null)          = null;
      +     * 
      + * + * @param bool the Boolean to negate, may be null + * @return the negated Boolean, or {@code null} if {@code null} input + */ + public static Boolean negate(final Boolean bool) { if (bool == null) { - return valueIfNull; + return null; } - return bool.booleanValue(); + return bool.booleanValue() ? Boolean.FALSE : Boolean.TRUE; } - // Integer to Boolean methods - //----------------------------------------------------------------------- /** - *

      Converts an int to a boolean using the convention that {@code zero} - * is {@code false}, everything else is {@code true}.

      + *

      Performs an 'or' operation on a set of booleans.

      * *
      -     *   BooleanUtils.toBoolean(0) = false
      -     *   BooleanUtils.toBoolean(1) = true
      -     *   BooleanUtils.toBoolean(2) = true
      +     *   BooleanUtils.or(true, true)          = true
      +     *   BooleanUtils.or(false, false)        = false
      +     *   BooleanUtils.or(true, false)         = true
      +     *   BooleanUtils.or(true, true, false)   = true
      +     *   BooleanUtils.or(true, true, true)    = true
      +     *   BooleanUtils.or(false, false, false) = false
            * 
      * - * @param value the int to convert - * @return {@code true} if non-zero, {@code false} - * if zero + * @param array an array of {@code boolean}s + * @return {@code true} if any of the arguments is {@code true}, and it returns {@code false} otherwise. + * @throws IllegalArgumentException if {@code array} is {@code null} + * @throws IllegalArgumentException if {@code array} is empty. + * @since 3.0.1 */ - public static boolean toBoolean(final int value) { - return value != 0; + public static boolean or(final boolean... array) { + if (array == null) { + throw new IllegalArgumentException("The Array must not be null"); + } + if (array.length == 0) { + throw new IllegalArgumentException("Array is empty"); + } + for (final boolean element : array) { + if (element) { + return true; + } + } + return false; } /** - *

      Converts an int to a Boolean using the convention that {@code zero} - * is {@code false}, everything else is {@code true}.

      + *

      Performs an 'or' operation on an array of Booleans.

      * *
      -     *   BooleanUtils.toBoolean(0) = Boolean.FALSE
      -     *   BooleanUtils.toBoolean(1) = Boolean.TRUE
      -     *   BooleanUtils.toBoolean(2) = Boolean.TRUE
      +     *   BooleanUtils.or(Boolean.TRUE, Boolean.TRUE)                  = Boolean.TRUE
      +     *   BooleanUtils.or(Boolean.FALSE, Boolean.FALSE)                = Boolean.FALSE
      +     *   BooleanUtils.or(Boolean.TRUE, Boolean.FALSE)                 = Boolean.TRUE
      +     *   BooleanUtils.or(Boolean.TRUE, Boolean.TRUE, Boolean.TRUE)    = Boolean.TRUE
      +     *   BooleanUtils.or(Boolean.FALSE, Boolean.FALSE, Boolean.TRUE)  = Boolean.TRUE
      +     *   BooleanUtils.or(Boolean.TRUE, Boolean.FALSE, Boolean.TRUE)   = Boolean.TRUE
      +     *   BooleanUtils.or(Boolean.FALSE, Boolean.FALSE, Boolean.FALSE) = Boolean.FALSE
            * 
      * - * @param value the int to convert - * @return Boolean.TRUE if non-zero, Boolean.FALSE if zero, - * {@code null} if {@code null} + * @param array an array of {@code Boolean}s + * @return {@code true} if any of the arguments is {@code true}, and it returns {@code false} otherwise. + * @throws IllegalArgumentException if {@code array} is {@code null} + * @throws IllegalArgumentException if {@code array} is empty. + * @throws IllegalArgumentException if {@code array} contains a {@code null} + * @since 3.0.1 */ - public static Boolean toBooleanObject(final int value) { - return value == 0 ? Boolean.FALSE : Boolean.TRUE; + public static Boolean or(final Boolean... array) { + if (array == null) { + throw new IllegalArgumentException("The Array must not be null"); + } + if (array.length == 0) { + throw new IllegalArgumentException("Array is empty"); + } + try { + final boolean[] primitive = ArrayUtils.toPrimitive(array); + return or(primitive) ? Boolean.TRUE : Boolean.FALSE; + } catch (final NullPointerException ex) { + throw new IllegalArgumentException("The array must not contain any null elements"); + } } /** - *

      Converts an Integer to a Boolean using the convention that {@code zero} - * is {@code false}, every other numeric value is {@code true}.

      + *

      Converts a Boolean to a boolean handling {@code null} + * by returning {@code false}.

      * - *

      {@code null} will be converted to {@code null}.

      + *
      +     *   BooleanUtils.toBoolean(Boolean.TRUE)  = true
      +     *   BooleanUtils.toBoolean(Boolean.FALSE) = false
      +     *   BooleanUtils.toBoolean(null)          = false
      +     * 
      * - *

      NOTE: This method may return {@code null} and may throw a {@code NullPointerException} - * if unboxed to a {@code boolean}.

      + * @param bool the boolean to convert + * @return {@code true} or {@code false}, {@code null} returns {@code false} + */ + public static boolean toBoolean(final Boolean bool) { + return bool != null && bool.booleanValue(); + } + + /** + *

      Converts an int to a boolean using the convention that {@code zero} + * is {@code false}, everything else is {@code true}.

      * *
      -     *   BooleanUtils.toBoolean(Integer.valueOf(0))    = Boolean.FALSE
      -     *   BooleanUtils.toBoolean(Integer.valueOf(1))    = Boolean.TRUE
      -     *   BooleanUtils.toBoolean(Integer.valueOf(null)) = null
      +     *   BooleanUtils.toBoolean(0) = false
      +     *   BooleanUtils.toBoolean(1) = true
      +     *   BooleanUtils.toBoolean(2) = true
            * 
      * - * @param value the Integer to convert - * @return Boolean.TRUE if non-zero, Boolean.FALSE if zero, - * {@code null} if {@code null} input + * @param value the int to convert + * @return {@code true} if non-zero, {@code false} + * if zero */ - public static Boolean toBooleanObject(final Integer value) { - if (value == null) { - return null; - } - return value.intValue() == 0 ? Boolean.FALSE : Boolean.TRUE; + public static boolean toBoolean(final int value) { + return value != 0; } /** @@ -310,6 +379,109 @@ public static boolean toBoolean(final Integer value, final Integer trueValue, fi throw new IllegalArgumentException("The Integer did not match either specified value"); } + /** + *

      Converts a String to a boolean (optimised for performance).

      + * + *

      {@code 'true'}, {@code 'on'}, {@code 'y'}, {@code 't'} or {@code 'yes'} + * (case insensitive) will return {@code true}. Otherwise, + * {@code false} is returned.

      + * + *

      This method performs 4 times faster (JDK1.4) than + * {@code Boolean.valueOf(String)}. However, this method accepts + * 'on' and 'yes', 't', 'y' as true values. + * + *

      +     *   BooleanUtils.toBoolean(null)    = false
      +     *   BooleanUtils.toBoolean("true")  = true
      +     *   BooleanUtils.toBoolean("TRUE")  = true
      +     *   BooleanUtils.toBoolean("tRUe")  = true
      +     *   BooleanUtils.toBoolean("on")    = true
      +     *   BooleanUtils.toBoolean("yes")   = true
      +     *   BooleanUtils.toBoolean("false") = false
      +     *   BooleanUtils.toBoolean("x gti") = false
      +     *   BooleanUtils.toBooleanObject("y") = true
      +     *   BooleanUtils.toBooleanObject("n") = false
      +     *   BooleanUtils.toBooleanObject("t") = true
      +     *   BooleanUtils.toBooleanObject("f") = false
      +     * 
      + * + * @param str the String to check + * @return the boolean value of the string, {@code false} if no match or the String is null + */ + public static boolean toBoolean(final String str) { + return toBooleanObject(str) == Boolean.TRUE; + } + + /** + *

      Converts a String to a Boolean throwing an exception if no match found.

      + * + *
      +     *   BooleanUtils.toBoolean("true", "true", "false")  = true
      +     *   BooleanUtils.toBoolean("false", "true", "false") = false
      +     * 
      + * + * @param str the String to check + * @param trueString the String to match for {@code true} (case sensitive), may be {@code null} + * @param falseString the String to match for {@code false} (case sensitive), may be {@code null} + * @return the boolean value of the string + * @throws IllegalArgumentException if the String doesn't match + */ + public static boolean toBoolean(final String str, final String trueString, final String falseString) { + if (str == trueString) { + return true; + } else if (str == falseString) { + return false; + } else if (str != null) { + if (str.equals(trueString)) { + return true; + } else if (str.equals(falseString)) { + return false; + } + } + throw new IllegalArgumentException("The String did not match either specified value"); + } + + /** + *

      Converts a Boolean to a boolean handling {@code null}.

      + * + *
      +     *   BooleanUtils.toBooleanDefaultIfNull(Boolean.TRUE, false)  = true
      +     *   BooleanUtils.toBooleanDefaultIfNull(Boolean.TRUE, true)   = true
      +     *   BooleanUtils.toBooleanDefaultIfNull(Boolean.FALSE, true)  = false
      +     *   BooleanUtils.toBooleanDefaultIfNull(Boolean.FALSE, false) = false
      +     *   BooleanUtils.toBooleanDefaultIfNull(null, true)           = true
      +     *   BooleanUtils.toBooleanDefaultIfNull(null, false)          = false
      +     * 
      + * + * @param bool the boolean object to convert to primitive + * @param valueIfNull the boolean value to return if the parameter {@code bool} is {@code null} + * @return {@code true} or {@code false} + */ + public static boolean toBooleanDefaultIfNull(final Boolean bool, final boolean valueIfNull) { + if (bool == null) { + return valueIfNull; + } + return bool.booleanValue(); + } + + /** + *

      Converts an int to a Boolean using the convention that {@code zero} + * is {@code false}, everything else is {@code true}.

      + * + *
      +     *   BooleanUtils.toBoolean(0) = Boolean.FALSE
      +     *   BooleanUtils.toBoolean(1) = Boolean.TRUE
      +     *   BooleanUtils.toBoolean(2) = Boolean.TRUE
      +     * 
      + * + * @param value the int to convert + * @return Boolean.TRUE if non-zero, Boolean.FALSE if zero, + * {@code null} if {@code null} + */ + public static Boolean toBooleanObject(final int value) { + return value == 0 ? Boolean.FALSE : Boolean.TRUE; + } + /** *

      Converts an int to a Boolean specifying the conversion values.

      * @@ -345,7 +517,33 @@ public static Boolean toBooleanObject(final int value, final int trueValue, fina if (value == nullValue) { return null; } - throw new IllegalArgumentException("The Integer did not match any specified value"); + throw new IllegalArgumentException("The Integer did not match any specified value"); + } + + /** + *

      Converts an Integer to a Boolean using the convention that {@code zero} + * is {@code false}, every other numeric value is {@code true}.

      + * + *

      {@code null} will be converted to {@code null}.

      + * + *

      NOTE: This method may return {@code null} and may throw a {@code NullPointerException} + * if unboxed to a {@code boolean}.

      + * + *
      +     *   BooleanUtils.toBoolean(Integer.valueOf(0))    = Boolean.FALSE
      +     *   BooleanUtils.toBoolean(Integer.valueOf(1))    = Boolean.TRUE
      +     *   BooleanUtils.toBoolean(Integer.valueOf(null)) = null
      +     * 
      + * + * @param value the Integer to convert + * @return Boolean.TRUE if non-zero, Boolean.FALSE if zero, + * {@code null} if {@code null} input + */ + public static Boolean toBooleanObject(final Integer value) { + if (value == null) { + return null; + } + return value.intValue() == 0 ? Boolean.FALSE : Boolean.TRUE; } /** @@ -394,141 +592,6 @@ public static Boolean toBooleanObject(final Integer value, final Integer trueVal throw new IllegalArgumentException("The Integer did not match any specified value"); } - // Boolean to Integer methods - //----------------------------------------------------------------------- - /** - *

      Converts a boolean to an int using the convention that - * {@code true} is {@code 1} and {@code false} is {@code 0}.

      - * - *
      -     *   BooleanUtils.toInteger(true)  = 1
      -     *   BooleanUtils.toInteger(false) = 0
      -     * 
      - * - * @param bool the boolean to convert - * @return one if {@code true}, zero if {@code false} - */ - public static int toInteger(final boolean bool) { - return bool ? 1 : 0; - } - - /** - *

      Converts a boolean to an Integer using the convention that - * {@code true} is {@code 1} and {@code false} is {@code 0}.

      - * - *
      -     *   BooleanUtils.toIntegerObject(true)  = Integer.valueOf(1)
      -     *   BooleanUtils.toIntegerObject(false) = Integer.valueOf(0)
      -     * 
      - * - * @param bool the boolean to convert - * @return one if {@code true}, zero if {@code false} - */ - public static Integer toIntegerObject(final boolean bool) { - return bool ? NumberUtils.INTEGER_ONE : NumberUtils.INTEGER_ZERO; - } - - /** - *

      Converts a Boolean to a Integer using the convention that - * {@code zero} is {@code false}.

      - * - *

      {@code null} will be converted to {@code null}.

      - * - *
      -     *   BooleanUtils.toIntegerObject(Boolean.TRUE)  = Integer.valueOf(1)
      -     *   BooleanUtils.toIntegerObject(Boolean.FALSE) = Integer.valueOf(0)
      -     * 
      - * - * @param bool the Boolean to convert - * @return one if Boolean.TRUE, zero if Boolean.FALSE, {@code null} if {@code null} - */ - public static Integer toIntegerObject(final Boolean bool) { - if (bool == null) { - return null; - } - return bool.booleanValue() ? NumberUtils.INTEGER_ONE : NumberUtils.INTEGER_ZERO; - } - - /** - *

      Converts a boolean to an int specifying the conversion values.

      - * - *
      -     *   BooleanUtils.toInteger(true, 1, 0)  = 1
      -     *   BooleanUtils.toInteger(false, 1, 0) = 0
      -     * 
      - * - * @param bool the to convert - * @param trueValue the value to return if {@code true} - * @param falseValue the value to return if {@code false} - * @return the appropriate value - */ - public static int toInteger(final boolean bool, final int trueValue, final int falseValue) { - return bool ? trueValue : falseValue; - } - - /** - *

      Converts a Boolean to an int specifying the conversion values.

      - * - *
      -     *   BooleanUtils.toInteger(Boolean.TRUE, 1, 0, 2)  = 1
      -     *   BooleanUtils.toInteger(Boolean.FALSE, 1, 0, 2) = 0
      -     *   BooleanUtils.toInteger(null, 1, 0, 2)          = 2
      -     * 
      - * - * @param bool the Boolean to convert - * @param trueValue the value to return if {@code true} - * @param falseValue the value to return if {@code false} - * @param nullValue the value to return if {@code null} - * @return the appropriate value - */ - public static int toInteger(final Boolean bool, final int trueValue, final int falseValue, final int nullValue) { - if (bool == null) { - return nullValue; - } - return bool.booleanValue() ? trueValue : falseValue; - } - - /** - *

      Converts a boolean to an Integer specifying the conversion values.

      - * - *
      -     *   BooleanUtils.toIntegerObject(true, Integer.valueOf(1), Integer.valueOf(0))  = Integer.valueOf(1)
      -     *   BooleanUtils.toIntegerObject(false, Integer.valueOf(1), Integer.valueOf(0)) = Integer.valueOf(0)
      -     * 
      - * - * @param bool the to convert - * @param trueValue the value to return if {@code true}, may be {@code null} - * @param falseValue the value to return if {@code false}, may be {@code null} - * @return the appropriate value - */ - public static Integer toIntegerObject(final boolean bool, final Integer trueValue, final Integer falseValue) { - return bool ? trueValue : falseValue; - } - - /** - *

      Converts a Boolean to an Integer specifying the conversion values.

      - * - *
      -     *   BooleanUtils.toIntegerObject(Boolean.TRUE, Integer.valueOf(1), Integer.valueOf(0), Integer.valueOf(2))  = Integer.valueOf(1)
      -     *   BooleanUtils.toIntegerObject(Boolean.FALSE, Integer.valueOf(1), Integer.valueOf(0), Integer.valueOf(2)) = Integer.valueOf(0)
      -     *   BooleanUtils.toIntegerObject(null, Integer.valueOf(1), Integer.valueOf(0), Integer.valueOf(2))          = Integer.valueOf(2)
      -     * 
      - * - * @param bool the Boolean to convert - * @param trueValue the value to return if {@code true}, may be {@code null} - * @param falseValue the value to return if {@code false}, may be {@code null} - * @param nullValue the value to return if {@code null}, may be {@code null} - * @return the appropriate value - */ - public static Integer toIntegerObject(final Boolean bool, final Integer trueValue, final Integer falseValue, final Integer nullValue) { - if (bool == null) { - return nullValue; - } - return bool.booleanValue() ? trueValue : falseValue; - } - - // String to Boolean methods - //----------------------------------------------------------------------- /** *

      Converts a String to a Boolean.

      * @@ -706,121 +769,152 @@ public static Boolean toBooleanObject(final String str, final String trueString, throw new IllegalArgumentException("The String did not match any specified value"); } - // String to boolean methods - //----------------------------------------------------------------------- /** - *

      Converts a String to a boolean (optimised for performance).

      + *

      Converts a boolean to an int using the convention that + * {@code true} is {@code 1} and {@code false} is {@code 0}.

      * - *

      {@code 'true'}, {@code 'on'}, {@code 'y'}, {@code 't'} or {@code 'yes'} - * (case insensitive) will return {@code true}. Otherwise, - * {@code false} is returned.

      + *
      +     *   BooleanUtils.toInteger(true)  = 1
      +     *   BooleanUtils.toInteger(false) = 0
      +     * 
      * - *

      This method performs 4 times faster (JDK1.4) than - * {@code Boolean.valueOf(String)}. However, this method accepts - * 'on' and 'yes', 't', 'y' as true values. + * @param bool the boolean to convert + * @return one if {@code true}, zero if {@code false} + */ + public static int toInteger(final boolean bool) { + return bool ? 1 : 0; + } + + /** + *

      Converts a boolean to an int specifying the conversion values.

      * *
      -     *   BooleanUtils.toBoolean(null)    = false
      -     *   BooleanUtils.toBoolean("true")  = true
      -     *   BooleanUtils.toBoolean("TRUE")  = true
      -     *   BooleanUtils.toBoolean("tRUe")  = true
      -     *   BooleanUtils.toBoolean("on")    = true
      -     *   BooleanUtils.toBoolean("yes")   = true
      -     *   BooleanUtils.toBoolean("false") = false
      -     *   BooleanUtils.toBoolean("x gti") = false
      -     *   BooleanUtils.toBooleanObject("y") = true
      -     *   BooleanUtils.toBooleanObject("n") = false
      -     *   BooleanUtils.toBooleanObject("t") = true
      -     *   BooleanUtils.toBooleanObject("f") = false
      +     *   BooleanUtils.toInteger(true, 1, 0)  = 1
      +     *   BooleanUtils.toInteger(false, 1, 0) = 0
            * 
      * - * @param str the String to check - * @return the boolean value of the string, {@code false} if no match or the String is null + * @param bool the to convert + * @param trueValue the value to return if {@code true} + * @param falseValue the value to return if {@code false} + * @return the appropriate value */ - public static boolean toBoolean(final String str) { - return toBooleanObject(str) == Boolean.TRUE; + public static int toInteger(final boolean bool, final int trueValue, final int falseValue) { + return bool ? trueValue : falseValue; } /** - *

      Converts a String to a Boolean throwing an exception if no match found.

      + *

      Converts a Boolean to an int specifying the conversion values.

      * *
      -     *   BooleanUtils.toBoolean("true", "true", "false")  = true
      -     *   BooleanUtils.toBoolean("false", "true", "false") = false
      +     *   BooleanUtils.toInteger(Boolean.TRUE, 1, 0, 2)  = 1
      +     *   BooleanUtils.toInteger(Boolean.FALSE, 1, 0, 2) = 0
      +     *   BooleanUtils.toInteger(null, 1, 0, 2)          = 2
            * 
      * - * @param str the String to check - * @param trueString the String to match for {@code true} (case sensitive), may be {@code null} - * @param falseString the String to match for {@code false} (case sensitive), may be {@code null} - * @return the boolean value of the string - * @throws IllegalArgumentException if the String doesn't match + * @param bool the Boolean to convert + * @param trueValue the value to return if {@code true} + * @param falseValue the value to return if {@code false} + * @param nullValue the value to return if {@code null} + * @return the appropriate value */ - public static boolean toBoolean(final String str, final String trueString, final String falseString) { - if (str == trueString) { - return true; - } else if (str == falseString) { - return false; - } else if (str != null) { - if (str.equals(trueString)) { - return true; - } else if (str.equals(falseString)) { - return false; - } + public static int toInteger(final Boolean bool, final int trueValue, final int falseValue, final int nullValue) { + if (bool == null) { + return nullValue; } - throw new IllegalArgumentException("The String did not match either specified value"); + return bool.booleanValue() ? trueValue : falseValue; } - // Boolean to String methods - //----------------------------------------------------------------------- /** - *

      Converts a Boolean to a String returning {@code 'true'}, - * {@code 'false'}, or {@code null}.

      + *

      Converts a boolean to an Integer using the convention that + * {@code true} is {@code 1} and {@code false} is {@code 0}.

      * *
      -     *   BooleanUtils.toStringTrueFalse(Boolean.TRUE)  = "true"
      -     *   BooleanUtils.toStringTrueFalse(Boolean.FALSE) = "false"
      -     *   BooleanUtils.toStringTrueFalse(null)          = null;
      +     *   BooleanUtils.toIntegerObject(true)  = Integer.valueOf(1)
      +     *   BooleanUtils.toIntegerObject(false) = Integer.valueOf(0)
      +     * 
      + * + * @param bool the boolean to convert + * @return one if {@code true}, zero if {@code false} + */ + public static Integer toIntegerObject(final boolean bool) { + return bool ? NumberUtils.INTEGER_ONE : NumberUtils.INTEGER_ZERO; + } + + /** + *

      Converts a boolean to an Integer specifying the conversion values.

      + * + *
      +     *   BooleanUtils.toIntegerObject(true, Integer.valueOf(1), Integer.valueOf(0))  = Integer.valueOf(1)
      +     *   BooleanUtils.toIntegerObject(false, Integer.valueOf(1), Integer.valueOf(0)) = Integer.valueOf(0)
      +     * 
      + * + * @param bool the to convert + * @param trueValue the value to return if {@code true}, may be {@code null} + * @param falseValue the value to return if {@code false}, may be {@code null} + * @return the appropriate value + */ + public static Integer toIntegerObject(final boolean bool, final Integer trueValue, final Integer falseValue) { + return bool ? trueValue : falseValue; + } + + /** + *

      Converts a Boolean to a Integer using the convention that + * {@code zero} is {@code false}.

      + * + *

      {@code null} will be converted to {@code null}.

      + * + *
      +     *   BooleanUtils.toIntegerObject(Boolean.TRUE)  = Integer.valueOf(1)
      +     *   BooleanUtils.toIntegerObject(Boolean.FALSE) = Integer.valueOf(0)
            * 
      * - * @param bool the Boolean to check - * @return {@code 'true'}, {@code 'false'}, or {@code null} + * @param bool the Boolean to convert + * @return one if Boolean.TRUE, zero if Boolean.FALSE, {@code null} if {@code null} */ - public static String toStringTrueFalse(final Boolean bool) { - return toString(bool, "true", "false", null); + public static Integer toIntegerObject(final Boolean bool) { + if (bool == null) { + return null; + } + return bool.booleanValue() ? NumberUtils.INTEGER_ONE : NumberUtils.INTEGER_ZERO; } /** - *

      Converts a Boolean to a String returning {@code 'on'}, - * {@code 'off'}, or {@code null}.

      + *

      Converts a Boolean to an Integer specifying the conversion values.

      * *
      -     *   BooleanUtils.toStringOnOff(Boolean.TRUE)  = "on"
      -     *   BooleanUtils.toStringOnOff(Boolean.FALSE) = "off"
      -     *   BooleanUtils.toStringOnOff(null)          = null;
      +     *   BooleanUtils.toIntegerObject(Boolean.TRUE, Integer.valueOf(1), Integer.valueOf(0), Integer.valueOf(2))  = Integer.valueOf(1)
      +     *   BooleanUtils.toIntegerObject(Boolean.FALSE, Integer.valueOf(1), Integer.valueOf(0), Integer.valueOf(2)) = Integer.valueOf(0)
      +     *   BooleanUtils.toIntegerObject(null, Integer.valueOf(1), Integer.valueOf(0), Integer.valueOf(2))          = Integer.valueOf(2)
            * 
      * - * @param bool the Boolean to check - * @return {@code 'on'}, {@code 'off'}, or {@code null} + * @param bool the Boolean to convert + * @param trueValue the value to return if {@code true}, may be {@code null} + * @param falseValue the value to return if {@code false}, may be {@code null} + * @param nullValue the value to return if {@code null}, may be {@code null} + * @return the appropriate value */ - public static String toStringOnOff(final Boolean bool) { - return toString(bool, "on", "off", null); + public static Integer toIntegerObject(final Boolean bool, final Integer trueValue, final Integer falseValue, final Integer nullValue) { + if (bool == null) { + return nullValue; + } + return bool.booleanValue() ? trueValue : falseValue; } /** - *

      Converts a Boolean to a String returning {@code 'yes'}, - * {@code 'no'}, or {@code null}.

      + *

      Converts a boolean to a String returning one of the input Strings.

      * *
      -     *   BooleanUtils.toStringYesNo(Boolean.TRUE)  = "yes"
      -     *   BooleanUtils.toStringYesNo(Boolean.FALSE) = "no"
      -     *   BooleanUtils.toStringYesNo(null)          = null;
      +     *   BooleanUtils.toString(true, "true", "false")   = "true"
      +     *   BooleanUtils.toString(false, "true", "false")  = "false"
            * 
      * * @param bool the Boolean to check - * @return {@code 'yes'}, {@code 'no'}, or {@code null} + * @param trueString the String to return if {@code true}, may be {@code null} + * @param falseString the String to return if {@code false}, may be {@code null} + * @return one of the two input Strings */ - public static String toStringYesNo(final Boolean bool) { - return toString(bool, "yes", "no", null); + public static String toString(final boolean bool, final String trueString, final String falseString) { + return bool ? trueString : falseString; } /** @@ -845,24 +939,6 @@ public static String toString(final Boolean bool, final String trueString, final return bool.booleanValue() ? trueString : falseString; } - // boolean to String methods - //----------------------------------------------------------------------- - /** - *

      Converts a boolean to a String returning {@code 'true'} - * or {@code 'false'}.

      - * - *
      -     *   BooleanUtils.toStringTrueFalse(true)   = "true"
      -     *   BooleanUtils.toStringTrueFalse(false)  = "false"
      -     * 
      - * - * @param bool the Boolean to check - * @return {@code 'true'}, {@code 'false'}, or {@code null} - */ - public static String toStringTrueFalse(final boolean bool) { - return toString(bool, "true", "false"); - } - /** *

      Converts a boolean to a String returning {@code 'on'} * or {@code 'off'}.

      @@ -880,175 +956,86 @@ public static String toStringOnOff(final boolean bool) { } /** - *

      Converts a boolean to a String returning {@code 'yes'} - * or {@code 'no'}.

      + *

      Converts a Boolean to a String returning {@code 'on'}, + * {@code 'off'}, or {@code null}.

      * *
      -     *   BooleanUtils.toStringYesNo(true)   = "yes"
      -     *   BooleanUtils.toStringYesNo(false)  = "no"
      +     *   BooleanUtils.toStringOnOff(Boolean.TRUE)  = "on"
      +     *   BooleanUtils.toStringOnOff(Boolean.FALSE) = "off"
      +     *   BooleanUtils.toStringOnOff(null)          = null;
            * 
      * * @param bool the Boolean to check - * @return {@code 'yes'}, {@code 'no'}, or {@code null} + * @return {@code 'on'}, {@code 'off'}, or {@code null} */ - public static String toStringYesNo(final boolean bool) { - return toString(bool, "yes", "no"); + public static String toStringOnOff(final Boolean bool) { + return toString(bool, "on", "off", null); } /** - *

      Converts a boolean to a String returning one of the input Strings.

      + *

      Converts a boolean to a String returning {@code 'true'} + * or {@code 'false'}.

      * *
      -     *   BooleanUtils.toString(true, "true", "false")   = "true"
      -     *   BooleanUtils.toString(false, "true", "false")  = "false"
      +     *   BooleanUtils.toStringTrueFalse(true)   = "true"
      +     *   BooleanUtils.toStringTrueFalse(false)  = "false"
            * 
      * * @param bool the Boolean to check - * @param trueString the String to return if {@code true}, may be {@code null} - * @param falseString the String to return if {@code false}, may be {@code null} - * @return one of the two input Strings - */ - public static String toString(final boolean bool, final String trueString, final String falseString) { - return bool ? trueString : falseString; - } - - // logical operations - // ---------------------------------------------------------------------- - /** - *

      Performs an 'and' operation on a set of booleans.

      - * - *
      -     *   BooleanUtils.and(true, true)         = true
      -     *   BooleanUtils.and(false, false)       = false
      -     *   BooleanUtils.and(true, false)        = false
      -     *   BooleanUtils.and(true, true, false)  = false
      -     *   BooleanUtils.and(true, true, true)   = true
      -     * 
      - * - * @param array an array of {@code boolean}s - * @return the result of the logical 'and' operation. That is {@code false} - * if any of the parameters is {@code false} and {@code true} otherwise. - * @throws IllegalArgumentException if {@code array} is {@code null} - * @throws IllegalArgumentException if {@code array} is empty. - * @since 3.0.1 + * @return {@code 'true'}, {@code 'false'}, or {@code null} */ - public static boolean and(final boolean... array) { - // Validates input - if (array == null) { - throw new IllegalArgumentException("The Array must not be null"); - } - if (array.length == 0) { - throw new IllegalArgumentException("Array is empty"); - } - for (final boolean element : array) { - if (!element) { - return false; - } - } - return true; + public static String toStringTrueFalse(final boolean bool) { + return toString(bool, "true", "false"); } /** - *

      Performs an 'and' operation on an array of Booleans.

      + *

      Converts a Boolean to a String returning {@code 'true'}, + * {@code 'false'}, or {@code null}.

      * *
      -     *   BooleanUtils.and(Boolean.TRUE, Boolean.TRUE)                 = Boolean.TRUE
      -     *   BooleanUtils.and(Boolean.FALSE, Boolean.FALSE)               = Boolean.FALSE
      -     *   BooleanUtils.and(Boolean.TRUE, Boolean.FALSE)                = Boolean.FALSE
      -     *   BooleanUtils.and(Boolean.TRUE, Boolean.TRUE, Boolean.TRUE)   = Boolean.TRUE
      -     *   BooleanUtils.and(Boolean.FALSE, Boolean.FALSE, Boolean.TRUE) = Boolean.FALSE
      -     *   BooleanUtils.and(Boolean.TRUE, Boolean.FALSE, Boolean.TRUE)  = Boolean.FALSE
      +     *   BooleanUtils.toStringTrueFalse(Boolean.TRUE)  = "true"
      +     *   BooleanUtils.toStringTrueFalse(Boolean.FALSE) = "false"
      +     *   BooleanUtils.toStringTrueFalse(null)          = null;
            * 
      * - * @param array an array of {@code Boolean}s - * @return the result of the logical 'and' operation. That is {@code false} - * if any of the parameters is {@code false} and {@code true} otherwise. - * @throws IllegalArgumentException if {@code array} is {@code null} - * @throws IllegalArgumentException if {@code array} is empty. - * @throws IllegalArgumentException if {@code array} contains a {@code null} - * @since 3.0.1 + * @param bool the Boolean to check + * @return {@code 'true'}, {@code 'false'}, or {@code null} */ - public static Boolean and(final Boolean... array) { - if (array == null) { - throw new IllegalArgumentException("The Array must not be null"); - } - if (array.length == 0) { - throw new IllegalArgumentException("Array is empty"); - } - try { - final boolean[] primitive = ArrayUtils.toPrimitive(array); - return and(primitive) ? Boolean.TRUE : Boolean.FALSE; - } catch (final NullPointerException ex) { - throw new IllegalArgumentException("The array must not contain any null elements"); - } + public static String toStringTrueFalse(final Boolean bool) { + return toString(bool, "true", "false", null); } /** - *

      Performs an 'or' operation on a set of booleans.

      + *

      Converts a boolean to a String returning {@code 'yes'} + * or {@code 'no'}.

      * *
      -     *   BooleanUtils.or(true, true)          = true
      -     *   BooleanUtils.or(false, false)        = false
      -     *   BooleanUtils.or(true, false)         = true
      -     *   BooleanUtils.or(true, true, false)   = true
      -     *   BooleanUtils.or(true, true, true)    = true
      -     *   BooleanUtils.or(false, false, false) = false
      +     *   BooleanUtils.toStringYesNo(true)   = "yes"
      +     *   BooleanUtils.toStringYesNo(false)  = "no"
            * 
      * - * @param array an array of {@code boolean}s - * @return {@code true} if any of the arguments is {@code true}, and it returns {@code false} otherwise. - * @throws IllegalArgumentException if {@code array} is {@code null} - * @throws IllegalArgumentException if {@code array} is empty. - * @since 3.0.1 + * @param bool the Boolean to check + * @return {@code 'yes'}, {@code 'no'}, or {@code null} */ - public static boolean or(final boolean... array) { - if (array == null) { - throw new IllegalArgumentException("The Array must not be null"); - } - if (array.length == 0) { - throw new IllegalArgumentException("Array is empty"); - } - for (final boolean element : array) { - if (element) { - return true; - } - } - return false; + public static String toStringYesNo(final boolean bool) { + return toString(bool, "yes", "no"); } /** - *

      Performs an 'or' operation on an array of Booleans.

      + *

      Converts a Boolean to a String returning {@code 'yes'}, + * {@code 'no'}, or {@code null}.

      * *
      -     *   BooleanUtils.or(Boolean.TRUE, Boolean.TRUE)                  = Boolean.TRUE
      -     *   BooleanUtils.or(Boolean.FALSE, Boolean.FALSE)                = Boolean.FALSE
      -     *   BooleanUtils.or(Boolean.TRUE, Boolean.FALSE)                 = Boolean.TRUE
      -     *   BooleanUtils.or(Boolean.TRUE, Boolean.TRUE, Boolean.TRUE)    = Boolean.TRUE
      -     *   BooleanUtils.or(Boolean.FALSE, Boolean.FALSE, Boolean.TRUE)  = Boolean.TRUE
      -     *   BooleanUtils.or(Boolean.TRUE, Boolean.FALSE, Boolean.TRUE)   = Boolean.TRUE
      -     *   BooleanUtils.or(Boolean.FALSE, Boolean.FALSE, Boolean.FALSE) = Boolean.FALSE
      +     *   BooleanUtils.toStringYesNo(Boolean.TRUE)  = "yes"
      +     *   BooleanUtils.toStringYesNo(Boolean.FALSE) = "no"
      +     *   BooleanUtils.toStringYesNo(null)          = null;
            * 
      * - * @param array an array of {@code Boolean}s - * @return {@code true} if any of the arguments is {@code true}, and it returns {@code false} otherwise. - * @throws IllegalArgumentException if {@code array} is {@code null} - * @throws IllegalArgumentException if {@code array} is empty. - * @throws IllegalArgumentException if {@code array} contains a {@code null} - * @since 3.0.1 + * @param bool the Boolean to check + * @return {@code 'yes'}, {@code 'no'}, or {@code null} */ - public static Boolean or(final Boolean... array) { - if (array == null) { - throw new IllegalArgumentException("The Array must not be null"); - } - if (array.length == 0) { - throw new IllegalArgumentException("Array is empty"); - } - try { - final boolean[] primitive = ArrayUtils.toPrimitive(array); - return or(primitive) ? Boolean.TRUE : Boolean.FALSE; - } catch (final NullPointerException ex) { - throw new IllegalArgumentException("The array must not contain any null elements"); - } + public static String toStringYesNo(final Boolean bool) { + return toString(bool, "yes", "no", null); } /** @@ -1114,20 +1101,14 @@ public static Boolean xor(final Boolean... array) { } /** - *

      Compares two {@code boolean} values. This is the same functionality as provided in Java 7.

      + *

      {@code BooleanUtils} instances should NOT be constructed in standard programming. + * Instead, the class should be used as {@code BooleanUtils.negate(true);}.

      * - * @param x the first {@code boolean} to compare - * @param y the second {@code boolean} to compare - * @return the value {@code 0} if {@code x == y}; - * a value less than {@code 0} if {@code !x && y}; and - * a value greater than {@code 0} if {@code x && !y} - * @since 3.4 + *

      This constructor is public to permit tools that require a JavaBean instance + * to operate.

      */ - public static int compare(final boolean x, final boolean y) { - if (x == y) { - return 0; - } - return x ? 1 : -1; + public BooleanUtils() { + super(); } } From a3e5a0134e06911b9ea35b1bcdeefd10a523743f Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Mon, 28 Sep 2020 15:19:12 -0400 Subject: [PATCH 0364/3230] Sort members. --- .../commons/lang3/BooleanUtilsTest.java | 1008 ++++++++--------- 1 file changed, 493 insertions(+), 515 deletions(-) diff --git a/src/test/java/org/apache/commons/lang3/BooleanUtilsTest.java b/src/test/java/org/apache/commons/lang3/BooleanUtilsTest.java index a70272fbc96..8920e851935 100644 --- a/src/test/java/org/apache/commons/lang3/BooleanUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/BooleanUtilsTest.java @@ -34,31 +34,18 @@ */ public class BooleanUtilsTest { - //----------------------------------------------------------------------- @Test - public void testConstructor() { - assertNotNull(new BooleanUtils()); - final Constructor[] cons = BooleanUtils.class.getDeclaredConstructors(); - assertEquals(1, cons.length); - assertTrue(Modifier.isPublic(cons[0].getModifiers())); - assertTrue(Modifier.isPublic(BooleanUtils.class.getModifiers())); - assertFalse(Modifier.isFinal(BooleanUtils.class.getModifiers())); - } - - //----------------------------------------------------------------------- - @Test - public void test_negate_Boolean() { - assertSame(null, BooleanUtils.negate(null)); - assertSame(Boolean.TRUE, BooleanUtils.negate(Boolean.FALSE)); - assertSame(Boolean.FALSE, BooleanUtils.negate(Boolean.TRUE)); + public void test_isFalse_Boolean() { + assertFalse(BooleanUtils.isFalse(Boolean.TRUE)); + assertTrue(BooleanUtils.isFalse(Boolean.FALSE)); + assertFalse(BooleanUtils.isFalse(null)); } - //----------------------------------------------------------------------- @Test - public void test_isTrue_Boolean() { - assertTrue(BooleanUtils.isTrue(Boolean.TRUE)); - assertFalse(BooleanUtils.isTrue(Boolean.FALSE)); - assertFalse(BooleanUtils.isTrue(null)); + public void test_isNotFalse_Boolean() { + assertTrue(BooleanUtils.isNotFalse(Boolean.TRUE)); + assertFalse(BooleanUtils.isNotFalse(Boolean.FALSE)); + assertTrue(BooleanUtils.isNotFalse(null)); } @Test @@ -68,22 +55,20 @@ public void test_isNotTrue_Boolean() { assertTrue(BooleanUtils.isNotTrue(null)); } - //----------------------------------------------------------------------- @Test - public void test_isFalse_Boolean() { - assertFalse(BooleanUtils.isFalse(Boolean.TRUE)); - assertTrue(BooleanUtils.isFalse(Boolean.FALSE)); - assertFalse(BooleanUtils.isFalse(null)); + public void test_isTrue_Boolean() { + assertTrue(BooleanUtils.isTrue(Boolean.TRUE)); + assertFalse(BooleanUtils.isTrue(Boolean.FALSE)); + assertFalse(BooleanUtils.isTrue(null)); } @Test - public void test_isNotFalse_Boolean() { - assertTrue(BooleanUtils.isNotFalse(Boolean.TRUE)); - assertFalse(BooleanUtils.isNotFalse(Boolean.FALSE)); - assertTrue(BooleanUtils.isNotFalse(null)); + public void test_negate_Boolean() { + assertSame(null, BooleanUtils.negate(null)); + assertSame(Boolean.TRUE, BooleanUtils.negate(Boolean.FALSE)); + assertSame(Boolean.FALSE, BooleanUtils.negate(Boolean.TRUE)); } - //----------------------------------------------------------------------- @Test public void test_toBoolean_Boolean() { assertTrue(BooleanUtils.toBoolean(Boolean.TRUE)); @@ -91,18 +76,6 @@ public void test_toBoolean_Boolean() { assertFalse(BooleanUtils.toBoolean((Boolean) null)); } - @Test - public void test_toBooleanDefaultIfNull_Boolean_boolean() { - assertTrue(BooleanUtils.toBooleanDefaultIfNull(Boolean.TRUE, true)); - assertTrue(BooleanUtils.toBooleanDefaultIfNull(Boolean.TRUE, false)); - assertFalse(BooleanUtils.toBooleanDefaultIfNull(Boolean.FALSE, true)); - assertFalse(BooleanUtils.toBooleanDefaultIfNull(Boolean.FALSE, false)); - assertTrue(BooleanUtils.toBooleanDefaultIfNull(null, true)); - assertFalse(BooleanUtils.toBooleanDefaultIfNull(null, false)); - } - - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- @Test public void test_toBoolean_int() { assertTrue(BooleanUtils.toBoolean(1)); @@ -110,22 +83,6 @@ public void test_toBoolean_int() { assertFalse(BooleanUtils.toBoolean(0)); } - @Test - public void test_toBooleanObject_int() { - assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject(1)); - assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject(-1)); - assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject(0)); - } - - @Test - public void test_toBooleanObject_Integer() { - assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject(Integer.valueOf(1))); - assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject(Integer.valueOf(-1))); - assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject(Integer.valueOf(0))); - assertNull(BooleanUtils.toBooleanObject((Integer) null)); - } - - //----------------------------------------------------------------------- @Test public void test_toBoolean_int_int_int() { assertTrue(BooleanUtils.toBoolean(6, 6, 7)); @@ -149,6 +106,12 @@ public void test_toBoolean_Integer_Integer_Integer() { assertFalse(BooleanUtils.toBoolean(Integer.valueOf(7), six, seven)); } + @Test + public void test_toBoolean_Integer_Integer_Integer_noMatch() { + assertThrows(IllegalArgumentException.class, + () -> BooleanUtils.toBoolean(Integer.valueOf(8), Integer.valueOf(6), Integer.valueOf(7))); + } + @Test public void test_toBoolean_Integer_Integer_Integer_nullValue() { assertThrows(IllegalArgumentException.class, @@ -156,12 +119,94 @@ public void test_toBoolean_Integer_Integer_Integer_nullValue() { } @Test - public void test_toBoolean_Integer_Integer_Integer_noMatch() { - assertThrows(IllegalArgumentException.class, - () -> BooleanUtils.toBoolean(Integer.valueOf(8), Integer.valueOf(6), Integer.valueOf(7))); + public void test_toBoolean_String() { + assertFalse(BooleanUtils.toBoolean((String) null)); + assertFalse(BooleanUtils.toBoolean("")); + assertFalse(BooleanUtils.toBoolean("off")); + assertFalse(BooleanUtils.toBoolean("oof")); + assertFalse(BooleanUtils.toBoolean("yep")); + assertFalse(BooleanUtils.toBoolean("trux")); + assertFalse(BooleanUtils.toBoolean("false")); + assertFalse(BooleanUtils.toBoolean("a")); + assertTrue(BooleanUtils.toBoolean("true")); // interned handled differently + assertTrue(BooleanUtils.toBoolean(new StringBuilder("tr").append("ue").toString())); + assertTrue(BooleanUtils.toBoolean("truE")); + assertTrue(BooleanUtils.toBoolean("trUe")); + assertTrue(BooleanUtils.toBoolean("trUE")); + assertTrue(BooleanUtils.toBoolean("tRue")); + assertTrue(BooleanUtils.toBoolean("tRuE")); + assertTrue(BooleanUtils.toBoolean("tRUe")); + assertTrue(BooleanUtils.toBoolean("tRUE")); + assertTrue(BooleanUtils.toBoolean("TRUE")); + assertTrue(BooleanUtils.toBoolean("TRUe")); + assertTrue(BooleanUtils.toBoolean("TRuE")); + assertTrue(BooleanUtils.toBoolean("TRue")); + assertTrue(BooleanUtils.toBoolean("TrUE")); + assertTrue(BooleanUtils.toBoolean("TrUe")); + assertTrue(BooleanUtils.toBoolean("TruE")); + assertTrue(BooleanUtils.toBoolean("True")); + assertTrue(BooleanUtils.toBoolean("on")); + assertTrue(BooleanUtils.toBoolean("oN")); + assertTrue(BooleanUtils.toBoolean("On")); + assertTrue(BooleanUtils.toBoolean("ON")); + assertTrue(BooleanUtils.toBoolean("yes")); + assertTrue(BooleanUtils.toBoolean("yeS")); + assertTrue(BooleanUtils.toBoolean("yEs")); + assertTrue(BooleanUtils.toBoolean("yES")); + assertTrue(BooleanUtils.toBoolean("Yes")); + assertTrue(BooleanUtils.toBoolean("YeS")); + assertTrue(BooleanUtils.toBoolean("YEs")); + assertTrue(BooleanUtils.toBoolean("YES")); + assertTrue(BooleanUtils.toBoolean("1")); + assertFalse(BooleanUtils.toBoolean("yes?")); + assertFalse(BooleanUtils.toBoolean("0")); + assertFalse(BooleanUtils.toBoolean("tru")); + + assertFalse(BooleanUtils.toBoolean("no")); + assertFalse(BooleanUtils.toBoolean("off")); + assertFalse(BooleanUtils.toBoolean("yoo")); + } + + @Test + public void test_toBoolean_String_String_String() { + assertTrue(BooleanUtils.toBoolean(null, null, "N")); + assertFalse(BooleanUtils.toBoolean(null, "Y", null)); + assertTrue(BooleanUtils.toBoolean("Y", "Y", "N")); + assertTrue(BooleanUtils.toBoolean("Y", new String("Y"), new String("N"))); + assertFalse(BooleanUtils.toBoolean("N", "Y", "N")); + assertFalse(BooleanUtils.toBoolean("N", new String("Y"), new String("N"))); + assertTrue(BooleanUtils.toBoolean((String) null, null, null)); + assertTrue(BooleanUtils.toBoolean("Y", "Y", "Y")); + assertTrue(BooleanUtils.toBoolean("Y", new String("Y"), new String("Y"))); + } + + @Test + public void test_toBoolean_String_String_String_noMatch() { + assertThrows(IllegalArgumentException.class, () -> BooleanUtils.toBoolean("X", "Y", "N")); + } + + @Test + public void test_toBoolean_String_String_String_nullValue() { + assertThrows(IllegalArgumentException.class, () -> BooleanUtils.toBoolean(null, "Y", "N")); + } + + @Test + public void test_toBooleanDefaultIfNull_Boolean_boolean() { + assertTrue(BooleanUtils.toBooleanDefaultIfNull(Boolean.TRUE, true)); + assertTrue(BooleanUtils.toBooleanDefaultIfNull(Boolean.TRUE, false)); + assertFalse(BooleanUtils.toBooleanDefaultIfNull(Boolean.FALSE, true)); + assertFalse(BooleanUtils.toBooleanDefaultIfNull(Boolean.FALSE, false)); + assertTrue(BooleanUtils.toBooleanDefaultIfNull(null, true)); + assertFalse(BooleanUtils.toBooleanDefaultIfNull(null, false)); + } + + @Test + public void test_toBooleanObject_int() { + assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject(1)); + assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject(-1)); + assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject(0)); } - //----------------------------------------------------------------------- @Test public void test_toBooleanObject_int_int_int() { assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject(6, 6, 7, 8)); @@ -174,6 +219,14 @@ public void test_toBooleanObject_int_int_int_noMatch() { assertThrows(IllegalArgumentException.class, () -> BooleanUtils.toBooleanObject(9, 6, 7, 8)); } + @Test + public void test_toBooleanObject_Integer() { + assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject(Integer.valueOf(1))); + assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject(Integer.valueOf(-1))); + assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject(Integer.valueOf(0))); + assertNull(BooleanUtils.toBooleanObject((Integer) null)); + } + @Test public void test_toBooleanObject_Integer_Integer_Integer_Integer() { final Integer six = Integer.valueOf(6); @@ -189,73 +242,18 @@ public void test_toBooleanObject_Integer_Integer_Integer_Integer() { assertNull(BooleanUtils.toBooleanObject(Integer.valueOf(8), six, seven, eight)); } - @Test - public void test_toBooleanObject_Integer_Integer_Integer_Integer_nullValue() { - assertThrows(IllegalArgumentException.class, - () -> BooleanUtils.toBooleanObject(null, Integer.valueOf(6), Integer.valueOf(7), Integer.valueOf(8))); - } - @Test public void test_toBooleanObject_Integer_Integer_Integer_Integer_noMatch() { assertThrows(IllegalArgumentException.class, () -> BooleanUtils.toBooleanObject(Integer.valueOf(9), Integer.valueOf(6), Integer.valueOf(7), Integer.valueOf(8))); } - //----------------------------------------------------------------------- - @Test - public void test_toInteger_boolean() { - assertEquals(1, BooleanUtils.toInteger(true)); - assertEquals(0, BooleanUtils.toInteger(false)); - } - - @Test - public void test_toIntegerObject_boolean() { - assertEquals(Integer.valueOf(1), BooleanUtils.toIntegerObject(true)); - assertEquals(Integer.valueOf(0), BooleanUtils.toIntegerObject(false)); - } - - @Test - public void test_toIntegerObject_Boolean() { - assertEquals(Integer.valueOf(1), BooleanUtils.toIntegerObject(Boolean.TRUE)); - assertEquals(Integer.valueOf(0), BooleanUtils.toIntegerObject(Boolean.FALSE)); - assertNull(BooleanUtils.toIntegerObject(null)); - } - - //----------------------------------------------------------------------- - @Test - public void test_toInteger_boolean_int_int() { - assertEquals(6, BooleanUtils.toInteger(true, 6, 7)); - assertEquals(7, BooleanUtils.toInteger(false, 6, 7)); - } - - @Test - public void test_toInteger_Boolean_int_int_int() { - assertEquals(6, BooleanUtils.toInteger(Boolean.TRUE, 6, 7, 8)); - assertEquals(7, BooleanUtils.toInteger(Boolean.FALSE, 6, 7, 8)); - assertEquals(8, BooleanUtils.toInteger(null, 6, 7, 8)); - } - @Test - public void test_toIntegerObject_boolean_Integer_Integer() { - final Integer six = Integer.valueOf(6); - final Integer seven = Integer.valueOf(7); - assertEquals(six, BooleanUtils.toIntegerObject(true, six, seven)); - assertEquals(seven, BooleanUtils.toIntegerObject(false, six, seven)); - } - - @Test - public void test_toIntegerObject_Boolean_Integer_Integer_Integer() { - final Integer six = Integer.valueOf(6); - final Integer seven = Integer.valueOf(7); - final Integer eight = Integer.valueOf(8); - assertEquals(six, BooleanUtils.toIntegerObject(Boolean.TRUE, six, seven, eight)); - assertEquals(seven, BooleanUtils.toIntegerObject(Boolean.FALSE, six, seven, eight)); - assertEquals(eight, BooleanUtils.toIntegerObject(null, six, seven, eight)); - assertNull(BooleanUtils.toIntegerObject(null, six, seven, null)); + public void test_toBooleanObject_Integer_Integer_Integer_Integer_nullValue() { + assertThrows(IllegalArgumentException.class, + () -> BooleanUtils.toBooleanObject(null, Integer.valueOf(6), Integer.valueOf(7), Integer.valueOf(8))); } - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- @Test public void test_toBooleanObject_String() { assertNull(BooleanUtils.toBooleanObject((String) null)); @@ -305,109 +303,71 @@ public void test_toBooleanObject_String_String_String_String() { assertNull(BooleanUtils.toBooleanObject("U", "Y", "N", "U")); } + @Test + public void test_toBooleanObject_String_String_String_String_noMatch() { + assertThrows(IllegalArgumentException.class, () -> BooleanUtils.toBooleanObject("X", "Y", "N", "U")); + } + @Test public void test_toBooleanObject_String_String_String_String_nullValue() { assertThrows(IllegalArgumentException.class, () -> BooleanUtils.toBooleanObject(null, "Y", "N", "U")); } @Test - public void test_toBooleanObject_String_String_String_String_noMatch() { - assertThrows(IllegalArgumentException.class, () -> BooleanUtils.toBooleanObject("X", "Y", "N", "U")); + public void test_toInteger_boolean() { + assertEquals(1, BooleanUtils.toInteger(true)); + assertEquals(0, BooleanUtils.toInteger(false)); } - //----------------------------------------------------------------------- @Test - public void test_toBoolean_String() { - assertFalse(BooleanUtils.toBoolean((String) null)); - assertFalse(BooleanUtils.toBoolean("")); - assertFalse(BooleanUtils.toBoolean("off")); - assertFalse(BooleanUtils.toBoolean("oof")); - assertFalse(BooleanUtils.toBoolean("yep")); - assertFalse(BooleanUtils.toBoolean("trux")); - assertFalse(BooleanUtils.toBoolean("false")); - assertFalse(BooleanUtils.toBoolean("a")); - assertTrue(BooleanUtils.toBoolean("true")); // interned handled differently - assertTrue(BooleanUtils.toBoolean(new StringBuilder("tr").append("ue").toString())); - assertTrue(BooleanUtils.toBoolean("truE")); - assertTrue(BooleanUtils.toBoolean("trUe")); - assertTrue(BooleanUtils.toBoolean("trUE")); - assertTrue(BooleanUtils.toBoolean("tRue")); - assertTrue(BooleanUtils.toBoolean("tRuE")); - assertTrue(BooleanUtils.toBoolean("tRUe")); - assertTrue(BooleanUtils.toBoolean("tRUE")); - assertTrue(BooleanUtils.toBoolean("TRUE")); - assertTrue(BooleanUtils.toBoolean("TRUe")); - assertTrue(BooleanUtils.toBoolean("TRuE")); - assertTrue(BooleanUtils.toBoolean("TRue")); - assertTrue(BooleanUtils.toBoolean("TrUE")); - assertTrue(BooleanUtils.toBoolean("TrUe")); - assertTrue(BooleanUtils.toBoolean("TruE")); - assertTrue(BooleanUtils.toBoolean("True")); - assertTrue(BooleanUtils.toBoolean("on")); - assertTrue(BooleanUtils.toBoolean("oN")); - assertTrue(BooleanUtils.toBoolean("On")); - assertTrue(BooleanUtils.toBoolean("ON")); - assertTrue(BooleanUtils.toBoolean("yes")); - assertTrue(BooleanUtils.toBoolean("yeS")); - assertTrue(BooleanUtils.toBoolean("yEs")); - assertTrue(BooleanUtils.toBoolean("yES")); - assertTrue(BooleanUtils.toBoolean("Yes")); - assertTrue(BooleanUtils.toBoolean("YeS")); - assertTrue(BooleanUtils.toBoolean("YEs")); - assertTrue(BooleanUtils.toBoolean("YES")); - assertTrue(BooleanUtils.toBoolean("1")); - assertFalse(BooleanUtils.toBoolean("yes?")); - assertFalse(BooleanUtils.toBoolean("0")); - assertFalse(BooleanUtils.toBoolean("tru")); - - assertFalse(BooleanUtils.toBoolean("no")); - assertFalse(BooleanUtils.toBoolean("off")); - assertFalse(BooleanUtils.toBoolean("yoo")); + public void test_toInteger_boolean_int_int() { + assertEquals(6, BooleanUtils.toInteger(true, 6, 7)); + assertEquals(7, BooleanUtils.toInteger(false, 6, 7)); } @Test - public void test_toBoolean_String_String_String() { - assertTrue(BooleanUtils.toBoolean(null, null, "N")); - assertFalse(BooleanUtils.toBoolean(null, "Y", null)); - assertTrue(BooleanUtils.toBoolean("Y", "Y", "N")); - assertTrue(BooleanUtils.toBoolean("Y", new String("Y"), new String("N"))); - assertFalse(BooleanUtils.toBoolean("N", "Y", "N")); - assertFalse(BooleanUtils.toBoolean("N", new String("Y"), new String("N"))); - assertTrue(BooleanUtils.toBoolean((String) null, null, null)); - assertTrue(BooleanUtils.toBoolean("Y", "Y", "Y")); - assertTrue(BooleanUtils.toBoolean("Y", new String("Y"), new String("Y"))); + public void test_toInteger_Boolean_int_int_int() { + assertEquals(6, BooleanUtils.toInteger(Boolean.TRUE, 6, 7, 8)); + assertEquals(7, BooleanUtils.toInteger(Boolean.FALSE, 6, 7, 8)); + assertEquals(8, BooleanUtils.toInteger(null, 6, 7, 8)); } @Test - public void test_toBoolean_String_String_String_nullValue() { - assertThrows(IllegalArgumentException.class, () -> BooleanUtils.toBoolean(null, "Y", "N")); + public void test_toIntegerObject_boolean() { + assertEquals(Integer.valueOf(1), BooleanUtils.toIntegerObject(true)); + assertEquals(Integer.valueOf(0), BooleanUtils.toIntegerObject(false)); } @Test - public void test_toBoolean_String_String_String_noMatch() { - assertThrows(IllegalArgumentException.class, () -> BooleanUtils.toBoolean("X", "Y", "N")); + public void test_toIntegerObject_Boolean() { + assertEquals(Integer.valueOf(1), BooleanUtils.toIntegerObject(Boolean.TRUE)); + assertEquals(Integer.valueOf(0), BooleanUtils.toIntegerObject(Boolean.FALSE)); + assertNull(BooleanUtils.toIntegerObject(null)); } - //----------------------------------------------------------------------- @Test - public void test_toStringTrueFalse_Boolean() { - assertNull(BooleanUtils.toStringTrueFalse(null)); - assertEquals("true", BooleanUtils.toStringTrueFalse(Boolean.TRUE)); - assertEquals("false", BooleanUtils.toStringTrueFalse(Boolean.FALSE)); + public void test_toIntegerObject_boolean_Integer_Integer() { + final Integer six = Integer.valueOf(6); + final Integer seven = Integer.valueOf(7); + assertEquals(six, BooleanUtils.toIntegerObject(true, six, seven)); + assertEquals(seven, BooleanUtils.toIntegerObject(false, six, seven)); } @Test - public void test_toStringOnOff_Boolean() { - assertNull(BooleanUtils.toStringOnOff(null)); - assertEquals("on", BooleanUtils.toStringOnOff(Boolean.TRUE)); - assertEquals("off", BooleanUtils.toStringOnOff(Boolean.FALSE)); + public void test_toIntegerObject_Boolean_Integer_Integer_Integer() { + final Integer six = Integer.valueOf(6); + final Integer seven = Integer.valueOf(7); + final Integer eight = Integer.valueOf(8); + assertEquals(six, BooleanUtils.toIntegerObject(Boolean.TRUE, six, seven, eight)); + assertEquals(seven, BooleanUtils.toIntegerObject(Boolean.FALSE, six, seven, eight)); + assertEquals(eight, BooleanUtils.toIntegerObject(null, six, seven, eight)); + assertNull(BooleanUtils.toIntegerObject(null, six, seven, null)); } @Test - public void test_toStringYesNo_Boolean() { - assertNull(BooleanUtils.toStringYesNo(null)); - assertEquals("yes", BooleanUtils.toStringYesNo(Boolean.TRUE)); - assertEquals("no", BooleanUtils.toStringYesNo(Boolean.FALSE)); + public void test_toString_boolean_String_String_String() { + assertEquals("Y", BooleanUtils.toString(true, "Y", "N")); + assertEquals("N", BooleanUtils.toString(false, "Y", "N")); } @Test @@ -417,13 +377,6 @@ public void test_toString_Boolean_String_String_String() { assertEquals("N", BooleanUtils.toString(Boolean.FALSE, "Y", "N", "U")); } - //----------------------------------------------------------------------- - @Test - public void test_toStringTrueFalse_boolean() { - assertEquals("true", BooleanUtils.toStringTrueFalse(true)); - assertEquals("false", BooleanUtils.toStringTrueFalse(false)); - } - @Test public void test_toStringOnOff_boolean() { assertEquals("on", BooleanUtils.toStringOnOff(true)); @@ -431,229 +384,163 @@ public void test_toStringOnOff_boolean() { } @Test - public void test_toStringYesNo_boolean() { - assertEquals("yes", BooleanUtils.toStringYesNo(true)); - assertEquals("no", BooleanUtils.toStringYesNo(false)); - } - - @Test - public void test_toString_boolean_String_String_String() { - assertEquals("Y", BooleanUtils.toString(true, "Y", "N")); - assertEquals("N", BooleanUtils.toString(false, "Y", "N")); + public void test_toStringOnOff_Boolean() { + assertNull(BooleanUtils.toStringOnOff(null)); + assertEquals("on", BooleanUtils.toStringOnOff(Boolean.TRUE)); + assertEquals("off", BooleanUtils.toStringOnOff(Boolean.FALSE)); } - // testXor - // ----------------------------------------------------------------------- @Test - public void testXor_primitive_nullInput() { - assertThrows(IllegalArgumentException.class, () -> BooleanUtils.xor((boolean[]) null)); + public void test_toStringTrueFalse_boolean() { + assertEquals("true", BooleanUtils.toStringTrueFalse(true)); + assertEquals("false", BooleanUtils.toStringTrueFalse(false)); } @Test - public void testXor_primitive_emptyInput() { - assertThrows(IllegalArgumentException.class, () -> BooleanUtils.xor(new boolean[] {})); + public void test_toStringTrueFalse_Boolean() { + assertNull(BooleanUtils.toStringTrueFalse(null)); + assertEquals("true", BooleanUtils.toStringTrueFalse(Boolean.TRUE)); + assertEquals("false", BooleanUtils.toStringTrueFalse(Boolean.FALSE)); } @Test - public void testXor_primitive_validInput_2items() { - assertEquals( - true ^ true, - BooleanUtils.xor(new boolean[] { true, true }), - "true ^ true"); - - assertEquals( - false ^ false, - BooleanUtils.xor(new boolean[] { false, false }), - "false ^ false"); - - assertEquals( - true ^ false, - BooleanUtils.xor(new boolean[] { true, false }), - "true ^ false"); - - assertEquals( - false ^ true, - BooleanUtils.xor(new boolean[] { false, true }), - "false ^ true"); + public void test_toStringYesNo_boolean() { + assertEquals("yes", BooleanUtils.toStringYesNo(true)); + assertEquals("no", BooleanUtils.toStringYesNo(false)); } @Test - public void testXor_primitive_validInput_3items() { - assertEquals( - false ^ false ^ false, - BooleanUtils.xor(new boolean[] { false, false, false }), - "false ^ false ^ false"); - - assertEquals( - false ^ false ^ true, - BooleanUtils.xor(new boolean[] { false, false, true }), - "false ^ false ^ true"); - - assertEquals( - false ^ true ^ false, - BooleanUtils.xor(new boolean[] { false, true, false }), - "false ^ true ^ false"); - - assertEquals( - false ^ true ^ true, - BooleanUtils.xor(new boolean[] { false, true, true }), - "false ^ true ^ true"); - - assertEquals( - true ^ false ^ false, - BooleanUtils.xor(new boolean[] { true, false, false }), - "true ^ false ^ false"); - - assertEquals( - true ^ false ^ true, - BooleanUtils.xor(new boolean[] { true, false, true }), - "true ^ false ^ true"); - - assertEquals( - true ^ true ^ false, - BooleanUtils.xor(new boolean[] { true, true, false }), - "true ^ true ^ false"); - - assertEquals( - true ^ true ^ true, - BooleanUtils.xor(new boolean[] { true, true, true }), - "true ^ true ^ true"); + public void test_toStringYesNo_Boolean() { + assertNull(BooleanUtils.toStringYesNo(null)); + assertEquals("yes", BooleanUtils.toStringYesNo(Boolean.TRUE)); + assertEquals("no", BooleanUtils.toStringYesNo(Boolean.FALSE)); } @Test - public void testXor_object_nullInput() { - assertThrows(IllegalArgumentException.class, () -> BooleanUtils.xor((Boolean[]) null)); + public void testAnd_object_emptyInput() { + assertThrows(IllegalArgumentException.class, () -> BooleanUtils.and(new Boolean[] {})); } @Test - public void testXor_object_emptyInput() { - assertThrows(IllegalArgumentException.class, () -> BooleanUtils.xor(new Boolean[] {})); + public void testAnd_object_nullElementInput() { + assertThrows(IllegalArgumentException.class, () -> BooleanUtils.and(new Boolean[] {null})); } @Test - public void testXor_object_nullElementInput() { - assertThrows(IllegalArgumentException.class, () -> BooleanUtils.xor(new Boolean[] {null})); + public void testAnd_object_nullInput() { + assertThrows(IllegalArgumentException.class, () -> BooleanUtils.and((Boolean[]) null)); } @Test - public void testXor_object_validInput_2items() { - assertEquals( - false ^ false, - BooleanUtils.xor(new Boolean[] { Boolean.FALSE, Boolean.FALSE }).booleanValue(), - "false ^ false"); + public void testAnd_object_validInput_2items() { + assertTrue( + BooleanUtils + .and(new Boolean[] { Boolean.TRUE, Boolean.TRUE }) + .booleanValue(), + "False result for (true, true)"); - assertEquals( - false ^ true, - BooleanUtils.xor(new Boolean[] { Boolean.FALSE, Boolean.TRUE }).booleanValue(), - "false ^ true"); + assertTrue( + ! BooleanUtils + .and(new Boolean[] { Boolean.FALSE, Boolean.FALSE }) + .booleanValue(), + "True result for (false, false)"); - assertEquals( - true ^ false, - BooleanUtils.xor(new Boolean[] { Boolean.TRUE, Boolean.FALSE }).booleanValue(), - "true ^ false"); + assertTrue( + ! BooleanUtils + .and(new Boolean[] { Boolean.TRUE, Boolean.FALSE }) + .booleanValue(), + "True result for (true, false)"); - assertEquals( - true ^ true, - BooleanUtils.xor(new Boolean[] { Boolean.TRUE, Boolean.TRUE }).booleanValue(), - "true ^ true"); + assertTrue( + ! BooleanUtils + .and(new Boolean[] { Boolean.FALSE, Boolean.TRUE }) + .booleanValue(), + "True result for (false, true)"); } @Test - public void testXor_object_validInput_3items() { - assertEquals( - false ^ false ^ false, - BooleanUtils.xor( - new Boolean[] { - Boolean.FALSE, - Boolean.FALSE, - Boolean.FALSE }) - .booleanValue(), - "false ^ false ^ false"); + public void testAnd_object_validInput_3items() { + assertTrue( + ! BooleanUtils + .and( + new Boolean[] { + Boolean.FALSE, + Boolean.FALSE, + Boolean.TRUE }) + .booleanValue(), + "True result for (false, false, true)"); - assertEquals( - false ^ false ^ true, - BooleanUtils - .xor( - new Boolean[] { - Boolean.FALSE, - Boolean.FALSE, - Boolean.TRUE }) - .booleanValue(), - "false ^ false ^ true"); + assertTrue( + ! BooleanUtils + .and( + new Boolean[] { + Boolean.FALSE, + Boolean.TRUE, + Boolean.FALSE }) + .booleanValue(), + "True result for (false, true, false)"); - assertEquals( - false ^ true ^ false, - BooleanUtils - .xor( - new Boolean[] { - Boolean.FALSE, - Boolean.TRUE, - Boolean.FALSE }) - .booleanValue(), - "false ^ true ^ false"); + assertTrue( + ! BooleanUtils + .and( + new Boolean[] { + Boolean.TRUE, + Boolean.FALSE, + Boolean.FALSE }) + .booleanValue(), + "True result for (true, false, false)"); - assertEquals( - true ^ false ^ false, + assertTrue( BooleanUtils - .xor( - new Boolean[] { - Boolean.TRUE, - Boolean.FALSE, - Boolean.FALSE }) - .booleanValue(), - "true ^ false ^ false"); + .and(new Boolean[] { Boolean.TRUE, Boolean.TRUE, Boolean.TRUE }) + .booleanValue(), + "False result for (true, true, true)"); - assertEquals( - true ^ false ^ true, - BooleanUtils.xor( - new Boolean[] { - Boolean.TRUE, - Boolean.FALSE, - Boolean.TRUE }) - .booleanValue(), - "true ^ false ^ true"); + assertTrue( + ! BooleanUtils.and( + new Boolean[] { + Boolean.FALSE, + Boolean.FALSE, + Boolean.FALSE }) + .booleanValue(), + "True result for (false, false)"); - assertEquals( - true ^ true ^ false, - BooleanUtils.xor( - new Boolean[] { - Boolean.TRUE, - Boolean.TRUE, - Boolean.FALSE }) - .booleanValue(), - "true ^ true ^ false"); + assertTrue( + ! BooleanUtils.and( + new Boolean[] { + Boolean.TRUE, + Boolean.TRUE, + Boolean.FALSE }) + .booleanValue(), + "True result for (true, true, false)"); - assertEquals( - false ^ true ^ true, - BooleanUtils.xor( - new Boolean[] { - Boolean.FALSE, - Boolean.TRUE, - Boolean.TRUE }) - .booleanValue(), - "false ^ true ^ true"); + assertTrue( + ! BooleanUtils.and( + new Boolean[] { + Boolean.TRUE, + Boolean.FALSE, + Boolean.TRUE }) + .booleanValue(), + "True result for (true, false, true)"); - assertEquals( - true ^ true ^ true, - BooleanUtils.xor( + assertTrue( + ! BooleanUtils.and( new Boolean[] { - Boolean.TRUE, - Boolean.TRUE, - Boolean.TRUE }) - .booleanValue(), - "true ^ true ^ true"); + Boolean.FALSE, + Boolean.TRUE, + Boolean.TRUE }) + .booleanValue(), + "True result for (false, true, true)"); } - // testAnd - // ----------------------------------------------------------------------- @Test - public void testAnd_primitive_nullInput() { - assertThrows(IllegalArgumentException.class, () -> BooleanUtils.and((boolean[]) null)); + public void testAnd_primitive_emptyInput() { + assertThrows(IllegalArgumentException.class, () -> BooleanUtils.and(new boolean[] {})); } @Test - public void testAnd_primitive_emptyInput() { - assertThrows(IllegalArgumentException.class, () -> BooleanUtils.and(new boolean[] {})); + public void testAnd_primitive_nullInput() { + assertThrows(IllegalArgumentException.class, () -> BooleanUtils.and((boolean[]) null)); } @Test @@ -711,87 +598,105 @@ public void testAnd_primitive_validInput_3items() { } @Test - public void testAnd_object_nullInput() { - assertThrows(IllegalArgumentException.class, () -> BooleanUtils.and((Boolean[]) null)); + public void testCompare() { + assertTrue(BooleanUtils.compare(true, false) > 0); + assertEquals(0, BooleanUtils.compare(true, true)); + assertEquals(0, BooleanUtils.compare(false, false)); + assertTrue(BooleanUtils.compare(false, true) < 0); } @Test - public void testAnd_object_emptyInput() { - assertThrows(IllegalArgumentException.class, () -> BooleanUtils.and(new Boolean[] {})); + public void testConstructor() { + assertNotNull(new BooleanUtils()); + final Constructor[] cons = BooleanUtils.class.getDeclaredConstructors(); + assertEquals(1, cons.length); + assertTrue(Modifier.isPublic(cons[0].getModifiers())); + assertTrue(Modifier.isPublic(BooleanUtils.class.getModifiers())); + assertFalse(Modifier.isFinal(BooleanUtils.class.getModifiers())); } @Test - public void testAnd_object_nullElementInput() { - assertThrows(IllegalArgumentException.class, () -> BooleanUtils.and(new Boolean[] {null})); + public void testOr_object_emptyInput() { + assertThrows(IllegalArgumentException.class, () -> BooleanUtils.or(new Boolean[] {})); } @Test - public void testAnd_object_validInput_2items() { + public void testOr_object_nullElementInput() { + assertThrows(IllegalArgumentException.class, () -> BooleanUtils.or(new Boolean[] {null})); + } + + @Test + public void testOr_object_nullInput() { + assertThrows(IllegalArgumentException.class, () -> BooleanUtils.or((Boolean[]) null)); + } + + @Test + public void testOr_object_validInput_2items() { assertTrue( BooleanUtils - .and(new Boolean[] { Boolean.TRUE, Boolean.TRUE }) + .or(new Boolean[] { Boolean.TRUE, Boolean.TRUE }) .booleanValue(), "False result for (true, true)"); assertTrue( ! BooleanUtils - .and(new Boolean[] { Boolean.FALSE, Boolean.FALSE }) + .or(new Boolean[] { Boolean.FALSE, Boolean.FALSE }) .booleanValue(), "True result for (false, false)"); assertTrue( - ! BooleanUtils - .and(new Boolean[] { Boolean.TRUE, Boolean.FALSE }) + BooleanUtils + .or(new Boolean[] { Boolean.TRUE, Boolean.FALSE }) .booleanValue(), - "True result for (true, false)"); + "False result for (true, false)"); assertTrue( - ! BooleanUtils - .and(new Boolean[] { Boolean.FALSE, Boolean.TRUE }) + BooleanUtils + .or(new Boolean[] { Boolean.FALSE, Boolean.TRUE }) .booleanValue(), - "True result for (false, true)"); + "False result for (false, true)"); } @Test - public void testAnd_object_validInput_3items() { + public void testOr_object_validInput_3items() { assertTrue( - ! BooleanUtils - .and( + BooleanUtils + .or( new Boolean[] { Boolean.FALSE, Boolean.FALSE, Boolean.TRUE }) .booleanValue(), - "True result for (false, false, true)"); + "False result for (false, false, true)"); assertTrue( - ! BooleanUtils - .and( + BooleanUtils + .or( new Boolean[] { Boolean.FALSE, Boolean.TRUE, Boolean.FALSE }) .booleanValue(), - "True result for (false, true, false)"); + "False result for (false, true, false)"); assertTrue( - ! BooleanUtils - .and( + BooleanUtils + .or( new Boolean[] { Boolean.TRUE, Boolean.FALSE, Boolean.FALSE }) .booleanValue(), - "True result for (true, false, false)"); + "False result for (true, false, false)"); assertTrue( BooleanUtils - .and(new Boolean[] { Boolean.TRUE, Boolean.TRUE, Boolean.TRUE }) + .or(new Boolean[] { Boolean.TRUE, Boolean.TRUE, Boolean.TRUE }) .booleanValue(), "False result for (true, true, true)"); assertTrue( - ! BooleanUtils.and( + ! BooleanUtils.or( new Boolean[] { Boolean.FALSE, Boolean.FALSE, @@ -800,43 +705,41 @@ public void testAnd_object_validInput_3items() { "True result for (false, false)"); assertTrue( - ! BooleanUtils.and( + BooleanUtils.or( new Boolean[] { Boolean.TRUE, Boolean.TRUE, Boolean.FALSE }) .booleanValue(), - "True result for (true, true, false)"); + "False result for (true, true, false)"); assertTrue( - ! BooleanUtils.and( + BooleanUtils.or( new Boolean[] { Boolean.TRUE, Boolean.FALSE, Boolean.TRUE }) .booleanValue(), - "True result for (true, false, true)"); + "False result for (true, false, true)"); assertTrue( - ! BooleanUtils.and( + BooleanUtils.or( new Boolean[] { Boolean.FALSE, Boolean.TRUE, Boolean.TRUE }) .booleanValue(), - "True result for (false, true, true)"); + "False result for (false, true, true)"); } - // testOr - // ----------------------------------------------------------------------- @Test - public void testOr_primitive_nullInput() { - assertThrows(IllegalArgumentException.class, () -> BooleanUtils.or((boolean[]) null)); + public void testOr_primitive_emptyInput() { + assertThrows(IllegalArgumentException.class, () -> BooleanUtils.or(new boolean[] {})); } @Test - public void testOr_primitive_emptyInput() { - assertThrows(IllegalArgumentException.class, () -> BooleanUtils.or(new boolean[] {})); + public void testOr_primitive_nullInput() { + assertThrows(IllegalArgumentException.class, () -> BooleanUtils.or((boolean[]) null)); } @Test @@ -893,129 +796,204 @@ public void testOr_primitive_validInput_3items() { "False result for (false, true, true)"); } + @Test - public void testOr_object_nullInput() { - assertThrows(IllegalArgumentException.class, () -> BooleanUtils.or((Boolean[]) null)); + public void testXor_object_emptyInput() { + assertThrows(IllegalArgumentException.class, () -> BooleanUtils.xor(new Boolean[] {})); } @Test - public void testOr_object_emptyInput() { - assertThrows(IllegalArgumentException.class, () -> BooleanUtils.or(new Boolean[] {})); + public void testXor_object_nullElementInput() { + assertThrows(IllegalArgumentException.class, () -> BooleanUtils.xor(new Boolean[] {null})); } @Test - public void testOr_object_nullElementInput() { - assertThrows(IllegalArgumentException.class, () -> BooleanUtils.or(new Boolean[] {null})); + public void testXor_object_nullInput() { + assertThrows(IllegalArgumentException.class, () -> BooleanUtils.xor((Boolean[]) null)); } - @Test - public void testOr_object_validInput_2items() { - assertTrue( - BooleanUtils - .or(new Boolean[] { Boolean.TRUE, Boolean.TRUE }) - .booleanValue(), - "False result for (true, true)"); + public void testXor_object_validInput_2items() { + assertEquals( + false ^ false, + BooleanUtils.xor(new Boolean[] { Boolean.FALSE, Boolean.FALSE }).booleanValue(), + "false ^ false"); - assertTrue( - ! BooleanUtils - .or(new Boolean[] { Boolean.FALSE, Boolean.FALSE }) - .booleanValue(), - "True result for (false, false)"); + assertEquals( + false ^ true, + BooleanUtils.xor(new Boolean[] { Boolean.FALSE, Boolean.TRUE }).booleanValue(), + "false ^ true"); - assertTrue( - BooleanUtils - .or(new Boolean[] { Boolean.TRUE, Boolean.FALSE }) - .booleanValue(), - "False result for (true, false)"); + assertEquals( + true ^ false, + BooleanUtils.xor(new Boolean[] { Boolean.TRUE, Boolean.FALSE }).booleanValue(), + "true ^ false"); - assertTrue( - BooleanUtils - .or(new Boolean[] { Boolean.FALSE, Boolean.TRUE }) - .booleanValue(), - "False result for (false, true)"); + assertEquals( + true ^ true, + BooleanUtils.xor(new Boolean[] { Boolean.TRUE, Boolean.TRUE }).booleanValue(), + "true ^ true"); } @Test - public void testOr_object_validInput_3items() { - assertTrue( - BooleanUtils - .or( - new Boolean[] { - Boolean.FALSE, - Boolean.FALSE, - Boolean.TRUE }) - .booleanValue(), - "False result for (false, false, true)"); + public void testXor_object_validInput_3items() { + assertEquals( + false ^ false ^ false, + BooleanUtils.xor( + new Boolean[] { + Boolean.FALSE, + Boolean.FALSE, + Boolean.FALSE }) + .booleanValue(), + "false ^ false ^ false"); - assertTrue( + assertEquals( + false ^ false ^ true, BooleanUtils - .or( - new Boolean[] { - Boolean.FALSE, - Boolean.TRUE, - Boolean.FALSE }) - .booleanValue(), - "False result for (false, true, false)"); + .xor( + new Boolean[] { + Boolean.FALSE, + Boolean.FALSE, + Boolean.TRUE }) + .booleanValue(), + "false ^ false ^ true"); - assertTrue( + assertEquals( + false ^ true ^ false, BooleanUtils - .or( - new Boolean[] { - Boolean.TRUE, - Boolean.FALSE, - Boolean.FALSE }) - .booleanValue(), - "False result for (true, false, false)"); + .xor( + new Boolean[] { + Boolean.FALSE, + Boolean.TRUE, + Boolean.FALSE }) + .booleanValue(), + "false ^ true ^ false"); - assertTrue( + assertEquals( + true ^ false ^ false, BooleanUtils - .or(new Boolean[] { Boolean.TRUE, Boolean.TRUE, Boolean.TRUE }) - .booleanValue(), - "False result for (true, true, true)"); + .xor( + new Boolean[] { + Boolean.TRUE, + Boolean.FALSE, + Boolean.FALSE }) + .booleanValue(), + "true ^ false ^ false"); - assertTrue( - ! BooleanUtils.or( - new Boolean[] { - Boolean.FALSE, - Boolean.FALSE, - Boolean.FALSE }) - .booleanValue(), - "True result for (false, false)"); + assertEquals( + true ^ false ^ true, + BooleanUtils.xor( + new Boolean[] { + Boolean.TRUE, + Boolean.FALSE, + Boolean.TRUE }) + .booleanValue(), + "true ^ false ^ true"); - assertTrue( - BooleanUtils.or( - new Boolean[] { - Boolean.TRUE, - Boolean.TRUE, - Boolean.FALSE }) - .booleanValue(), - "False result for (true, true, false)"); + assertEquals( + true ^ true ^ false, + BooleanUtils.xor( + new Boolean[] { + Boolean.TRUE, + Boolean.TRUE, + Boolean.FALSE }) + .booleanValue(), + "true ^ true ^ false"); - assertTrue( - BooleanUtils.or( - new Boolean[] { - Boolean.TRUE, - Boolean.FALSE, - Boolean.TRUE }) - .booleanValue(), - "False result for (true, false, true)"); + assertEquals( + false ^ true ^ true, + BooleanUtils.xor( + new Boolean[] { + Boolean.FALSE, + Boolean.TRUE, + Boolean.TRUE }) + .booleanValue(), + "false ^ true ^ true"); - assertTrue( - BooleanUtils.or( + assertEquals( + true ^ true ^ true, + BooleanUtils.xor( new Boolean[] { - Boolean.FALSE, - Boolean.TRUE, - Boolean.TRUE }) - .booleanValue(), - "False result for (false, true, true)"); + Boolean.TRUE, + Boolean.TRUE, + Boolean.TRUE }) + .booleanValue(), + "true ^ true ^ true"); } @Test - public void testCompare() { - assertTrue(BooleanUtils.compare(true, false) > 0); - assertEquals(0, BooleanUtils.compare(true, true)); - assertEquals(0, BooleanUtils.compare(false, false)); - assertTrue(BooleanUtils.compare(false, true) < 0); + public void testXor_primitive_emptyInput() { + assertThrows(IllegalArgumentException.class, () -> BooleanUtils.xor(new boolean[] {})); + } + + @Test + public void testXor_primitive_nullInput() { + assertThrows(IllegalArgumentException.class, () -> BooleanUtils.xor((boolean[]) null)); + } + + @Test + public void testXor_primitive_validInput_2items() { + assertEquals( + true ^ true, + BooleanUtils.xor(new boolean[] { true, true }), + "true ^ true"); + + assertEquals( + false ^ false, + BooleanUtils.xor(new boolean[] { false, false }), + "false ^ false"); + + assertEquals( + true ^ false, + BooleanUtils.xor(new boolean[] { true, false }), + "true ^ false"); + + assertEquals( + false ^ true, + BooleanUtils.xor(new boolean[] { false, true }), + "false ^ true"); + } + + @Test + public void testXor_primitive_validInput_3items() { + assertEquals( + false ^ false ^ false, + BooleanUtils.xor(new boolean[] { false, false, false }), + "false ^ false ^ false"); + + assertEquals( + false ^ false ^ true, + BooleanUtils.xor(new boolean[] { false, false, true }), + "false ^ false ^ true"); + + assertEquals( + false ^ true ^ false, + BooleanUtils.xor(new boolean[] { false, true, false }), + "false ^ true ^ false"); + + assertEquals( + false ^ true ^ true, + BooleanUtils.xor(new boolean[] { false, true, true }), + "false ^ true ^ true"); + + assertEquals( + true ^ false ^ false, + BooleanUtils.xor(new boolean[] { true, false, false }), + "true ^ false ^ false"); + + assertEquals( + true ^ false ^ true, + BooleanUtils.xor(new boolean[] { true, false, true }), + "true ^ false ^ true"); + + assertEquals( + true ^ true ^ false, + BooleanUtils.xor(new boolean[] { true, true, false }), + "true ^ true ^ false"); + + assertEquals( + true ^ true ^ true, + BooleanUtils.xor(new boolean[] { true, true, true }), + "true ^ true ^ true"); } } From b2e7374bfb91b54d49dfb4d327de639ff1f4b127 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Mon, 28 Sep 2020 15:31:56 -0400 Subject: [PATCH 0365/3230] Add BooleanUtils.booleanValues(). Add BooleanUtils.primitiveValues(). Handy for tools and tests. Make next release version 3.12.0. --- pom.xml | 8 ++++---- src/changes/changes.xml | 5 ++++- .../org/apache/commons/lang3/BooleanUtils.java | 18 ++++++++++++++++++ .../apache/commons/lang3/BooleanUtilsTest.java | 14 ++++++++++++++ 4 files changed, 40 insertions(+), 5 deletions(-) diff --git a/pom.xml b/pom.xml index e3c2f7042fd..b1e6bfc01e3 100644 --- a/pom.xml +++ b/pom.xml @@ -26,7 +26,7 @@ 4.0.0 commons-lang3 - 3.12-SNAPSHOT + 3.12.0-SNAPSHOT Apache Commons Lang 2001 @@ -47,7 +47,7 @@ scm:git:http://gitbox.apache.org/repos/asf/commons-lang.git scm:git:https://gitbox.apache.org/repos/asf/commons-lang.git https://gitbox.apache.org/repos/asf?p=commons-lang.git - commons-lang-3.12 + commons-lang-3.12.0 @@ -587,7 +587,7 @@ lang3 org.apache.commons.lang3 - 3.12 + 3.12.0 (Java 8+) 2.6 @@ -624,7 +624,7 @@ 0.14.3 - 3.10 + 3.11 RC2 true scm:svn:https://dist.apache.org/repos/dist/dev/commons/lang diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 90fa7f55410..e624fc0ffa4 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -45,11 +45,14 @@ The type attribute can be add,update,fix,remove. - + Correct implementation of RandomUtils.nextLong(long, long) Restore handling of collections for non-JSON ToStringStyle #610. ContextedException Javadoc add missing semicolon #581. + + Add BooleanUtils.booleanValues(). + Add BooleanUtils.primitiveValues(). StringUtils.countMatches - clarify Javadoc. Remove redundant argument from substring call. diff --git a/src/main/java/org/apache/commons/lang3/BooleanUtils.java b/src/main/java/org/apache/commons/lang3/BooleanUtils.java index 39338538975..7b8885e3de0 100644 --- a/src/main/java/org/apache/commons/lang3/BooleanUtils.java +++ b/src/main/java/org/apache/commons/lang3/BooleanUtils.java @@ -99,6 +99,15 @@ public static Boolean and(final Boolean... array) { } } + /** + * Returns a new array of possible values (like an enum would). + * @return a new array of possible values (like an enum would). + * @since 3.12.0 + */ + public static Boolean[] booleanValues() { + return new Boolean[] {Boolean.FALSE, Boolean.TRUE}; + } + /** *

      Compares two {@code boolean} values. This is the same functionality as provided in Java 7.

      * @@ -280,6 +289,15 @@ public static Boolean or(final Boolean... array) { } } + /** + * Returns a new array of possible values (like an enum would). + * @return a new array of possible values (like an enum would). + * @since 3.12.0 + */ + public static boolean[] primitiveValues() { + return new boolean[] {false, true}; + } + /** *

      Converts a Boolean to a boolean handling {@code null} * by returning {@code false}.

      diff --git a/src/test/java/org/apache/commons/lang3/BooleanUtilsTest.java b/src/test/java/org/apache/commons/lang3/BooleanUtilsTest.java index 8920e851935..6eb6d1cefb5 100644 --- a/src/test/java/org/apache/commons/lang3/BooleanUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/BooleanUtilsTest.java @@ -16,6 +16,7 @@ */ package org.apache.commons.lang3; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; @@ -26,6 +27,7 @@ import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; +import java.util.Arrays; import org.junit.jupiter.api.Test; @@ -34,6 +36,13 @@ */ public class BooleanUtilsTest { + @Test + public void test_booleanValues() { + final Boolean[] expected = new Boolean[] {false, true}; + Arrays.sort(expected); + assertArrayEquals(expected, BooleanUtils.booleanValues()); + } + @Test public void test_isFalse_Boolean() { assertFalse(BooleanUtils.isFalse(Boolean.TRUE)); @@ -69,6 +78,11 @@ public void test_negate_Boolean() { assertSame(Boolean.FALSE, BooleanUtils.negate(Boolean.TRUE)); } + @Test + public void test_primitiveValues() { + assertArrayEquals(new boolean[] {false, true}, BooleanUtils.primitiveValues()); + } + @Test public void test_toBoolean_Boolean() { assertTrue(BooleanUtils.toBoolean(Boolean.TRUE)); From 737f32a06c6dd3918b03bd4d8e02835656f9e41d Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 1 Oct 2020 06:01:33 +0000 Subject: [PATCH 0366/3230] Bump actions/setup-java from v1.4.2 to v1.4.3 Bumps [actions/setup-java](https://github.com/actions/setup-java) from v1.4.2 to v1.4.3. - [Release notes](https://github.com/actions/setup-java/releases) - [Commits](https://github.com/actions/setup-java/compare/v1.4.2...d202f5dbf7256730fb690ec59f6381650114feb2) Signed-off-by: dependabot[bot] --- .github/workflows/maven.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml index 5f89c7c8060..6720e142b7b 100644 --- a/.github/workflows/maven.yml +++ b/.github/workflows/maven.yml @@ -39,7 +39,7 @@ jobs: restore-keys: | ${{ runner.os }}-maven- - name: Set up JDK ${{ matrix.java }} - uses: actions/setup-java@v1.4.2 + uses: actions/setup-java@v1.4.3 with: java-version: ${{ matrix.java }} - name: Build with Maven From 66681a764360380e27ea1f3dc617812025c7b7ee Mon Sep 17 00:00:00 2001 From: Rob Tompkins Date: Thu, 1 Oct 2020 10:07:30 -0400 Subject: [PATCH 0367/3230] (changes) Bump checkstyle from 8.36 to 8.36.2 --- src/changes/changes.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index e624fc0ffa4..679c5f9cfd0 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -54,6 +54,7 @@ The type attribute can be add,update,fix,remove. Add BooleanUtils.booleanValues(). Add BooleanUtils.primitiveValues(). + Bump checkstyle from 8.36 to 8.36.2 StringUtils.countMatches - clarify Javadoc. Remove redundant argument from substring call. Improve StringUtils.stripAccents conversion of remaining accents. From dd1c0d929288391577e40076c137026356c574c1 Mon Sep 17 00:00:00 2001 From: Rob Tompkins Date: Thu, 1 Oct 2020 10:10:16 -0400 Subject: [PATCH 0368/3230] (changes) Bump spotbugs from 4.1.2 to 4.1.3 --- src/changes/changes.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 679c5f9cfd0..27cec876bee 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -54,6 +54,7 @@ The type attribute can be add,update,fix,remove. Add BooleanUtils.booleanValues(). Add BooleanUtils.primitiveValues(). + Bump spotbugs from 4.1.2 to 4.1.3 Bump checkstyle from 8.36 to 8.36.2 StringUtils.countMatches - clarify Javadoc. Remove redundant argument from substring call. From c1c4a7535bfaa377eb7a72de7b7e36a04f33a2f8 Mon Sep 17 00:00:00 2001 From: Rob Tompkins Date: Thu, 1 Oct 2020 10:16:03 -0400 Subject: [PATCH 0369/3230] (changes) Bump junit-jupiter from 5.6.2 to 5.7.0 --- src/changes/changes.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 27cec876bee..bff8f6d90e7 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -54,6 +54,7 @@ The type attribute can be add,update,fix,remove. Add BooleanUtils.booleanValues(). Add BooleanUtils.primitiveValues(). + Bump junit-jupiter from 5.6.2 to 5.7.0 Bump spotbugs from 4.1.2 to 4.1.3 Bump checkstyle from 8.36 to 8.36.2 StringUtils.countMatches - clarify Javadoc. From 3a3c517b4074b752d2e17153b8f8b5ab225b9f92 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 2 Oct 2020 11:08:39 -0400 Subject: [PATCH 0370/3230] Bump junit-pioneer from 0.9.0 to 0.9.2 (#624) Bumps [junit-pioneer](https://github.com/junit-pioneer/junit-pioneer) from 0.9.0 to 0.9.2. - [Release notes](https://github.com/junit-pioneer/junit-pioneer/releases) - [Changelog](https://github.com/junit-pioneer/junit-pioneer/blob/master/docs/release-notes.md) - [Commits](https://github.com/junit-pioneer/junit-pioneer/compare/v0.9.0...v0.9.2) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index a178bbf133d..db0778f0e08 100644 --- a/pom.xml +++ b/pom.xml @@ -525,7 +525,7 @@ org.junit-pioneer junit-pioneer - 0.9.0 + 0.9.2 test From a6f97f358ff2523c05eb5e4d952090a100ca4b10 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Fri, 2 Oct 2020 11:15:43 -0400 Subject: [PATCH 0371/3230] Bump junit-pioneer from 0.9.0 to 0.9.2 #624. --- src/changes/changes.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index bff8f6d90e7..d26f2a2a9a3 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -64,7 +64,7 @@ The type attribute can be add,update,fix,remove. Enable Dependabot #587. Update spotbugs-maven-plugin from 4.0.0 to 4.1.2, #593, #596, #609. Update biz.aQute.bndlib from 5.1.1 to 5.1.2 #592. - Update junit-pioneer from 0.6.0 to 0.9.0, #589, #597, #600. + Update junit-pioneer from 0.6.0 to 0.9.2, #589, #597, #600, #624. Update checkstyle from 8.34 to 8.36 #594, #614. Update actions/checkout from v2.3.1 to v2.3.2 #601. Update actions/setup-java from v1.4.0 to v1.4.2 #612. From 3e9526de77d0e330e07c9c479cd3947eba6abc97 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sat, 3 Oct 2020 10:27:36 -0400 Subject: [PATCH 0372/3230] Bump spotbugs-maven-plugin from 4.0.4 to 4.1.3 (#623) Bumps [spotbugs-maven-plugin](https://github.com/spotbugs/spotbugs-maven-plugin) from 4.0.4 to 4.1.3. - [Release notes](https://github.com/spotbugs/spotbugs-maven-plugin/releases) - [Commits](https://github.com/spotbugs/spotbugs-maven-plugin/compare/spotbugs-maven-plugin-4.0.4...spotbugs-maven-plugin-4.1.3) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index db0778f0e08..2508c6ce7c3 100644 --- a/pom.xml +++ b/pom.xml @@ -606,7 +606,7 @@ 8.36.2 src/site/resources/checkstyle - 4.0.4 + 4.1.3 4.1.3 false true From 8ff63a0da3a82c8aae303f9c28184240196cda00 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sat, 3 Oct 2020 10:28:45 -0400 Subject: [PATCH 0373/3230] Bump spotbugs-maven-plugin from 4.0.4 to 4.1.3 #623. --- src/changes/changes.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index d26f2a2a9a3..e6cd3727f07 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -62,7 +62,7 @@ The type attribute can be add,update,fix,remove. Improve StringUtils.stripAccents conversion of remaining accents. ArrayUtils.toPrimitive(Object) does not support boolean and other types #607. Enable Dependabot #587. - Update spotbugs-maven-plugin from 4.0.0 to 4.1.2, #593, #596, #609. + Update spotbugs-maven-plugin from 4.0.0 to 4.1.3, #593, #596, #609, #623. Update biz.aQute.bndlib from 5.1.1 to 5.1.2 #592. Update junit-pioneer from 0.6.0 to 0.9.2, #589, #597, #600, #624. Update checkstyle from 8.34 to 8.36 #594, #614. From 206a8f1f4456f3042f0858a48f9cf9c6cab62a70 Mon Sep 17 00:00:00 2001 From: Edgar Asatryan Date: Sat, 17 Oct 2020 16:22:18 +0400 Subject: [PATCH 0374/3230] [LANG-1608] Include junit-bom for dependency version alignment. --- pom.xml | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 2508c6ce7c3..4b5f1c95d83 100644 --- a/pom.xml +++ b/pom.xml @@ -513,13 +513,24 @@ + + + + org.junit + junit-bom + 5.7.0 + pom + import + + + + org.junit.jupiter junit-jupiter - 5.7.0 test From 43c80576cfe661b6f832ec7db51ab0077711f0ed Mon Sep 17 00:00:00 2001 From: Alex Herbert Date: Sat, 17 Oct 2020 14:00:54 +0100 Subject: [PATCH 0375/3230] LANG-1608: Track changes --- src/changes/changes.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index e6cd3727f07..d5f9099e484 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -50,6 +50,7 @@ The type attribute can be add,update,fix,remove. Correct implementation of RandomUtils.nextLong(long, long) Restore handling of collections for non-JSON ToStringStyle #610. ContextedException Javadoc add missing semicolon #581. + Resolve JUnit pioneer transitive dependencies using JUnit BOM. Add BooleanUtils.booleanValues(). Add BooleanUtils.primitiveValues(). From 6fc542586f6d6e309ec0d1ecf5c5902f0c2e8f06 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 20 Oct 2020 10:17:11 -0400 Subject: [PATCH 0376/3230] Bump biz.aQute.bndlib from 5.1.2 to 5.2.0 (#628) Bumps [biz.aQute.bndlib](https://github.com/bndtools/bnd) from 5.1.2 to 5.2.0. - [Release notes](https://github.com/bndtools/bnd/releases) - [Changelog](https://github.com/bndtools/bnd/blob/master/docs/ADDING_RELEASE_DOCS.md) - [Commits](https://github.com/bndtools/bnd/commits) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 4b5f1c95d83..947b35cbaaa 100644 --- a/pom.xml +++ b/pom.xml @@ -785,7 +785,7 @@ biz.aQute.bnd biz.aQute.bndlib - 5.1.2 + 5.2.0 From 02d6a732fdbbb8a2985dcaf8de1386aa297b6b3b Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 20 Oct 2020 10:18:24 -0400 Subject: [PATCH 0377/3230] Bump spotbugs from 4.1.3 to 4.1.4 (#627) Bumps [spotbugs](https://github.com/spotbugs/spotbugs) from 4.1.3 to 4.1.4. - [Release notes](https://github.com/spotbugs/spotbugs/releases) - [Changelog](https://github.com/spotbugs/spotbugs/blob/master/CHANGELOG.md) - [Commits](https://github.com/spotbugs/spotbugs/compare/4.1.3...4.1.4) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 947b35cbaaa..6eb8b9131e3 100644 --- a/pom.xml +++ b/pom.xml @@ -618,7 +618,7 @@ src/site/resources/checkstyle 4.1.3 - 4.1.3 + 4.1.4 false true From 40b4b03d264205969305cee0e85a50ed81d1c946 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 20 Oct 2020 10:19:42 -0400 Subject: [PATCH 0378/3230] Bump junit-pioneer from 0.9.2 to 1.0.0 (#625) Bumps [junit-pioneer](https://github.com/junit-pioneer/junit-pioneer) from 0.9.2 to 1.0.0. - [Release notes](https://github.com/junit-pioneer/junit-pioneer/releases) - [Changelog](https://github.com/junit-pioneer/junit-pioneer/blob/master/docs/release-notes.md) - [Commits](https://github.com/junit-pioneer/junit-pioneer/compare/v0.9.2...v1.0.0) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 6eb8b9131e3..0aad6a34e8a 100644 --- a/pom.xml +++ b/pom.xml @@ -536,7 +536,7 @@ org.junit-pioneer junit-pioneer - 0.9.2 + 1.0.0 test From e14a2d92269d23c09e38e8ab5fc51c2eb1785610 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Tue, 20 Oct 2020 10:21:56 -0400 Subject: [PATCH 0379/3230] Update dependencies. - Bump biz.aQute.bndlib from 5.1.2 to 5.2.0 #628. - Bump spotbugs from 4.1.3 to 4.1.4 #627. - Bump junit-pioneer from 0.9.2 to 1.0.0 #625. --- src/changes/changes.xml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index d5f9099e484..fdb5c698082 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -55,8 +55,8 @@ The type attribute can be add,update,fix,remove. Add BooleanUtils.booleanValues(). Add BooleanUtils.primitiveValues(). - Bump junit-jupiter from 5.6.2 to 5.7.0 - Bump spotbugs from 4.1.2 to 4.1.3 + Bump junit-jupiter from 5.6.2 to 5.7.0. + Bump spotbugs from 4.1.2 to 4.1.4, #627. Bump checkstyle from 8.36 to 8.36.2 StringUtils.countMatches - clarify Javadoc. Remove redundant argument from substring call. @@ -64,8 +64,8 @@ The type attribute can be add,update,fix,remove. ArrayUtils.toPrimitive(Object) does not support boolean and other types #607. Enable Dependabot #587. Update spotbugs-maven-plugin from 4.0.0 to 4.1.3, #593, #596, #609, #623. - Update biz.aQute.bndlib from 5.1.1 to 5.1.2 #592. - Update junit-pioneer from 0.6.0 to 0.9.2, #589, #597, #600, #624. + Update biz.aQute.bndlib from 5.1.1 to 5.2.0 #592, #628. + Update junit-pioneer from 0.6.0 to 1.0.0, #589, #597, #600, #624, #625. Update checkstyle from 8.34 to 8.36 #594, #614. Update actions/checkout from v2.3.1 to v2.3.2 #601. Update actions/setup-java from v1.4.0 to v1.4.2 #612. From d05ad7abd6093f26e79c15e585c77c7102c3a9df Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Tue, 20 Oct 2020 10:47:07 -0400 Subject: [PATCH 0380/3230] Add missing Javadoc. --- .../concurrent/AbstractCircuitBreaker.java | 4 ++++ .../apache/commons/lang3/stream/Streams.java | 10 ++++++++++ .../text/translate/NumericEntityUnescaper.java | 17 ++++++++++++++++- 3 files changed, 30 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/apache/commons/lang3/concurrent/AbstractCircuitBreaker.java b/src/main/java/org/apache/commons/lang3/concurrent/AbstractCircuitBreaker.java index 01079247559..05c1cc97404 100644 --- a/src/main/java/org/apache/commons/lang3/concurrent/AbstractCircuitBreaker.java +++ b/src/main/java/org/apache/commons/lang3/concurrent/AbstractCircuitBreaker.java @@ -27,6 +27,7 @@ * @since 3.5 */ public abstract class AbstractCircuitBreaker implements CircuitBreaker { + /** * The name of the open property as it is passed to registered * change listeners. @@ -139,6 +140,8 @@ public void removeChangeListener(final PropertyChangeListener listener) { * {@code CircuitBreaker}. */ protected enum State { + + /** The closed state. */ CLOSED { /** * {@inheritDoc} @@ -149,6 +152,7 @@ public State oppositeState() { } }, + /** The open state. */ OPEN { /** * {@inheritDoc} diff --git a/src/main/java/org/apache/commons/lang3/stream/Streams.java b/src/main/java/org/apache/commons/lang3/stream/Streams.java index ff4da1a68f7..9dd75e92970 100644 --- a/src/main/java/org/apache/commons/lang3/stream/Streams.java +++ b/src/main/java/org/apache/commons/lang3/stream/Streams.java @@ -66,10 +66,20 @@ */ public class Streams { + /** + * A Collector type for arrays. + * + * @param The array type. + */ public static class ArrayCollector implements Collector, O[]> { private static final Set characteristics = Collections.emptySet(); private final Class elementType; + /** + * Constructs a new instance for the given element type. + * + * @param elementType The element type. + */ public ArrayCollector(final Class elementType) { this.elementType = elementType; } diff --git a/src/main/java/org/apache/commons/lang3/text/translate/NumericEntityUnescaper.java b/src/main/java/org/apache/commons/lang3/text/translate/NumericEntityUnescaper.java index e765825ab2a..670fb07db3b 100644 --- a/src/main/java/org/apache/commons/lang3/text/translate/NumericEntityUnescaper.java +++ b/src/main/java/org/apache/commons/lang3/text/translate/NumericEntityUnescaper.java @@ -36,8 +36,23 @@ @Deprecated public class NumericEntityUnescaper extends CharSequenceTranslator { + /** Enumerates NumericEntityUnescaper options for unescaping. */ public enum OPTION { - semiColonRequired, semiColonOptional, errorIfNoSemiColon + + /** + * Require a semicolon. + */ + semiColonRequired, + + /** + * Do not require a semicolon. + */ + semiColonOptional, + + /** + * Throw an exception if a semi-colon is missing. + */ + errorIfNoSemiColon } // TODO?: Create an OptionsSet class to hide some of the conditional logic below From b8204aa29b10d02777b93eb38307075e02518454 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Tue, 20 Oct 2020 11:05:14 -0400 Subject: [PATCH 0381/3230] Checkstyle: Whitepace. --- .../apache/commons/lang3/concurrent/AbstractCircuitBreaker.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/apache/commons/lang3/concurrent/AbstractCircuitBreaker.java b/src/main/java/org/apache/commons/lang3/concurrent/AbstractCircuitBreaker.java index 05c1cc97404..a27d7f84654 100644 --- a/src/main/java/org/apache/commons/lang3/concurrent/AbstractCircuitBreaker.java +++ b/src/main/java/org/apache/commons/lang3/concurrent/AbstractCircuitBreaker.java @@ -140,7 +140,7 @@ public void removeChangeListener(final PropertyChangeListener listener) { * {@code CircuitBreaker}. */ protected enum State { - + /** The closed state. */ CLOSED { /** From bcdff98f02c3ef011187f2dbf7934a3ea3a48db5 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Tue, 20 Oct 2020 11:45:46 -0400 Subject: [PATCH 0382/3230] Sort methods. --- .../lang3/time/FastDateParserTest.java | 822 +++++++++--------- 1 file changed, 411 insertions(+), 411 deletions(-) diff --git a/src/test/java/org/apache/commons/lang3/time/FastDateParserTest.java b/src/test/java/org/apache/commons/lang3/time/FastDateParserTest.java index 5a15ea3c9be..817de7b98bd 100644 --- a/src/test/java/org/apache/commons/lang3/time/FastDateParserTest.java +++ b/src/test/java/org/apache/commons/lang3/time/FastDateParserTest.java @@ -45,32 +45,101 @@ * @since 3.2 */ public class FastDateParserTest { + private enum Expected1806 { + India(INDIA, "+05", "+0530", "+05:30", true), + Greenwich(GMT, "Z", "Z", "Z", false), + NewYork(NEW_YORK, "-05", "-0500", "-05:00", false); + + final TimeZone zone; + + final String one; + final String two; + final String three; + final long offset; + Expected1806(final TimeZone zone, final String one, final String two, final String three, final boolean hasHalfHourOffset) { + this.zone = zone; + this.one = one; + this.two = two; + this.three = three; + this.offset = hasHalfHourOffset ?30*60*1000 :0; + } + } private static final String SHORT_FORMAT_NOERA = "y/M/d/h/a/m/s/E"; private static final String LONG_FORMAT_NOERA = "yyyy/MMMM/dddd/hhhh/mmmm/ss/aaaa/EEEE"; private static final String SHORT_FORMAT = "G/" + SHORT_FORMAT_NOERA; - private static final String LONG_FORMAT = "GGGG/" + LONG_FORMAT_NOERA; + private static final String LONG_FORMAT = "GGGG/" + LONG_FORMAT_NOERA; private static final String yMdHmsSZ = "yyyy-MM-dd'T'HH:mm:ss.SSS Z"; private static final String DMY_DOT = "dd.MM.yyyy"; private static final String YMD_SLASH = "yyyy/MM/dd"; private static final String MDY_DASH = "MM-DD-yyyy"; - private static final String MDY_SLASH = "MM/DD/yyyy"; + private static final String MDY_SLASH = "MM/DD/yyyy"; private static final TimeZone REYKJAVIK = TimeZone.getTimeZone("Atlantic/Reykjavik"); private static final TimeZone NEW_YORK = TimeZone.getTimeZone("America/New_York"); private static final TimeZone GMT = TimeZone.getTimeZone("GMT"); + private static final TimeZone INDIA = TimeZone.getTimeZone("Asia/Calcutta"); private static final Locale SWEDEN = new Locale("sv", "SE"); - DateParser getInstance(final String format) { - return getInstance(format, TimeZone.getDefault(), Locale.getDefault()); + private static Calendar initializeCalendar(final TimeZone tz) { + final Calendar cal = Calendar.getInstance(tz); + cal.set(Calendar.YEAR, 2001); + cal.set(Calendar.MONTH, 1); // not daylight savings + cal.set(Calendar.DAY_OF_MONTH, 4); + cal.set(Calendar.HOUR_OF_DAY, 12); + cal.set(Calendar.MINUTE, 8); + cal.set(Calendar.SECOND, 56); + cal.set(Calendar.MILLISECOND, 235); + return cal; + } + + private void checkParse(final Locale locale, final Calendar cal, final SimpleDateFormat sdf, final DateParser fdf) throws ParseException { + final String formattedDate= sdf.format(cal.getTime()); + checkParse(locale, sdf, fdf, formattedDate); + checkParse(locale, sdf, fdf, formattedDate.toLowerCase(locale)); + checkParse(locale, sdf, fdf, formattedDate.toUpperCase(locale)); + } + + private void checkParse(final Locale locale, final SimpleDateFormat sdf, final DateParser fdf, final String formattedDate) throws ParseException { + try { + final Date expectedTime = sdf.parse(formattedDate); + final Date actualTime = fdf.parse(formattedDate); + assertEquals(expectedTime, actualTime, "locale : " + locale + " formattedDate : " + formattedDate + "\n"); + } catch (Exception e) { + fail("locale : " + locale + " formattedDate : " + formattedDate + " error : " + e + "\n", e); + } } private DateParser getDateInstance(final int dateStyle, final Locale locale) { return getInstance(FormatCache.getPatternForStyle(Integer.valueOf(dateStyle), null, locale), TimeZone.getDefault(), Locale.getDefault()); } + private Calendar getEraStart(int year, final TimeZone zone, final Locale locale) { + final Calendar cal = Calendar.getInstance(zone, locale); + cal.clear(); + + // http://docs.oracle.com/javase/6/docs/technotes/guides/intl/calendar.doc.html + if (locale.equals(FastDateParser.JAPANESE_IMPERIAL)) { + if (year < 1868) { + cal.set(Calendar.ERA, 0); + cal.set(Calendar.YEAR, 1868-year); + } + } else { + if (year < 0) { + cal.set(Calendar.ERA, GregorianCalendar.BC); + year= -year; + } + cal.set(Calendar.YEAR, year/100 * 100); + } + return cal; + } + + DateParser getInstance(final String format) { + return getInstance(format, TimeZone.getDefault(), Locale.getDefault()); + } + private DateParser getInstance(final String format, final Locale locale) { return getInstance(format, TimeZone.getDefault(), locale); } @@ -92,6 +161,29 @@ protected DateParser getInstance(final String format, final TimeZone timeZone, f return new FastDateParser(format, timeZone, locale, null); } + @Test + public void java15BuggyLocaleTest() throws ParseException { + final String buggyLocaleName = "ff_LR_#Adlm"; + Locale buggyLocale = null; + for (final Locale locale : Locale.getAvailableLocales()) { + if (buggyLocaleName.equals(locale.toString())) { + buggyLocale = locale; + break; + } + } + if (buggyLocale == null) { + return; + } + testSingleLocale(buggyLocale); + } + + @Test + public void java15BuggyLocaleTestAll() throws ParseException { + for (final Locale locale : Locale.getAvailableLocales()) { + testSingleLocale(locale); + } + } + @Test public void test_Equality_Hash() { final DateParser[] parsers= { @@ -116,51 +208,31 @@ public void test_Equality_Hash() { } } - @Test - public void testParseZone() throws ParseException { - final Calendar cal= Calendar.getInstance(NEW_YORK, Locale.US); - cal.clear(); - cal.set(2003, Calendar.JULY, 10, 16, 33, 20); - final DateParser fdf = getInstance(yMdHmsSZ, NEW_YORK, Locale.US); + @Test + public void test1806() throws ParseException { + final String formatStub = "yyyy-MM-dd'T'HH:mm:ss.SSS"; + final String dateStub = "2001-02-04T12:08:56.235"; - assertEquals(cal.getTime(), fdf.parse("2003-07-10T15:33:20.000 -0500")); - assertEquals(cal.getTime(), fdf.parse("2003-07-10T15:33:20.000 GMT-05:00")); - assertEquals(cal.getTime(), fdf.parse("2003-07-10T16:33:20.000 Eastern Daylight Time")); - assertEquals(cal.getTime(), fdf.parse("2003-07-10T16:33:20.000 EDT")); + for (final Expected1806 trial : Expected1806.values()) { + final Calendar cal = initializeCalendar(trial.zone); - cal.setTimeZone(TimeZone.getTimeZone("GMT-3")); - cal.set(2003, Calendar.FEBRUARY, 10, 9, 0, 0); + final String message = trial.zone.getDisplayName()+";"; - assertEquals(cal.getTime(), fdf.parse("2003-02-10T09:00:00.000 -0300")); + DateParser parser = getInstance(formatStub+"X", trial.zone); + assertEquals(cal.getTime().getTime(), parser.parse(dateStub+trial.one).getTime()-trial.offset, message+trial.one); - cal.setTimeZone(TimeZone.getTimeZone("GMT+5")); - cal.set(2003, Calendar.FEBRUARY, 10, 15, 5, 6); + parser = getInstance(formatStub+"XX", trial.zone); + assertEquals(cal.getTime(), parser.parse(dateStub+trial.two), message+trial.two); - assertEquals(cal.getTime(), fdf.parse("2003-02-10T15:05:06.000 +0500")); + parser = getInstance(formatStub+"XXX", trial.zone); + assertEquals(cal.getTime(), parser.parse(dateStub+trial.three), message+trial.three); + } } @Test - public void testParseLongShort() throws ParseException { - final Calendar cal= Calendar.getInstance(NEW_YORK, Locale.US); - cal.clear(); - cal.set(2003, Calendar.FEBRUARY, 10, 15, 33, 20); - cal.set(Calendar.MILLISECOND, 989); - cal.setTimeZone(NEW_YORK); - - DateParser fdf = getInstance("yyyy GGGG MMMM dddd aaaa EEEE HHHH mmmm ssss SSSS ZZZZ", NEW_YORK, Locale.US); - - assertEquals(cal.getTime(), fdf.parse("2003 AD February 0010 PM Monday 0015 0033 0020 0989 GMT-05:00")); - cal.set(Calendar.ERA, GregorianCalendar.BC); - - final Date parse = fdf.parse("2003 BC February 0010 PM Saturday 0015 0033 0020 0989 GMT-05:00"); - assertEquals(cal.getTime(), parse); - - fdf = getInstance("y G M d a E H m s S Z", NEW_YORK, Locale.US); - assertEquals(cal.getTime(), fdf.parse("03 BC 2 10 PM Sat 15 33 20 989 -0500")); - - cal.set(Calendar.ERA, GregorianCalendar.AD); - assertEquals(cal.getTime(), fdf.parse("03 AD 2 10 PM Saturday 15 33 20 989 -0500")); + public void test1806Argument() { + assertThrows(IllegalArgumentException.class, () -> getInstance("XXXX")); } @Test @@ -198,126 +270,146 @@ public void testAmPm() throws ParseException { assertEquals(cal.getTime(), H.parse("2010-08-01 12:33:20")); } - private Calendar getEraStart(int year, final TimeZone zone, final Locale locale) { - final Calendar cal = Calendar.getInstance(zone, locale); - cal.clear(); + @Test + public void testDayNumberOfWeek() throws ParseException { + final DateParser parser = getInstance("u"); + final Calendar calendar = Calendar.getInstance(); - // http://docs.oracle.com/javase/6/docs/technotes/guides/intl/calendar.doc.html - if (locale.equals(FastDateParser.JAPANESE_IMPERIAL)) { - if (year < 1868) { - cal.set(Calendar.ERA, 0); - cal.set(Calendar.YEAR, 1868-year); - } - } else { - if (year < 0) { - cal.set(Calendar.ERA, GregorianCalendar.BC); - year= -year; - } - cal.set(Calendar.YEAR, year/100 * 100); - } - return cal; - } + calendar.setTime(parser.parse("1")); + assertEquals(Calendar.MONDAY, calendar.get(Calendar.DAY_OF_WEEK)); - private void validateSdfFormatFdpParseEquality(final String format, final Locale locale, final TimeZone tz, final DateParser fdp, final Date in, final int year, final Date cs) throws ParseException { - final SimpleDateFormat sdf = new SimpleDateFormat(format, locale); - sdf.setTimeZone(tz); - if (format.equals(SHORT_FORMAT)) { - sdf.set2DigitYearStart( cs ); - } - final String fmt = sdf.format(in); - try { - final Date out = fdp.parse(fmt); - assertEquals(in, out, locale.toString()+" "+in+" "+ format+ " "+tz.getID()); - } catch (final ParseException pe) { - if (year >= 1868 || !locale.getCountry().equals("JP")) {// LANG-978 - throw pe; - } - } + calendar.setTime(parser.parse("6")); + assertEquals(Calendar.SATURDAY, calendar.get(Calendar.DAY_OF_WEEK)); + + calendar.setTime(parser.parse("7")); + assertEquals(Calendar.SUNDAY, calendar.get(Calendar.DAY_OF_WEEK)); } @Test - // Check that all Locales can parse the formats we use - public void testParses() throws Exception { - for (final String format : new String[]{LONG_FORMAT, SHORT_FORMAT}) { - for (final Locale locale : Locale.getAvailableLocales()) { - for (final TimeZone tz : new TimeZone[]{NEW_YORK, REYKJAVIK, GMT}) { - for (final int year : new int[]{2003, 1940, 1868, 1867, 1, -1, -1940}) { - final Calendar cal= getEraStart(year, tz, locale); - final Date centuryStart= cal.getTime(); - - cal.set(Calendar.MONTH, 1); - cal.set(Calendar.DAY_OF_MONTH, 10); - final Date in= cal.getTime(); + public void testDayOf() throws ParseException { + final Calendar cal= Calendar.getInstance(NEW_YORK, Locale.US); + cal.clear(); + cal.set(2003, Calendar.FEBRUARY, 10); - final FastDateParser fdp= new FastDateParser(format, tz, locale, centuryStart); - validateSdfFormatFdpParseEquality(format, locale, tz, fdp, in, year, centuryStart); - } - } - } - } + final DateParser fdf = getInstance("W w F D y", NEW_YORK, Locale.US); + assertEquals(cal.getTime(), fdf.parse("3 7 2 41 03")); } - // we cannot use historic dates to test timezone parsing, some timezones have second offsets - // as well as hours and minutes which makes the z formats a low fidelity round trip @Test - public void testTzParses() throws Exception { - // Check that all Locales can parse the time formats we use - for (final Locale locale : Locale.getAvailableLocales()) { - final FastDateParser fdp= new FastDateParser("yyyy/MM/dd z", TimeZone.getDefault(), locale); + public void testEquals() { + final DateParser parser1= getInstance(YMD_SLASH); + final DateParser parser2= getInstance(YMD_SLASH); - for (final TimeZone tz : new TimeZone[]{NEW_YORK, REYKJAVIK, GMT}) { - final Calendar cal= Calendar.getInstance(tz, locale); - cal.clear(); - cal.set(Calendar.YEAR, 2000); - cal.set(Calendar.MONTH, 1); - cal.set(Calendar.DAY_OF_MONTH, 10); - final Date expected= cal.getTime(); + assertEquals(parser1, parser2); + assertEquals(parser1.hashCode(), parser2.hashCode()); - final Date actual = fdp.parse("2000/02/10 "+tz.getDisplayName(locale)); - assertEquals(expected, actual, "tz:"+tz.getID()+" locale:"+locale.getDisplayName()); - } - } + assertNotEquals(parser1, new Object()); } - @Test - public void testLocales_Long_AD() throws Exception { - testLocales(LONG_FORMAT, false); - } + public void testJpLocales() throws ParseException { - @Test - public void testLocales_Long_BC() throws Exception { - testLocales(LONG_FORMAT, true); - } + final Calendar cal= Calendar.getInstance(GMT); + cal.clear(); + cal.set(2003, Calendar.FEBRUARY, 10); + cal.set(Calendar.ERA, GregorianCalendar.BC); + + final Locale locale = LocaleUtils.toLocale("zh"); + // ja_JP_JP cannot handle dates before 1868 properly + + final SimpleDateFormat sdf = new SimpleDateFormat(LONG_FORMAT, locale); + final DateParser fdf = getInstance(LONG_FORMAT, locale); + + // If parsing fails, a ParseException will be thrown and the test will fail + checkParse(locale, cal, sdf, fdf); + } @Test - public void testLocales_Short_AD() throws Exception { - testLocales(SHORT_FORMAT, false); + public void testLANG_831() throws Exception { + testSdfAndFdp("M E", "3 Tue", true); } @Test - public void testLocales_Short_BC() throws Exception { - testLocales(SHORT_FORMAT, true); + public void testLANG_832() throws Exception { + testSdfAndFdp("'d'd", "d3", false); // OK + testSdfAndFdp("'d'd'", "d3", true); // should fail (unterminated quote) } @Test - public void testLocales_LongNoEra_AD() throws Exception { - testLocales(LONG_FORMAT_NOERA, false); + public void testLang1121() throws ParseException { + final TimeZone kst = TimeZone.getTimeZone("KST"); + final DateParser fdp = getInstance("yyyyMMdd", kst, Locale.KOREA); + + assertThrows(ParseException.class, () -> fdp.parse("2015")); + + // Wed Apr 29 00:00:00 KST 2015 + Date actual = fdp.parse("20150429"); + final Calendar cal = Calendar.getInstance(kst, Locale.KOREA); + cal.clear(); + cal.set(2015, 3, 29); + Date expected = cal.getTime(); + assertEquals(expected, actual); + + final SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd", Locale.KOREA); + df.setTimeZone(kst); + expected = df.parse("20150429113100"); + + // Thu Mar 16 00:00:00 KST 81724 + actual = fdp.parse("20150429113100"); + assertEquals(expected, actual); } @Test - public void testLocales_LongNoEra_BC() throws Exception { - testLocales(LONG_FORMAT_NOERA, true); + public void testLang1380() throws ParseException { + final Calendar expected = Calendar.getInstance(GMT, Locale.FRANCE); + expected.clear(); + expected.set(2014, Calendar.APRIL, 14); + + final DateParser fdp = getInstance("dd MMM yyyy", GMT, Locale.FRANCE); + assertEquals(expected.getTime(), fdp.parse("14 avril 2014")); + assertEquals(expected.getTime(), fdp.parse("14 avr. 2014")); + assertEquals(expected.getTime(), fdp.parse("14 avr 2014")); } @Test - public void testLocales_ShortNoEra_AD() throws Exception { - testLocales(SHORT_FORMAT_NOERA, false); + public void testLang303() throws ParseException { + DateParser parser = getInstance(YMD_SLASH); + final Calendar cal = Calendar.getInstance(); + cal.set(2004, Calendar.DECEMBER, 31); + + final Date date = parser.parse("2004/11/31"); + + parser = SerializationUtils.deserialize(SerializationUtils.serialize((Serializable) parser)); + assertEquals(date, parser.parse("2004/11/31")); } @Test - public void testLocales_ShortNoEra_BC() throws Exception { - testLocales(SHORT_FORMAT_NOERA, true); + public void testLang538() throws ParseException { + final DateParser parser = getInstance("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", GMT); + + final Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT-8")); + cal.clear(); + cal.set(2009, Calendar.OCTOBER, 16, 8, 42, 16); + + assertEquals(cal.getTime(), parser.parse("2009-10-16T16:42:16.000Z")); + } + + @Test + public void testLang996() throws ParseException { + final Calendar expected = Calendar.getInstance(NEW_YORK, Locale.US); + expected.clear(); + expected.set(2014, Calendar.MAY, 14); + + final DateParser fdp = getInstance("ddMMMyyyy", NEW_YORK, Locale.US); + assertEquals(expected.getTime(), fdp.parse("14may2014")); + assertEquals(expected.getTime(), fdp.parse("14MAY2014")); + assertEquals(expected.getTime(), fdp.parse("14May2014")); + } + + @Test + public void testLocaleMatches() { + final DateParser parser= getInstance(yMdHmsSZ, SWEDEN); + assertEquals(SWEDEN, parser.getLocale()); } private void testLocales(final String format, final boolean eraBC) throws Exception { @@ -343,150 +435,43 @@ private void testLocales(final String format, final boolean eraBC) throws Except } @Test - public void testJpLocales() throws ParseException { - - final Calendar cal= Calendar.getInstance(GMT); - cal.clear(); - cal.set(2003, Calendar.FEBRUARY, 10); - cal.set(Calendar.ERA, GregorianCalendar.BC); - - final Locale locale = LocaleUtils.toLocale("zh"); - // ja_JP_JP cannot handle dates before 1868 properly - - final SimpleDateFormat sdf = new SimpleDateFormat(LONG_FORMAT, locale); - final DateParser fdf = getInstance(LONG_FORMAT, locale); - - // If parsing fails, a ParseException will be thrown and the test will fail - checkParse(locale, cal, sdf, fdf); - } - - private void checkParse(final Locale locale, final Calendar cal, final SimpleDateFormat sdf, final DateParser fdf) throws ParseException { - final String formattedDate= sdf.format(cal.getTime()); - checkParse(locale, sdf, fdf, formattedDate); - checkParse(locale, sdf, fdf, formattedDate.toLowerCase(locale)); - checkParse(locale, sdf, fdf, formattedDate.toUpperCase(locale)); - } - - private void checkParse(final Locale locale, final SimpleDateFormat sdf, final DateParser fdf, final String formattedDate) throws ParseException { - try { - final Date expectedTime = sdf.parse(formattedDate); - final Date actualTime = fdf.parse(formattedDate); - assertEquals(expectedTime, actualTime, "locale : " + locale + " formattedDate : " + formattedDate + "\n"); - } catch (Exception e) { - fail("locale : " + locale + " formattedDate : " + formattedDate + " error : " + e + "\n", e); - } + public void testLocales_Long_AD() throws Exception { + testLocales(LONG_FORMAT, false); } @Test - public void testParseNumerics() throws ParseException { - final Calendar cal= Calendar.getInstance(NEW_YORK, Locale.US); - cal.clear(); - cal.set(2003, Calendar.FEBRUARY, 10, 15, 33, 20); - cal.set(Calendar.MILLISECOND, 989); - - final DateParser fdf = getInstance("yyyyMMddHHmmssSSS", NEW_YORK, Locale.US); - assertEquals(cal.getTime(), fdf.parse("20030210153320989")); + public void testLocales_Long_BC() throws Exception { + testLocales(LONG_FORMAT, true); } @Test - public void testQuotes() throws ParseException { - final Calendar cal= Calendar.getInstance(NEW_YORK, Locale.US); - cal.clear(); - cal.set(2003, Calendar.FEBRUARY, 10, 15, 33, 20); - cal.set(Calendar.MILLISECOND, 989); - - final DateParser fdf = getInstance("''yyyyMMdd'A''B'HHmmssSSS''", NEW_YORK, Locale.US); - assertEquals(cal.getTime(), fdf.parse("'20030210A'B153320989'")); + public void testLocales_LongNoEra_AD() throws Exception { + testLocales(LONG_FORMAT_NOERA, false); } @Test - public void testSpecialCharacters() throws Exception { - testSdfAndFdp("q", "", true); // bad pattern character (at present) - testSdfAndFdp("Q", "", true); // bad pattern character - testSdfAndFdp("$", "$", false); // OK - testSdfAndFdp("?.d", "?.12", false); // OK - testSdfAndFdp("''yyyyMMdd'A''B'HHmmssSSS''", "'20030210A'B153320989'", false); // OK - testSdfAndFdp("''''yyyyMMdd'A''B'HHmmssSSS''", "''20030210A'B153320989'", false); // OK - testSdfAndFdp("'$\\Ed'", "$\\Ed", false); // OK - - // quoted charaters are case sensitive - testSdfAndFdp("'QED'", "QED", false); - testSdfAndFdp("'QED'", "qed", true); - // case sensitive after insensitive Month field - testSdfAndFdp("yyyy-MM-dd 'QED'", "2003-02-10 QED", false); - testSdfAndFdp("yyyy-MM-dd 'QED'", "2003-02-10 qed", true); + public void testLocales_LongNoEra_BC() throws Exception { + testLocales(LONG_FORMAT_NOERA, true); } @Test - public void testLANG_832() throws Exception { - testSdfAndFdp("'d'd", "d3", false); // OK - testSdfAndFdp("'d'd'", "d3", true); // should fail (unterminated quote) + public void testLocales_Short_AD() throws Exception { + testLocales(SHORT_FORMAT, false); } @Test - public void testLANG_831() throws Exception { - testSdfAndFdp("M E", "3 Tue", true); - } - - private void testSdfAndFdp(final String format, final String date, final boolean shouldFail) - throws Exception { - Date dfdp = null; - Date dsdf = null; - Throwable f = null; - Throwable s = null; - - try { - final SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.US); - sdf.setTimeZone(NEW_YORK); - dsdf = sdf.parse(date); - assertFalse(shouldFail, "Expected SDF failure, but got " + dsdf + " for ["+format+", "+date+"]"); - } catch (final Exception e) { - s = e; - if (!shouldFail) { - throw e; - } - } - - try { - final DateParser fdp = getInstance(format, NEW_YORK, Locale.US); - dfdp = fdp.parse(date); - assertFalse(shouldFail, "Expected FDF failure, but got " + dfdp + " for ["+format+", "+date+"]"); - } catch (final Exception e) { - f = e; - if (!shouldFail) { - throw e; - } - } - // SDF and FDF should produce equivalent results - assertEquals((f == null), (s == null), "Should both or neither throw Exceptions"); - assertEquals(dsdf, dfdp, "Parsed dates should be equal"); + public void testLocales_Short_BC() throws Exception { + testLocales(SHORT_FORMAT, true); } @Test - public void testDayOf() throws ParseException { - final Calendar cal= Calendar.getInstance(NEW_YORK, Locale.US); - cal.clear(); - cal.set(2003, Calendar.FEBRUARY, 10); - - final DateParser fdf = getInstance("W w F D y", NEW_YORK, Locale.US); - assertEquals(cal.getTime(), fdf.parse("3 7 2 41 03")); + public void testLocales_ShortNoEra_AD() throws Exception { + testLocales(SHORT_FORMAT_NOERA, false); } - /** - * Test case for {@link FastDateParser#FastDateParser(String, TimeZone, Locale)}. - * @throws ParseException so we don't have to catch it - */ @Test - public void testShortDateStyleWithLocales() throws ParseException { - DateParser fdf = getDateInstance(FastDateFormat.SHORT, Locale.US); - final Calendar cal = Calendar.getInstance(); - cal.clear(); - - cal.set(2004, Calendar.FEBRUARY, 3); - assertEquals(cal.getTime(), fdf.parse("2/3/04")); - - fdf = getDateInstance(FastDateFormat.SHORT, SWEDEN); - assertEquals(cal.getTime(), fdf.parse("2004-02-03")); + public void testLocales_ShortNoEra_BC() throws Exception { + testLocales(SHORT_FORMAT_NOERA, true); } /** @@ -520,226 +505,241 @@ public void testMilleniumBug() throws ParseException { } @Test - public void testLang303() throws ParseException { - DateParser parser = getInstance(YMD_SLASH); - final Calendar cal = Calendar.getInstance(); - cal.set(2004, Calendar.DECEMBER, 31); + public void testParseLongShort() throws ParseException { + final Calendar cal= Calendar.getInstance(NEW_YORK, Locale.US); + cal.clear(); + cal.set(2003, Calendar.FEBRUARY, 10, 15, 33, 20); + cal.set(Calendar.MILLISECOND, 989); + cal.setTimeZone(NEW_YORK); - final Date date = parser.parse("2004/11/31"); + DateParser fdf = getInstance("yyyy GGGG MMMM dddd aaaa EEEE HHHH mmmm ssss SSSS ZZZZ", NEW_YORK, Locale.US); - parser = SerializationUtils.deserialize(SerializationUtils.serialize((Serializable) parser)); - assertEquals(date, parser.parse("2004/11/31")); + assertEquals(cal.getTime(), fdf.parse("2003 AD February 0010 PM Monday 0015 0033 0020 0989 GMT-05:00")); + cal.set(Calendar.ERA, GregorianCalendar.BC); + + final Date parse = fdf.parse("2003 BC February 0010 PM Saturday 0015 0033 0020 0989 GMT-05:00"); + assertEquals(cal.getTime(), parse); + + fdf = getInstance("y G M d a E H m s S Z", NEW_YORK, Locale.US); + assertEquals(cal.getTime(), fdf.parse("03 BC 2 10 PM Sat 15 33 20 989 -0500")); + + cal.set(Calendar.ERA, GregorianCalendar.AD); + assertEquals(cal.getTime(), fdf.parse("03 AD 2 10 PM Saturday 15 33 20 989 -0500")); } @Test - public void testLang538() throws ParseException { - final DateParser parser = getInstance("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", GMT); - - final Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT-8")); + public void testParseNumerics() throws ParseException { + final Calendar cal= Calendar.getInstance(NEW_YORK, Locale.US); cal.clear(); - cal.set(2009, Calendar.OCTOBER, 16, 8, 42, 16); + cal.set(2003, Calendar.FEBRUARY, 10, 15, 33, 20); + cal.set(Calendar.MILLISECOND, 989); - assertEquals(cal.getTime(), parser.parse("2009-10-16T16:42:16.000Z")); + final DateParser fdf = getInstance("yyyyMMddHHmmssSSS", NEW_YORK, Locale.US); + assertEquals(cal.getTime(), fdf.parse("20030210153320989")); } @Test - public void testEquals() { - final DateParser parser1= getInstance(YMD_SLASH); - final DateParser parser2= getInstance(YMD_SLASH); - - assertEquals(parser1, parser2); - assertEquals(parser1.hashCode(), parser2.hashCode()); - - assertNotEquals(parser1, new Object()); - } + public void testParseOffset() { + final DateParser parser = getInstance(YMD_SLASH); + final Date date = parser.parse("Today is 2015/07/04", new ParsePosition(9)); - @Test - public void testToStringContainsName() { - final DateParser parser= getInstance(YMD_SLASH); - assertTrue(parser.toString().startsWith("FastDate")); + final Calendar cal = Calendar.getInstance(); + cal.clear(); + cal.set(2015, Calendar.JULY, 4); + assertEquals(cal.getTime(), date); } @Test - public void testPatternMatches() { - final DateParser parser= getInstance(yMdHmsSZ); - assertEquals(yMdHmsSZ, parser.getPattern()); - } + // Check that all Locales can parse the formats we use + public void testParses() throws Exception { + for (final String format : new String[]{LONG_FORMAT, SHORT_FORMAT}) { + for (final Locale locale : Locale.getAvailableLocales()) { + for (final TimeZone tz : new TimeZone[]{NEW_YORK, REYKJAVIK, GMT}) { + for (final int year : new int[]{2003, 1940, 1868, 1867, 1, -1, -1940}) { + final Calendar cal= getEraStart(year, tz, locale); + final Date centuryStart= cal.getTime(); - @Test - public void testLocaleMatches() { - final DateParser parser= getInstance(yMdHmsSZ, SWEDEN); - assertEquals(SWEDEN, parser.getLocale()); - } + cal.set(Calendar.MONTH, 1); + cal.set(Calendar.DAY_OF_MONTH, 10); + final Date in= cal.getTime(); - @Test - public void testTimeZoneMatches() { - final DateParser parser= getInstance(yMdHmsSZ, REYKJAVIK); - assertEquals(REYKJAVIK, parser.getTimeZone()); + final FastDateParser fdp= new FastDateParser(format, tz, locale, centuryStart); + validateSdfFormatFdpParseEquality(format, locale, tz, fdp, in, year, centuryStart); + } + } + } + } } @Test - public void testLang996() throws ParseException { - final Calendar expected = Calendar.getInstance(NEW_YORK, Locale.US); - expected.clear(); - expected.set(2014, Calendar.MAY, 14); + public void testParseZone() throws ParseException { + final Calendar cal= Calendar.getInstance(NEW_YORK, Locale.US); + cal.clear(); + cal.set(2003, Calendar.JULY, 10, 16, 33, 20); - final DateParser fdp = getInstance("ddMMMyyyy", NEW_YORK, Locale.US); - assertEquals(expected.getTime(), fdp.parse("14may2014")); - assertEquals(expected.getTime(), fdp.parse("14MAY2014")); - assertEquals(expected.getTime(), fdp.parse("14May2014")); - } + final DateParser fdf = getInstance(yMdHmsSZ, NEW_YORK, Locale.US); - @Test - public void test1806Argument() { - assertThrows(IllegalArgumentException.class, () -> getInstance("XXXX")); - } + assertEquals(cal.getTime(), fdf.parse("2003-07-10T15:33:20.000 -0500")); + assertEquals(cal.getTime(), fdf.parse("2003-07-10T15:33:20.000 GMT-05:00")); + assertEquals(cal.getTime(), fdf.parse("2003-07-10T16:33:20.000 Eastern Daylight Time")); + assertEquals(cal.getTime(), fdf.parse("2003-07-10T16:33:20.000 EDT")); - private static Calendar initializeCalendar(final TimeZone tz) { - final Calendar cal = Calendar.getInstance(tz); - cal.set(Calendar.YEAR, 2001); - cal.set(Calendar.MONTH, 1); // not daylight savings - cal.set(Calendar.DAY_OF_MONTH, 4); - cal.set(Calendar.HOUR_OF_DAY, 12); - cal.set(Calendar.MINUTE, 8); - cal.set(Calendar.SECOND, 56); - cal.set(Calendar.MILLISECOND, 235); - return cal; - } + cal.setTimeZone(TimeZone.getTimeZone("GMT-3")); + cal.set(2003, Calendar.FEBRUARY, 10, 9, 0, 0); - private enum Expected1806 { - India(INDIA, "+05", "+0530", "+05:30", true), - Greenwich(GMT, "Z", "Z", "Z", false), - NewYork(NEW_YORK, "-05", "-0500", "-05:00", false); + assertEquals(cal.getTime(), fdf.parse("2003-02-10T09:00:00.000 -0300")); - Expected1806(final TimeZone zone, final String one, final String two, final String three, final boolean hasHalfHourOffset) { - this.zone = zone; - this.one = one; - this.two = two; - this.three = three; - this.offset = hasHalfHourOffset ?30*60*1000 :0; - } + cal.setTimeZone(TimeZone.getTimeZone("GMT+5")); + cal.set(2003, Calendar.FEBRUARY, 10, 15, 5, 6); - final TimeZone zone; - final String one; - final String two; - final String three; - final long offset; + assertEquals(cal.getTime(), fdf.parse("2003-02-10T15:05:06.000 +0500")); } @Test - public void test1806() throws ParseException { - final String formatStub = "yyyy-MM-dd'T'HH:mm:ss.SSS"; - final String dateStub = "2001-02-04T12:08:56.235"; + public void testPatternMatches() { + final DateParser parser= getInstance(yMdHmsSZ); + assertEquals(yMdHmsSZ, parser.getPattern()); + } - for (final Expected1806 trial : Expected1806.values()) { - final Calendar cal = initializeCalendar(trial.zone); + @Test + public void testQuotes() throws ParseException { + final Calendar cal= Calendar.getInstance(NEW_YORK, Locale.US); + cal.clear(); + cal.set(2003, Calendar.FEBRUARY, 10, 15, 33, 20); + cal.set(Calendar.MILLISECOND, 989); - final String message = trial.zone.getDisplayName()+";"; + final DateParser fdf = getInstance("''yyyyMMdd'A''B'HHmmssSSS''", NEW_YORK, Locale.US); + assertEquals(cal.getTime(), fdf.parse("'20030210A'B153320989'")); + } - DateParser parser = getInstance(formatStub+"X", trial.zone); - assertEquals(cal.getTime().getTime(), parser.parse(dateStub+trial.one).getTime()-trial.offset, message+trial.one); + private void testSdfAndFdp(final String format, final String date, final boolean shouldFail) + throws Exception { + Date dfdp = null; + Date dsdf = null; + Throwable f = null; + Throwable s = null; - parser = getInstance(formatStub+"XX", trial.zone); - assertEquals(cal.getTime(), parser.parse(dateStub+trial.two), message+trial.two); + try { + final SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.US); + sdf.setTimeZone(NEW_YORK); + dsdf = sdf.parse(date); + assertFalse(shouldFail, "Expected SDF failure, but got " + dsdf + " for ["+format+", "+date+"]"); + } catch (final Exception e) { + s = e; + if (!shouldFail) { + throw e; + } + } - parser = getInstance(formatStub+"XXX", trial.zone); - assertEquals(cal.getTime(), parser.parse(dateStub+trial.three), message+trial.three); + try { + final DateParser fdp = getInstance(format, NEW_YORK, Locale.US); + dfdp = fdp.parse(date); + assertFalse(shouldFail, "Expected FDF failure, but got " + dfdp + " for ["+format+", "+date+"]"); + } catch (final Exception e) { + f = e; + if (!shouldFail) { + throw e; + } } + // SDF and FDF should produce equivalent results + assertEquals((f == null), (s == null), "Should both or neither throw Exceptions"); + assertEquals(dsdf, dfdp, "Parsed dates should be equal"); } + /** + * Test case for {@link FastDateParser#FastDateParser(String, TimeZone, Locale)}. + * @throws ParseException so we don't have to catch it + */ @Test - public void testLang1121() throws ParseException { - final TimeZone kst = TimeZone.getTimeZone("KST"); - final DateParser fdp = getInstance("yyyyMMdd", kst, Locale.KOREA); - - assertThrows(ParseException.class, () -> fdp.parse("2015")); - - // Wed Apr 29 00:00:00 KST 2015 - Date actual = fdp.parse("20150429"); - final Calendar cal = Calendar.getInstance(kst, Locale.KOREA); + public void testShortDateStyleWithLocales() throws ParseException { + DateParser fdf = getDateInstance(FastDateFormat.SHORT, Locale.US); + final Calendar cal = Calendar.getInstance(); cal.clear(); - cal.set(2015, 3, 29); - Date expected = cal.getTime(); - assertEquals(expected, actual); - final SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd", Locale.KOREA); - df.setTimeZone(kst); - expected = df.parse("20150429113100"); + cal.set(2004, Calendar.FEBRUARY, 3); + assertEquals(cal.getTime(), fdf.parse("2/3/04")); - // Thu Mar 16 00:00:00 KST 81724 - actual = fdp.parse("20150429113100"); - assertEquals(expected, actual); + fdf = getDateInstance(FastDateFormat.SHORT, SWEDEN); + assertEquals(cal.getTime(), fdf.parse("2004-02-03")); } - @Test - public void testParseOffset() { - final DateParser parser = getInstance(YMD_SLASH); - final Date date = parser.parse("Today is 2015/07/04", new ParsePosition(9)); - - final Calendar cal = Calendar.getInstance(); + private void testSingleLocale(final Locale locale) throws ParseException { + final Calendar cal = Calendar.getInstance(GMT); cal.clear(); - cal.set(2015, Calendar.JULY, 4); - assertEquals(cal.getTime(), date); + cal.set(2003, Calendar.FEBRUARY, 10); + final SimpleDateFormat sdf = new SimpleDateFormat(LONG_FORMAT, locale); + final String formattedDate = sdf.format(cal.getTime()); + sdf.parse(formattedDate); + sdf.parse(formattedDate.toUpperCase(locale)); + sdf.parse(formattedDate.toLowerCase(locale)); } @Test - public void testDayNumberOfWeek() throws ParseException { - final DateParser parser = getInstance("u"); - final Calendar calendar = Calendar.getInstance(); - - calendar.setTime(parser.parse("1")); - assertEquals(Calendar.MONDAY, calendar.get(Calendar.DAY_OF_WEEK)); - - calendar.setTime(parser.parse("6")); - assertEquals(Calendar.SATURDAY, calendar.get(Calendar.DAY_OF_WEEK)); + public void testSpecialCharacters() throws Exception { + testSdfAndFdp("q", "", true); // bad pattern character (at present) + testSdfAndFdp("Q", "", true); // bad pattern character + testSdfAndFdp("$", "$", false); // OK + testSdfAndFdp("?.d", "?.12", false); // OK + testSdfAndFdp("''yyyyMMdd'A''B'HHmmssSSS''", "'20030210A'B153320989'", false); // OK + testSdfAndFdp("''''yyyyMMdd'A''B'HHmmssSSS''", "''20030210A'B153320989'", false); // OK + testSdfAndFdp("'$\\Ed'", "$\\Ed", false); // OK - calendar.setTime(parser.parse("7")); - assertEquals(Calendar.SUNDAY, calendar.get(Calendar.DAY_OF_WEEK)); + // quoted charaters are case sensitive + testSdfAndFdp("'QED'", "QED", false); + testSdfAndFdp("'QED'", "qed", true); + // case sensitive after insensitive Month field + testSdfAndFdp("yyyy-MM-dd 'QED'", "2003-02-10 QED", false); + testSdfAndFdp("yyyy-MM-dd 'QED'", "2003-02-10 qed", true); } @Test - public void testLang1380() throws ParseException { - final Calendar expected = Calendar.getInstance(GMT, Locale.FRANCE); - expected.clear(); - expected.set(2014, Calendar.APRIL, 14); - - final DateParser fdp = getInstance("dd MMM yyyy", GMT, Locale.FRANCE); - assertEquals(expected.getTime(), fdp.parse("14 avril 2014")); - assertEquals(expected.getTime(), fdp.parse("14 avr. 2014")); - assertEquals(expected.getTime(), fdp.parse("14 avr 2014")); + public void testTimeZoneMatches() { + final DateParser parser= getInstance(yMdHmsSZ, REYKJAVIK); + assertEquals(REYKJAVIK, parser.getTimeZone()); } @Test - public void java15BuggyLocaleTestAll() throws ParseException { - for (final Locale locale : Locale.getAvailableLocales()) { - testSingleLocale(locale); - } + public void testToStringContainsName() { + final DateParser parser= getInstance(YMD_SLASH); + assertTrue(parser.toString().startsWith("FastDate")); } + // we cannot use historic dates to test timezone parsing, some timezones have second offsets + // as well as hours and minutes which makes the z formats a low fidelity round trip @Test - public void java15BuggyLocaleTest() throws ParseException { - final String buggyLocaleName = "ff_LR_#Adlm"; - Locale buggyLocale = null; + public void testTzParses() throws Exception { + // Check that all Locales can parse the time formats we use for (final Locale locale : Locale.getAvailableLocales()) { - if (buggyLocaleName.equals(locale.toString())) { - buggyLocale = locale; - break; + final FastDateParser fdp= new FastDateParser("yyyy/MM/dd z", TimeZone.getDefault(), locale); + + for (final TimeZone tz : new TimeZone[]{NEW_YORK, REYKJAVIK, GMT}) { + final Calendar cal= Calendar.getInstance(tz, locale); + cal.clear(); + cal.set(Calendar.YEAR, 2000); + cal.set(Calendar.MONTH, 1); + cal.set(Calendar.DAY_OF_MONTH, 10); + final Date expected= cal.getTime(); + + final Date actual = fdp.parse("2000/02/10 "+tz.getDisplayName(locale)); + assertEquals(expected, actual, "tz:"+tz.getID()+" locale:"+locale.getDisplayName()); } } - if (buggyLocale == null) { - return; - } - testSingleLocale(buggyLocale); } - private void testSingleLocale(final Locale locale) throws ParseException { - final Calendar cal = Calendar.getInstance(GMT); - cal.clear(); - cal.set(2003, Calendar.FEBRUARY, 10); - final SimpleDateFormat sdf = new SimpleDateFormat(LONG_FORMAT, locale); - final String formattedDate = sdf.format(cal.getTime()); - sdf.parse(formattedDate); - sdf.parse(formattedDate.toUpperCase(locale)); - sdf.parse(formattedDate.toLowerCase(locale)); + private void validateSdfFormatFdpParseEquality(final String format, final Locale locale, final TimeZone tz, final DateParser fdp, final Date in, final int year, final Date cs) throws ParseException { + final SimpleDateFormat sdf = new SimpleDateFormat(format, locale); + sdf.setTimeZone(tz); + if (format.equals(SHORT_FORMAT)) { + sdf.set2DigitYearStart( cs ); + } + final String fmt = sdf.format(in); + try { + final Date out = fdp.parse(fmt); + assertEquals(in, out, locale.toString()+" "+in+" "+ format+ " "+tz.getID()); + } catch (final ParseException pe) { + if (year >= 1868 || !locale.getCountry().equals("JP")) {// LANG-978 + throw pe; + } + } } } From 7995aad79fab336a4534a5290fdd760df7f55dde Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Thu, 22 Oct 2020 14:47:45 -0400 Subject: [PATCH 0383/3230] Split out tests for a Java 15 bug. These tests fail on Java 15 due to a bug which was only fixed for Java 16. See https://bugs.openjdk.java.net/browse/JDK-8248434 See https://bugs.openjdk.java.net/browse/JDK-8248655 --- pom.xml | 20 + .../commons/lang3/function/TriFunction.java | 65 +++ .../lang3/time/FastDateFormat_ParserTest.java | 33 -- .../lang3/time/FastDateParserTest.java | 422 ++++++++---------- .../time/Java15BugFastDateParserTest.java | 156 +++++++ 5 files changed, 429 insertions(+), 267 deletions(-) create mode 100644 src/main/java/org/apache/commons/lang3/function/TriFunction.java delete mode 100644 src/test/java/org/apache/commons/lang3/time/FastDateFormat_ParserTest.java create mode 100644 src/test/java/org/apache/commons/lang3/time/Java15BugFastDateParserTest.java diff --git a/pom.xml b/pom.xml index 0aad6a34e8a..83f70ad46f7 100644 --- a/pom.xml +++ b/pom.xml @@ -941,6 +941,26 @@ true + + java15 + + + 15 + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + org/apache/commons/lang3/time/Java15BugFastDateParserTest.java + + + + + + benchmark diff --git a/src/main/java/org/apache/commons/lang3/function/TriFunction.java b/src/main/java/org/apache/commons/lang3/function/TriFunction.java new file mode 100644 index 00000000000..653013ada74 --- /dev/null +++ b/src/main/java/org/apache/commons/lang3/function/TriFunction.java @@ -0,0 +1,65 @@ +/* + * 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.function; + +import java.util.Objects; +import java.util.function.Function; + +/** + * Represents a function that accepts three arguments and produces a result. This is the three-arity specialization of + * {@link Function}. + * + *

      + * This is a functional interface whose functional method is + * {@link #apply(Object, Object, Object)}. + * + * @param the type of the first argument to the function + * @param the type of the second argument to the function + * @param the type of the third argument to the function + * @param the type of the result of the function + * + * @see Function + * @since 3.12.0 + */ +@FunctionalInterface +public interface TriFunction { + + /** + * Applies this function to the given arguments. + * + * @param t the first function argument + * @param u the second function argument + * @param v the third function argument + * @return the function result + */ + R apply(T t, U u, V v); + + /** + * Returns a composed function that first applies this function to its input, and then applies the {@code after} + * function to the result. If evaluation of either function throws an exception, it is relayed to the caller of the + * composed function. + * + * @param the type of output of the {@code after} function, and of the composed function + * @param after the function to apply after this function is applied + * @return a composed function that first applies this function and then applies the {@code after} function + * @throws NullPointerException if after is null + */ + default TriFunction andThen(Function after) { + Objects.requireNonNull(after); + return (T t, U u, V v) -> after.apply(apply(t, u, v)); + } +} diff --git a/src/test/java/org/apache/commons/lang3/time/FastDateFormat_ParserTest.java b/src/test/java/org/apache/commons/lang3/time/FastDateFormat_ParserTest.java deleted file mode 100644 index bdbff2f0cab..00000000000 --- a/src/test/java/org/apache/commons/lang3/time/FastDateFormat_ParserTest.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * 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.time; - -import java.util.Locale; -import java.util.TimeZone; - -/** - * Unit tests for the parse methods of FastDateFormat - * - * @since 3.2 - */ -public class FastDateFormat_ParserTest extends FastDateParserTest { - - @Override - protected DateParser getInstance(final String format, final TimeZone timeZone, final Locale locale) { - return FastDateFormat.getInstance(format, timeZone, locale); - } -} diff --git a/src/test/java/org/apache/commons/lang3/time/FastDateParserTest.java b/src/test/java/org/apache/commons/lang3/time/FastDateParserTest.java index 817de7b98bd..0fbce4ab4cf 100644 --- a/src/test/java/org/apache/commons/lang3/time/FastDateParserTest.java +++ b/src/test/java/org/apache/commons/lang3/time/FastDateParserTest.java @@ -34,10 +34,15 @@ import java.util.Locale; import java.util.Map; import java.util.TimeZone; +import java.util.stream.Stream; import org.apache.commons.lang3.LocaleUtils; import org.apache.commons.lang3.SerializationUtils; +import org.apache.commons.lang3.function.TriFunction; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; /** * Unit tests {@link org.apache.commons.lang3.time.FastDateParser}. @@ -45,9 +50,9 @@ * @since 3.2 */ public class FastDateParserTest { + private enum Expected1806 { - India(INDIA, "+05", "+0530", "+05:30", true), - Greenwich(GMT, "Z", "Z", "Z", false), + India(INDIA, "+05", "+0530", "+05:30", true), Greenwich(GMT, "Z", "Z", "Z", false), NewYork(NEW_YORK, "-05", "-0500", "-05:00", false); final TimeZone zone; @@ -56,33 +61,48 @@ private enum Expected1806 { final String two; final String three; final long offset; - Expected1806(final TimeZone zone, final String one, final String two, final String three, final boolean hasHalfHourOffset) { + + Expected1806(final TimeZone zone, final String one, final String two, final String three, + final boolean hasHalfHourOffset) { this.zone = zone; this.one = one; this.two = two; this.three = three; - this.offset = hasHalfHourOffset ?30*60*1000 :0; + this.offset = hasHalfHourOffset ? 30 * 60 * 1000 : 0; } } - private static final String SHORT_FORMAT_NOERA = "y/M/d/h/a/m/s/E"; - private static final String LONG_FORMAT_NOERA = "yyyy/MMMM/dddd/hhhh/mmmm/ss/aaaa/EEEE"; - private static final String SHORT_FORMAT = "G/" + SHORT_FORMAT_NOERA; - private static final String LONG_FORMAT = "GGGG/" + LONG_FORMAT_NOERA; + static final String DATE_PARSER_PARAMETERS = "dateParserParameters"; + + static final String SHORT_FORMAT_NOERA = "y/M/d/h/a/m/s/E"; + + static final String LONG_FORMAT_NOERA = "yyyy/MMMM/dddd/hhhh/mmmm/ss/aaaa/EEEE"; + static final String SHORT_FORMAT = "G/" + SHORT_FORMAT_NOERA; + static final String LONG_FORMAT = "GGGG/" + LONG_FORMAT_NOERA; + private static final String yMdHmsSZ = "yyyy-MM-dd'T'HH:mm:ss.SSS Z"; private static final String DMY_DOT = "dd.MM.yyyy"; private static final String YMD_SLASH = "yyyy/MM/dd"; private static final String MDY_DASH = "MM-DD-yyyy"; - private static final String MDY_SLASH = "MM/DD/yyyy"; + private static final TimeZone REYKJAVIK = TimeZone.getTimeZone("Atlantic/Reykjavik"); private static final TimeZone NEW_YORK = TimeZone.getTimeZone("America/New_York"); - private static final TimeZone GMT = TimeZone.getTimeZone("GMT"); - + static final TimeZone GMT = TimeZone.getTimeZone("GMT"); private static final TimeZone INDIA = TimeZone.getTimeZone("Asia/Calcutta"); private static final Locale SWEDEN = new Locale("sv", "SE"); + static Stream dateParserParameters() { + return Stream.of( + // @formatter:off + Arguments.of((TriFunction) (format, timeZone, locale) + -> new FastDateParser(format, timeZone, locale, null)), + Arguments.of((TriFunction) FastDateFormat::getInstance) + // @formatter:on + ); + } + private static Calendar initializeCalendar(final TimeZone tz) { final Calendar cal = Calendar.getInstance(tz); cal.set(Calendar.YEAR, 2001); @@ -95,25 +115,30 @@ private static Calendar initializeCalendar(final TimeZone tz) { return cal; } - private void checkParse(final Locale locale, final Calendar cal, final SimpleDateFormat sdf, final DateParser fdf) throws ParseException { - final String formattedDate= sdf.format(cal.getTime()); + private final TriFunction dateParserProvider = (format, timeZone, + locale) -> new FastDateParser(format, timeZone, locale, null); + + static void checkParse(final Locale locale, final Calendar cal, final SimpleDateFormat sdf, final DateParser fdf) { + final String formattedDate = sdf.format(cal.getTime()); checkParse(locale, sdf, fdf, formattedDate); checkParse(locale, sdf, fdf, formattedDate.toLowerCase(locale)); checkParse(locale, sdf, fdf, formattedDate.toUpperCase(locale)); } - private void checkParse(final Locale locale, final SimpleDateFormat sdf, final DateParser fdf, final String formattedDate) throws ParseException { + static void checkParse(final Locale locale, final SimpleDateFormat sdf, final DateParser fdf, + final String formattedDate) { try { final Date expectedTime = sdf.parse(formattedDate); final Date actualTime = fdf.parse(formattedDate); assertEquals(expectedTime, actualTime, "locale : " + locale + " formattedDate : " + formattedDate + "\n"); - } catch (Exception e) { + } catch (final Exception e) { fail("locale : " + locale + " formattedDate : " + formattedDate + " error : " + e + "\n", e); } } private DateParser getDateInstance(final int dateStyle, final Locale locale) { - return getInstance(FormatCache.getPatternForStyle(Integer.valueOf(dateStyle), null, locale), TimeZone.getDefault(), Locale.getDefault()); + return getInstance(null, FormatCache.getPatternForStyle(Integer.valueOf(dateStyle), null, locale), + TimeZone.getDefault(), Locale.getDefault()); } private Calendar getEraStart(int year, final TimeZone zone, final Locale locale) { @@ -124,91 +149,68 @@ private Calendar getEraStart(int year, final TimeZone zone, final Locale locale) if (locale.equals(FastDateParser.JAPANESE_IMPERIAL)) { if (year < 1868) { cal.set(Calendar.ERA, 0); - cal.set(Calendar.YEAR, 1868-year); + cal.set(Calendar.YEAR, 1868 - year); } } else { if (year < 0) { cal.set(Calendar.ERA, GregorianCalendar.BC); - year= -year; + year = -year; } - cal.set(Calendar.YEAR, year/100 * 100); + cal.set(Calendar.YEAR, year / 100 * 100); } return cal; } DateParser getInstance(final String format) { - return getInstance(format, TimeZone.getDefault(), Locale.getDefault()); + return getInstance(null, format, TimeZone.getDefault(), Locale.getDefault()); } - private DateParser getInstance(final String format, final Locale locale) { - return getInstance(format, TimeZone.getDefault(), locale); + DateParser getInstance(final String format, final Locale locale) { + return getInstance(null, format, TimeZone.getDefault(), locale); } private DateParser getInstance(final String format, final TimeZone timeZone) { - return getInstance(format, timeZone, Locale.getDefault()); + return getInstance(null, format, timeZone, Locale.getDefault()); } /** * Override this method in derived tests to change the construction of instances * + * @param dpProvider TODO * @param format the format string to use * @param timeZone the time zone to use * @param locale the locale to use * * @return the DateParser instance to use for testing */ - protected DateParser getInstance(final String format, final TimeZone timeZone, final Locale locale) { - return new FastDateParser(format, timeZone, locale, null); - } - - @Test - public void java15BuggyLocaleTest() throws ParseException { - final String buggyLocaleName = "ff_LR_#Adlm"; - Locale buggyLocale = null; - for (final Locale locale : Locale.getAvailableLocales()) { - if (buggyLocaleName.equals(locale.toString())) { - buggyLocale = locale; - break; - } - } - if (buggyLocale == null) { - return; - } - testSingleLocale(buggyLocale); - } - - @Test - public void java15BuggyLocaleTestAll() throws ParseException { - for (final Locale locale : Locale.getAvailableLocales()) { - testSingleLocale(locale); - } - } - - @Test - public void test_Equality_Hash() { - final DateParser[] parsers= { - getInstance(yMdHmsSZ, NEW_YORK, Locale.US), - getInstance(DMY_DOT, NEW_YORK, Locale.US), - getInstance(YMD_SLASH, NEW_YORK, Locale.US), - getInstance(MDY_DASH, NEW_YORK, Locale.US), - getInstance(MDY_SLASH, NEW_YORK, Locale.US), - getInstance(MDY_SLASH, REYKJAVIK, Locale.US), - getInstance(MDY_SLASH, REYKJAVIK, SWEDEN) - }; - - final Map map= new HashMap<>(); - int i= 0; - for (final DateParser parser:parsers) { + protected DateParser getInstance(final TriFunction dpProvider, + final String format, final TimeZone timeZone, final Locale locale) { + return (dpProvider == null ? this.dateParserProvider : dpProvider).apply(format, timeZone, locale); + } + + @ParameterizedTest + @MethodSource(DATE_PARSER_PARAMETERS) + public void test_Equality_Hash(final TriFunction dpProvider) { + final DateParser[] parsers = {getInstance(dpProvider, yMdHmsSZ, NEW_YORK, Locale.US), + getInstance(dpProvider, DMY_DOT, NEW_YORK, Locale.US), + getInstance(dpProvider, YMD_SLASH, NEW_YORK, Locale.US), + getInstance(dpProvider, MDY_DASH, NEW_YORK, Locale.US), + getInstance(dpProvider, MDY_SLASH, NEW_YORK, Locale.US), + getInstance(dpProvider, MDY_SLASH, REYKJAVIK, Locale.US), + getInstance(dpProvider, MDY_SLASH, REYKJAVIK, SWEDEN)}; + + final Map map = new HashMap<>(); + int i = 0; + for (final DateParser parser : parsers) { map.put(parser, Integer.valueOf(i++)); } - i= 0; - for (final DateParser parser:parsers) { + i = 0; + for (final DateParser parser : parsers) { assertEquals(i++, map.get(parser).intValue()); } } - @Test public void test1806() throws ParseException { final String formatStub = "yyyy-MM-dd'T'HH:mm:ss.SSS"; @@ -217,16 +219,17 @@ public void test1806() throws ParseException { for (final Expected1806 trial : Expected1806.values()) { final Calendar cal = initializeCalendar(trial.zone); - final String message = trial.zone.getDisplayName()+";"; + final String message = trial.zone.getDisplayName() + ";"; - DateParser parser = getInstance(formatStub+"X", trial.zone); - assertEquals(cal.getTime().getTime(), parser.parse(dateStub+trial.one).getTime()-trial.offset, message+trial.one); + DateParser parser = getInstance(formatStub + "X", trial.zone); + assertEquals(cal.getTime().getTime(), parser.parse(dateStub + trial.one).getTime() - trial.offset, + message + trial.one); - parser = getInstance(formatStub+"XX", trial.zone); - assertEquals(cal.getTime(), parser.parse(dateStub+trial.two), message+trial.two); + parser = getInstance(formatStub + "XX", trial.zone); + assertEquals(cal.getTime(), parser.parse(dateStub + trial.two), message + trial.two); - parser = getInstance(formatStub+"XXX", trial.zone); - assertEquals(cal.getTime(), parser.parse(dateStub+trial.three), message+trial.three); + parser = getInstance(formatStub + "XXX", trial.zone); + assertEquals(cal.getTime(), parser.parse(dateStub + trial.three), message + trial.three); } } @@ -235,15 +238,16 @@ public void test1806Argument() { assertThrows(IllegalArgumentException.class, () -> getInstance("XXXX")); } - @Test - public void testAmPm() throws ParseException { - final Calendar cal= Calendar.getInstance(NEW_YORK, Locale.US); + @ParameterizedTest + @MethodSource(DATE_PARSER_PARAMETERS) + public void testAmPm(final TriFunction dpProvider) throws ParseException { + final Calendar cal = Calendar.getInstance(NEW_YORK, Locale.US); cal.clear(); - final DateParser h = getInstance("yyyy-MM-dd hh a mm:ss", NEW_YORK, Locale.US); - final DateParser K = getInstance("yyyy-MM-dd KK a mm:ss", NEW_YORK, Locale.US); - final DateParser k = getInstance("yyyy-MM-dd kk:mm:ss", NEW_YORK, Locale.US); - final DateParser H = getInstance("yyyy-MM-dd HH:mm:ss", NEW_YORK, Locale.US); + final DateParser h = getInstance(dpProvider, "yyyy-MM-dd hh a mm:ss", NEW_YORK, Locale.US); + final DateParser K = getInstance(dpProvider, "yyyy-MM-dd KK a mm:ss", NEW_YORK, Locale.US); + final DateParser k = getInstance(dpProvider, "yyyy-MM-dd kk:mm:ss", NEW_YORK, Locale.US); + final DateParser H = getInstance(dpProvider, "yyyy-MM-dd HH:mm:ss", NEW_YORK, Locale.US); cal.set(2010, Calendar.AUGUST, 1, 0, 33, 20); assertEquals(cal.getTime(), h.parse("2010-08-01 12 AM 33:20")); @@ -285,20 +289,21 @@ public void testDayNumberOfWeek() throws ParseException { assertEquals(Calendar.SUNDAY, calendar.get(Calendar.DAY_OF_WEEK)); } - @Test - public void testDayOf() throws ParseException { - final Calendar cal= Calendar.getInstance(NEW_YORK, Locale.US); + @ParameterizedTest + @MethodSource(DATE_PARSER_PARAMETERS) + public void testDayOf(final TriFunction dpProvider) throws ParseException { + final Calendar cal = Calendar.getInstance(NEW_YORK, Locale.US); cal.clear(); cal.set(2003, Calendar.FEBRUARY, 10); - final DateParser fdf = getInstance("W w F D y", NEW_YORK, Locale.US); + final DateParser fdf = getInstance(dpProvider, "W w F D y", NEW_YORK, Locale.US); assertEquals(cal.getTime(), fdf.parse("3 7 2 41 03")); } @Test public void testEquals() { - final DateParser parser1= getInstance(YMD_SLASH); - final DateParser parser2= getInstance(YMD_SLASH); + final DateParser parser1 = getInstance(YMD_SLASH); + final DateParser parser2 = getInstance(YMD_SLASH); assertEquals(parser1, parser2); assertEquals(parser1.hashCode(), parser2.hashCode()); @@ -306,10 +311,13 @@ public void testEquals() { assertNotEquals(parser1, new Object()); } + /** + * @throws ParseException + */ @Test public void testJpLocales() throws ParseException { - final Calendar cal= Calendar.getInstance(GMT); + final Calendar cal = Calendar.getInstance(GMT); cal.clear(); cal.set(2003, Calendar.FEBRUARY, 10); cal.set(Calendar.ERA, GregorianCalendar.BC); @@ -324,21 +332,24 @@ public void testJpLocales() throws ParseException { checkParse(locale, cal, sdf, fdf); } - @Test - public void testLANG_831() throws Exception { - testSdfAndFdp("M E", "3 Tue", true); + @ParameterizedTest + @MethodSource(DATE_PARSER_PARAMETERS) + public void testLANG_831(final TriFunction dpProvider) throws Exception { + testSdfAndFdp(dpProvider, "M E", "3 Tue", true); } - @Test - public void testLANG_832() throws Exception { - testSdfAndFdp("'d'd", "d3", false); // OK - testSdfAndFdp("'d'd'", "d3", true); // should fail (unterminated quote) + @ParameterizedTest + @MethodSource(DATE_PARSER_PARAMETERS) + public void testLANG_832(final TriFunction dpProvider) throws Exception { + testSdfAndFdp(dpProvider, "'d'd", "d3", false); // OK + testSdfAndFdp(dpProvider, "'d'd'", "d3", true); // should fail (unterminated quote) } - @Test - public void testLang1121() throws ParseException { + @ParameterizedTest + @MethodSource(DATE_PARSER_PARAMETERS) + public void testLang1121(final TriFunction dpProvider) throws ParseException { final TimeZone kst = TimeZone.getTimeZone("KST"); - final DateParser fdp = getInstance("yyyyMMdd", kst, Locale.KOREA); + final DateParser fdp = getInstance(dpProvider, "yyyyMMdd", kst, Locale.KOREA); assertThrows(ParseException.class, () -> fdp.parse("2015")); @@ -359,13 +370,14 @@ public void testLang1121() throws ParseException { assertEquals(expected, actual); } - @Test - public void testLang1380() throws ParseException { + @ParameterizedTest + @MethodSource(DATE_PARSER_PARAMETERS) + public void testLang1380(final TriFunction dpProvider) throws ParseException { final Calendar expected = Calendar.getInstance(GMT, Locale.FRANCE); expected.clear(); expected.set(2014, Calendar.APRIL, 14); - final DateParser fdp = getInstance("dd MMM yyyy", GMT, Locale.FRANCE); + final DateParser fdp = getInstance(dpProvider, "dd MMM yyyy", GMT, Locale.FRANCE); assertEquals(expected.getTime(), fdp.parse("14 avril 2014")); assertEquals(expected.getTime(), fdp.parse("14 avr. 2014")); assertEquals(expected.getTime(), fdp.parse("14 avr 2014")); @@ -394,13 +406,14 @@ public void testLang538() throws ParseException { assertEquals(cal.getTime(), parser.parse("2009-10-16T16:42:16.000Z")); } - @Test - public void testLang996() throws ParseException { + @ParameterizedTest + @MethodSource(DATE_PARSER_PARAMETERS) + public void testLang996(final TriFunction dpProvider) throws ParseException { final Calendar expected = Calendar.getInstance(NEW_YORK, Locale.US); expected.clear(); expected.set(2014, Calendar.MAY, 14); - final DateParser fdp = getInstance("ddMMMyyyy", NEW_YORK, Locale.US); + final DateParser fdp = getInstance(dpProvider, "ddMMMyyyy", NEW_YORK, Locale.US); assertEquals(expected.getTime(), fdp.parse("14may2014")); assertEquals(expected.getTime(), fdp.parse("14MAY2014")); assertEquals(expected.getTime(), fdp.parse("14May2014")); @@ -408,74 +421,13 @@ public void testLang996() throws ParseException { @Test public void testLocaleMatches() { - final DateParser parser= getInstance(yMdHmsSZ, SWEDEN); + final DateParser parser = getInstance(yMdHmsSZ, SWEDEN); assertEquals(SWEDEN, parser.getLocale()); } - private void testLocales(final String format, final boolean eraBC) throws Exception { - - final Calendar cal= Calendar.getInstance(GMT); - cal.clear(); - cal.set(2003, Calendar.FEBRUARY, 10); - if (eraBC) { - cal.set(Calendar.ERA, GregorianCalendar.BC); - } - - for (final Locale locale : Locale.getAvailableLocales() ) { - // ja_JP_JP cannot handle dates before 1868 properly - if (eraBC && locale.equals(FastDateParser.JAPANESE_IMPERIAL)) { - continue; - } - final SimpleDateFormat sdf = new SimpleDateFormat(format, locale); - final DateParser fdf = getInstance(format, locale); - - // If parsing fails, a ParseException will be thrown and the test will fail - checkParse(locale, cal, sdf, fdf); - } - } - - @Test - public void testLocales_Long_AD() throws Exception { - testLocales(LONG_FORMAT, false); - } - - @Test - public void testLocales_Long_BC() throws Exception { - testLocales(LONG_FORMAT, true); - } - - @Test - public void testLocales_LongNoEra_AD() throws Exception { - testLocales(LONG_FORMAT_NOERA, false); - } - - @Test - public void testLocales_LongNoEra_BC() throws Exception { - testLocales(LONG_FORMAT_NOERA, true); - } - - @Test - public void testLocales_Short_AD() throws Exception { - testLocales(SHORT_FORMAT, false); - } - - @Test - public void testLocales_Short_BC() throws Exception { - testLocales(SHORT_FORMAT, true); - } - - @Test - public void testLocales_ShortNoEra_AD() throws Exception { - testLocales(SHORT_FORMAT_NOERA, false); - } - - @Test - public void testLocales_ShortNoEra_BC() throws Exception { - testLocales(SHORT_FORMAT_NOERA, true); - } - /** * Tests that pre-1000AD years get padded with yyyy + * * @throws ParseException so we don't have to catch it */ @Test @@ -504,37 +456,42 @@ public void testMilleniumBug() throws ParseException { assertEquals(cal.getTime(), parser.parse("01.01.1000")); } - @Test - public void testParseLongShort() throws ParseException { - final Calendar cal= Calendar.getInstance(NEW_YORK, Locale.US); + @ParameterizedTest + @MethodSource(DATE_PARSER_PARAMETERS) + public void testParseLongShort(final TriFunction dpProvider) + throws ParseException { + final Calendar cal = Calendar.getInstance(NEW_YORK, Locale.US); cal.clear(); cal.set(2003, Calendar.FEBRUARY, 10, 15, 33, 20); cal.set(Calendar.MILLISECOND, 989); cal.setTimeZone(NEW_YORK); - DateParser fdf = getInstance("yyyy GGGG MMMM dddd aaaa EEEE HHHH mmmm ssss SSSS ZZZZ", NEW_YORK, Locale.US); + DateParser fdf = getInstance(dpProvider, "yyyy GGGG MMMM dddd aaaa EEEE HHHH mmmm ssss SSSS ZZZZ", NEW_YORK, + Locale.US); assertEquals(cal.getTime(), fdf.parse("2003 AD February 0010 PM Monday 0015 0033 0020 0989 GMT-05:00")); cal.set(Calendar.ERA, GregorianCalendar.BC); final Date parse = fdf.parse("2003 BC February 0010 PM Saturday 0015 0033 0020 0989 GMT-05:00"); - assertEquals(cal.getTime(), parse); + assertEquals(cal.getTime(), parse); - fdf = getInstance("y G M d a E H m s S Z", NEW_YORK, Locale.US); + fdf = getInstance(null, "y G M d a E H m s S Z", NEW_YORK, Locale.US); assertEquals(cal.getTime(), fdf.parse("03 BC 2 10 PM Sat 15 33 20 989 -0500")); cal.set(Calendar.ERA, GregorianCalendar.AD); assertEquals(cal.getTime(), fdf.parse("03 AD 2 10 PM Saturday 15 33 20 989 -0500")); } - @Test - public void testParseNumerics() throws ParseException { - final Calendar cal= Calendar.getInstance(NEW_YORK, Locale.US); + @ParameterizedTest + @MethodSource(DATE_PARSER_PARAMETERS) + public void testParseNumerics(final TriFunction dpProvider) + throws ParseException { + final Calendar cal = Calendar.getInstance(NEW_YORK, Locale.US); cal.clear(); cal.set(2003, Calendar.FEBRUARY, 10, 15, 33, 20); cal.set(Calendar.MILLISECOND, 989); - final DateParser fdf = getInstance("yyyyMMddHHmmssSSS", NEW_YORK, Locale.US); + final DateParser fdf = getInstance(dpProvider, "yyyyMMddHHmmssSSS", NEW_YORK, Locale.US); assertEquals(cal.getTime(), fdf.parse("20030210153320989")); } @@ -552,18 +509,18 @@ public void testParseOffset() { @Test // Check that all Locales can parse the formats we use public void testParses() throws Exception { - for (final String format : new String[]{LONG_FORMAT, SHORT_FORMAT}) { + for (final String format : new String[] {LONG_FORMAT, SHORT_FORMAT}) { for (final Locale locale : Locale.getAvailableLocales()) { - for (final TimeZone tz : new TimeZone[]{NEW_YORK, REYKJAVIK, GMT}) { - for (final int year : new int[]{2003, 1940, 1868, 1867, 1, -1, -1940}) { - final Calendar cal= getEraStart(year, tz, locale); - final Date centuryStart= cal.getTime(); + for (final TimeZone tz : new TimeZone[] {NEW_YORK, REYKJAVIK, GMT}) { + for (final int year : new int[] {2003, 1940, 1868, 1867, 1, -1, -1940}) { + final Calendar cal = getEraStart(year, tz, locale); + final Date centuryStart = cal.getTime(); cal.set(Calendar.MONTH, 1); cal.set(Calendar.DAY_OF_MONTH, 10); - final Date in= cal.getTime(); + final Date in = cal.getTime(); - final FastDateParser fdp= new FastDateParser(format, tz, locale, centuryStart); + final FastDateParser fdp = new FastDateParser(format, tz, locale, centuryStart); validateSdfFormatFdpParseEquality(format, locale, tz, fdp, in, year, centuryStart); } } @@ -571,13 +528,15 @@ public void testParses() throws Exception { } } - @Test - public void testParseZone() throws ParseException { - final Calendar cal= Calendar.getInstance(NEW_YORK, Locale.US); + @ParameterizedTest + @MethodSource(DATE_PARSER_PARAMETERS) + public void testParseZone(final TriFunction dpProvider) + throws ParseException { + final Calendar cal = Calendar.getInstance(NEW_YORK, Locale.US); cal.clear(); cal.set(2003, Calendar.JULY, 10, 16, 33, 20); - final DateParser fdf = getInstance(yMdHmsSZ, NEW_YORK, Locale.US); + final DateParser fdf = getInstance(dpProvider, yMdHmsSZ, NEW_YORK, Locale.US); assertEquals(cal.getTime(), fdf.parse("2003-07-10T15:33:20.000 -0500")); assertEquals(cal.getTime(), fdf.parse("2003-07-10T15:33:20.000 GMT-05:00")); @@ -597,23 +556,24 @@ public void testParseZone() throws ParseException { @Test public void testPatternMatches() { - final DateParser parser= getInstance(yMdHmsSZ); + final DateParser parser = getInstance(yMdHmsSZ); assertEquals(yMdHmsSZ, parser.getPattern()); } - @Test - public void testQuotes() throws ParseException { - final Calendar cal= Calendar.getInstance(NEW_YORK, Locale.US); + @ParameterizedTest + @MethodSource(DATE_PARSER_PARAMETERS) + public void testQuotes(final TriFunction dpProvider) throws ParseException { + final Calendar cal = Calendar.getInstance(NEW_YORK, Locale.US); cal.clear(); cal.set(2003, Calendar.FEBRUARY, 10, 15, 33, 20); cal.set(Calendar.MILLISECOND, 989); - final DateParser fdf = getInstance("''yyyyMMdd'A''B'HHmmssSSS''", NEW_YORK, Locale.US); + final DateParser fdf = getInstance(dpProvider, "''yyyyMMdd'A''B'HHmmssSSS''", NEW_YORK, Locale.US); assertEquals(cal.getTime(), fdf.parse("'20030210A'B153320989'")); } - private void testSdfAndFdp(final String format, final String date, final boolean shouldFail) - throws Exception { + private void testSdfAndFdp(final TriFunction dbProvider, final String format, + final String date, final boolean shouldFail) throws Exception { Date dfdp = null; Date dsdf = null; Throwable f = null; @@ -623,7 +583,7 @@ private void testSdfAndFdp(final String format, final String date, final boolean final SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.US); sdf.setTimeZone(NEW_YORK); dsdf = sdf.parse(date); - assertFalse(shouldFail, "Expected SDF failure, but got " + dsdf + " for ["+format+", "+date+"]"); + assertFalse(shouldFail, "Expected SDF failure, but got " + dsdf + " for [" + format + ", " + date + "]"); } catch (final Exception e) { s = e; if (!shouldFail) { @@ -632,9 +592,9 @@ private void testSdfAndFdp(final String format, final String date, final boolean } try { - final DateParser fdp = getInstance(format, NEW_YORK, Locale.US); + final DateParser fdp = getInstance(dbProvider, format, NEW_YORK, Locale.US); dfdp = fdp.parse(date); - assertFalse(shouldFail, "Expected FDF failure, but got " + dfdp + " for ["+format+", "+date+"]"); + assertFalse(shouldFail, "Expected FDF failure, but got " + dfdp + " for [" + format + ", " + date + "]"); } catch (final Exception e) { f = e; if (!shouldFail) { @@ -648,6 +608,7 @@ private void testSdfAndFdp(final String format, final String date, final boolean /** * Test case for {@link FastDateParser#FastDateParser(String, TimeZone, Locale)}. + * * @throws ParseException so we don't have to catch it */ @Test @@ -663,44 +624,35 @@ public void testShortDateStyleWithLocales() throws ParseException { assertEquals(cal.getTime(), fdf.parse("2004-02-03")); } - private void testSingleLocale(final Locale locale) throws ParseException { - final Calendar cal = Calendar.getInstance(GMT); - cal.clear(); - cal.set(2003, Calendar.FEBRUARY, 10); - final SimpleDateFormat sdf = new SimpleDateFormat(LONG_FORMAT, locale); - final String formattedDate = sdf.format(cal.getTime()); - sdf.parse(formattedDate); - sdf.parse(formattedDate.toUpperCase(locale)); - sdf.parse(formattedDate.toLowerCase(locale)); - } - - @Test - public void testSpecialCharacters() throws Exception { - testSdfAndFdp("q", "", true); // bad pattern character (at present) - testSdfAndFdp("Q", "", true); // bad pattern character - testSdfAndFdp("$", "$", false); // OK - testSdfAndFdp("?.d", "?.12", false); // OK - testSdfAndFdp("''yyyyMMdd'A''B'HHmmssSSS''", "'20030210A'B153320989'", false); // OK - testSdfAndFdp("''''yyyyMMdd'A''B'HHmmssSSS''", "''20030210A'B153320989'", false); // OK - testSdfAndFdp("'$\\Ed'", "$\\Ed", false); // OK + @ParameterizedTest + @MethodSource(DATE_PARSER_PARAMETERS) + public void testSpecialCharacters(final TriFunction dpProvider) + throws Exception { + testSdfAndFdp(dpProvider, "q", "", true); // bad pattern character (at present) + testSdfAndFdp(dpProvider, "Q", "", true); // bad pattern character + testSdfAndFdp(dpProvider, "$", "$", false); // OK + testSdfAndFdp(dpProvider, "?.d", "?.12", false); // OK + testSdfAndFdp(dpProvider, "''yyyyMMdd'A''B'HHmmssSSS''", "'20030210A'B153320989'", false); // OK + testSdfAndFdp(dpProvider, "''''yyyyMMdd'A''B'HHmmssSSS''", "''20030210A'B153320989'", false); // OK + testSdfAndFdp(dpProvider, "'$\\Ed'", "$\\Ed", false); // OK // quoted charaters are case sensitive - testSdfAndFdp("'QED'", "QED", false); - testSdfAndFdp("'QED'", "qed", true); + testSdfAndFdp(dpProvider, "'QED'", "QED", false); + testSdfAndFdp(dpProvider, "'QED'", "qed", true); // case sensitive after insensitive Month field - testSdfAndFdp("yyyy-MM-dd 'QED'", "2003-02-10 QED", false); - testSdfAndFdp("yyyy-MM-dd 'QED'", "2003-02-10 qed", true); + testSdfAndFdp(dpProvider, "yyyy-MM-dd 'QED'", "2003-02-10 QED", false); + testSdfAndFdp(dpProvider, "yyyy-MM-dd 'QED'", "2003-02-10 qed", true); } @Test public void testTimeZoneMatches() { - final DateParser parser= getInstance(yMdHmsSZ, REYKJAVIK); + final DateParser parser = getInstance(yMdHmsSZ, REYKJAVIK); assertEquals(REYKJAVIK, parser.getTimeZone()); } @Test public void testToStringContainsName() { - final DateParser parser= getInstance(YMD_SLASH); + final DateParser parser = getInstance(YMD_SLASH); assertTrue(parser.toString().startsWith("FastDate")); } @@ -710,32 +662,33 @@ public void testToStringContainsName() { public void testTzParses() throws Exception { // Check that all Locales can parse the time formats we use for (final Locale locale : Locale.getAvailableLocales()) { - final FastDateParser fdp= new FastDateParser("yyyy/MM/dd z", TimeZone.getDefault(), locale); + final FastDateParser fdp = new FastDateParser("yyyy/MM/dd z", TimeZone.getDefault(), locale); - for (final TimeZone tz : new TimeZone[]{NEW_YORK, REYKJAVIK, GMT}) { - final Calendar cal= Calendar.getInstance(tz, locale); + for (final TimeZone tz : new TimeZone[] {NEW_YORK, REYKJAVIK, GMT}) { + final Calendar cal = Calendar.getInstance(tz, locale); cal.clear(); cal.set(Calendar.YEAR, 2000); cal.set(Calendar.MONTH, 1); cal.set(Calendar.DAY_OF_MONTH, 10); - final Date expected= cal.getTime(); + final Date expected = cal.getTime(); - final Date actual = fdp.parse("2000/02/10 "+tz.getDisplayName(locale)); - assertEquals(expected, actual, "tz:"+tz.getID()+" locale:"+locale.getDisplayName()); + final Date actual = fdp.parse("2000/02/10 " + tz.getDisplayName(locale)); + assertEquals(expected, actual, "tz:" + tz.getID() + " locale:" + locale.getDisplayName()); } } } - private void validateSdfFormatFdpParseEquality(final String format, final Locale locale, final TimeZone tz, final DateParser fdp, final Date in, final int year, final Date cs) throws ParseException { + private void validateSdfFormatFdpParseEquality(final String format, final Locale locale, final TimeZone tz, + final DateParser fdp, final Date in, final int year, final Date cs) throws ParseException { final SimpleDateFormat sdf = new SimpleDateFormat(format, locale); sdf.setTimeZone(tz); if (format.equals(SHORT_FORMAT)) { - sdf.set2DigitYearStart( cs ); + sdf.set2DigitYearStart(cs); } final String fmt = sdf.format(in); try { final Date out = fdp.parse(fmt); - assertEquals(in, out, locale.toString()+" "+in+" "+ format+ " "+tz.getID()); + assertEquals(in, out, locale.toString() + " " + in + " " + format + " " + tz.getID()); } catch (final ParseException pe) { if (year >= 1868 || !locale.getCountry().equals("JP")) {// LANG-978 throw pe; @@ -743,3 +696,4 @@ private void validateSdfFormatFdpParseEquality(final String format, final Locale } } } + diff --git a/src/test/java/org/apache/commons/lang3/time/Java15BugFastDateParserTest.java b/src/test/java/org/apache/commons/lang3/time/Java15BugFastDateParserTest.java new file mode 100644 index 00000000000..15221d174bc --- /dev/null +++ b/src/test/java/org/apache/commons/lang3/time/Java15BugFastDateParserTest.java @@ -0,0 +1,156 @@ +/* + * 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.time; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.GregorianCalendar; +import java.util.Locale; +import java.util.TimeZone; + +import org.apache.commons.lang3.function.TriFunction; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +/** + * These tests fail on Java 15 due to a bug which was only fixed for Java 16. + *

        + *
      • https://bugs.openjdk.java.net/browse/JDK-8248434
      • + *
      • https://bugs.openjdk.java.net/browse/JDK-8248655
      • + *
      + */ +public class Java15BugFastDateParserTest { + + private static final String DATE_PARSER_PARAMETERS = "org.apache.commons.lang3.time.FastDateParserTest#dateParserParameters()"; + + @Test + public void java15BuggyLocaleTest() throws ParseException { + final String buggyLocaleName = "ff_LR_#Adlm"; + Locale buggyLocale = null; + for (final Locale locale : Locale.getAvailableLocales()) { + if (buggyLocaleName.equals(locale.toString())) { + buggyLocale = locale; + break; + } + } + if (buggyLocale == null) { + return; + } + testSingleLocale(buggyLocale); + } + + @Test + public void java15BuggyLocaleTestAll() throws ParseException { + for (final Locale locale : Locale.getAvailableLocales()) { + testSingleLocale(locale); + } + } + + private void testLocales(final TriFunction dbProvider, final String format, + final boolean eraBC) throws Exception { + + final Calendar cal = Calendar.getInstance(FastDateParserTest.GMT); + cal.clear(); + cal.set(2003, Calendar.FEBRUARY, 10); + if (eraBC) { + cal.set(Calendar.ERA, GregorianCalendar.BC); + } + + for (final Locale locale : Locale.getAvailableLocales()) { + // ja_JP_JP cannot handle dates before 1868 properly + if (eraBC && locale.equals(FastDateParser.JAPANESE_IMPERIAL)) { + continue; + } + final SimpleDateFormat sdf = new SimpleDateFormat(format, locale); + final DateParser fdf = dbProvider.apply(format, TimeZone.getDefault(), locale); + + // If parsing fails, a ParseException will be thrown and the test will fail + FastDateParserTest.checkParse(locale, cal, sdf, fdf); + } + } + + @ParameterizedTest + @MethodSource(DATE_PARSER_PARAMETERS) + public void testLocales_Long_AD(final TriFunction dpProvider) + throws Exception { + testLocales(dpProvider, FastDateParserTest.LONG_FORMAT, false); + } + + @ParameterizedTest + @MethodSource(DATE_PARSER_PARAMETERS) + public void testLocales_Long_BC(final TriFunction dpProvider) + throws Exception { + testLocales(dpProvider, FastDateParserTest.LONG_FORMAT, true); + } + + @ParameterizedTest + @MethodSource(DATE_PARSER_PARAMETERS) + public void testLocales_LongNoEra_AD(final TriFunction dpProvider) + throws Exception { + testLocales(dpProvider, FastDateParserTest.LONG_FORMAT_NOERA, false); + } + + @ParameterizedTest + @MethodSource(DATE_PARSER_PARAMETERS) + public void testLocales_LongNoEra_BC(final TriFunction dpProvider) + throws Exception { + testLocales(dpProvider, FastDateParserTest.LONG_FORMAT_NOERA, true); + } + + @ParameterizedTest + @MethodSource(DATE_PARSER_PARAMETERS) + public void testLocales_Short_AD(final TriFunction dpProvider) + throws Exception { + testLocales(dpProvider, FastDateParserTest.SHORT_FORMAT, false); + } + + @ParameterizedTest + @MethodSource(DATE_PARSER_PARAMETERS) + public void testLocales_Short_BC(final TriFunction dpProvider) + throws Exception { + testLocales(dpProvider, FastDateParserTest.SHORT_FORMAT, true); + } + + @ParameterizedTest + @MethodSource(DATE_PARSER_PARAMETERS) + public void testLocales_ShortNoEra_AD(final TriFunction dpProvider) + throws Exception { + testLocales(dpProvider, FastDateParserTest.SHORT_FORMAT_NOERA, false); + } + + @ParameterizedTest + @MethodSource(DATE_PARSER_PARAMETERS) + public void testLocales_ShortNoEra_BC(final TriFunction dpProvider) + throws Exception { + testLocales(dpProvider, FastDateParserTest.SHORT_FORMAT_NOERA, true); + } + + private void testSingleLocale(final Locale locale) throws ParseException { + final Calendar cal = Calendar.getInstance(FastDateParserTest.GMT); + cal.clear(); + cal.set(2003, Calendar.FEBRUARY, 10); + final SimpleDateFormat sdf = new SimpleDateFormat(FastDateParserTest.LONG_FORMAT, locale); + final String formattedDate = sdf.format(cal.getTime()); + sdf.parse(formattedDate); + sdf.parse(formattedDate.toUpperCase(locale)); + sdf.parse(formattedDate.toLowerCase(locale)); + } + +} \ No newline at end of file From 110b4c021e4901efab91499fedcdfb43c564ebdf Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Thu, 22 Oct 2020 14:53:59 -0400 Subject: [PATCH 0384/3230] Checkstyle. --- .../apache/commons/lang3/time/Java15BugFastDateParserTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/org/apache/commons/lang3/time/Java15BugFastDateParserTest.java b/src/test/java/org/apache/commons/lang3/time/Java15BugFastDateParserTest.java index 15221d174bc..4bc33151376 100644 --- a/src/test/java/org/apache/commons/lang3/time/Java15BugFastDateParserTest.java +++ b/src/test/java/org/apache/commons/lang3/time/Java15BugFastDateParserTest.java @@ -153,4 +153,4 @@ private void testSingleLocale(final Locale locale) throws ParseException { sdf.parse(formattedDate.toLowerCase(locale)); } -} \ No newline at end of file +} From 6d7a3e6eebfe9c06567b3fc7903ae2ea9718c33a Mon Sep 17 00:00:00 2001 From: Hubert <2518652+HubertWo@users.noreply.github.com> Date: Sun, 25 Oct 2020 15:12:45 +0100 Subject: [PATCH 0385/3230] NumberUtilsTest - incorrect types in min/max tests (#634) * Fix: correctly declared types and added castings * Fix: code format * Redo - optimize imports --- .../commons/lang3/math/NumberUtilsTest.java | 54 +++++++++---------- 1 file changed, 27 insertions(+), 27 deletions(-) diff --git a/src/test/java/org/apache/commons/lang3/math/NumberUtilsTest.java b/src/test/java/org/apache/commons/lang3/math/NumberUtilsTest.java index 523cb0cc4d2..cb78580aee3 100644 --- a/src/test/java/org/apache/commons/lang3/math/NumberUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/math/NumberUtilsTest.java @@ -696,11 +696,11 @@ public void testMinLong_emptyArray() { @Test public void testMinLong() { - assertEquals(5, NumberUtils.min(5), "min(long[]) failed for array length 1"); - assertEquals(6, NumberUtils.min(6, 9), "min(long[]) failed for array length 2"); + assertEquals(5L, NumberUtils.min(5L), "min(long[]) failed for array length 1"); + assertEquals(6L, NumberUtils.min(6L, 9L), "min(long[]) failed for array length 2"); - assertEquals(-10, NumberUtils.min(-10, -5, 0, 5, 10)); - assertEquals(-10, NumberUtils.min(-5, 0, -10, 5, 10)); + assertEquals(-10L, NumberUtils.min(-10L, -5L, 0L, 5L, 10L)); + assertEquals(-10L, NumberUtils.min(-5L, 0L, -10L, 5L, 10L)); } @Test @@ -734,11 +734,11 @@ public void testMinShort_emptyArray() { @Test public void testMinShort() { - assertEquals(5, NumberUtils.min(5), "min(short[]) failed for array length 1"); - assertEquals(6, NumberUtils.min(6, 9), "min(short[]) failed for array length 2"); + assertEquals((short) 5, NumberUtils.min((short) 5), "min(short[]) failed for array length 1"); + assertEquals((short) 6, NumberUtils.min((short) 6, (short) 9), "min(short[]) failed for array length 2"); - assertEquals(-10, NumberUtils.min(-10, -5, 0, 5, 10)); - assertEquals(-10, NumberUtils.min(-5, 0, -10, 5, 10)); + assertEquals((short) -10, NumberUtils.min((short) -10, (short) -5, (short) 0, (short) 5, (short) 10)); + assertEquals((short) -10, NumberUtils.min((short) -5, (short) 0, (short) -10, (short) 5, (short) 10)); } @Test @@ -753,11 +753,11 @@ public void testMinByte_emptyArray() { @Test public void testMinByte() { - assertEquals(5, NumberUtils.min(5), "min(byte[]) failed for array length 1"); - assertEquals(6, NumberUtils.min(6, 9), "min(byte[]) failed for array length 2"); + assertEquals((byte) 5, NumberUtils.min((byte) 5), "min(byte[]) failed for array length 1"); + assertEquals((byte) 6, NumberUtils.min((byte) 6, (byte) 9), "min(byte[]) failed for array length 2"); - assertEquals(-10, NumberUtils.min(-10, -5, 0, 5, 10)); - assertEquals(-10, NumberUtils.min(-5, 0, -10, 5, 10)); + assertEquals((byte) -10, NumberUtils.min((byte) -10, (byte) -5, (byte) 0, (byte) 5, (byte) 10)); + assertEquals((byte) -10, NumberUtils.min((byte) -5, (byte) 0, (byte) -10, (byte) 5, (byte) 10)); } @Test @@ -810,11 +810,11 @@ public void testMaxLong_emptyArray() { @Test public void testMaxLong() { - assertEquals(5, NumberUtils.max(5), "max(long[]) failed for array length 1"); - assertEquals(9, NumberUtils.max(6, 9), "max(long[]) failed for array length 2"); - assertEquals(10, NumberUtils.max(-10, -5, 0, 5, 10), "max(long[]) failed for array length 5"); - assertEquals(10, NumberUtils.max(-10, -5, 0, 5, 10)); - assertEquals(10, NumberUtils.max(-5, 0, 10, 5, -10)); + assertEquals(5L, NumberUtils.max(5L), "max(long[]) failed for array length 1"); + assertEquals(9L, NumberUtils.max(6L, 9L), "max(long[]) failed for array length 2"); + assertEquals(10L, NumberUtils.max(-10L, -5L, 0L, 5L, 10L), "max(long[]) failed for array length 5"); + assertEquals(10L, NumberUtils.max(-10L, -5L, 0L, 5L, 10L)); + assertEquals(10L, NumberUtils.max(-5L, 0L, 10L, 5L, -10L)); } @Test @@ -848,11 +848,11 @@ public void testMaxShort_emptyArray() { @Test public void testMaxShort() { - assertEquals(5, NumberUtils.max(5), "max(short[]) failed for array length 1"); - assertEquals(9, NumberUtils.max(6, 9), "max(short[]) failed for array length 2"); - assertEquals(10, NumberUtils.max(-10, -5, 0, 5, 10), "max(short[]) failed for array length 5"); - assertEquals(10, NumberUtils.max(-10, -5, 0, 5, 10)); - assertEquals(10, NumberUtils.max(-5, 0, 10, 5, -10)); + assertEquals((short) 5, NumberUtils.max((short) 5), "max(short[]) failed for array length 1"); + assertEquals((short) 9, NumberUtils.max((short) 6, (short) 9), "max(short[]) failed for array length 2"); + assertEquals((short) 10, NumberUtils.max((short) -10, (short) -5, (short) 0, (short) 5, (short) 10), "max(short[]) failed for array length 5"); + assertEquals((short) 10, NumberUtils.max((short) -10, (short) -5, (short) 0, (short) 5, (short) 10)); + assertEquals((short) 10, NumberUtils.max((short) -5, (short) 0, (short) 10, (short) 5, (short) -10)); } @Test @@ -867,11 +867,11 @@ public void testMaxByte_emptyArray() { @Test public void testMaxByte() { - assertEquals(5, NumberUtils.max(5), "max(byte[]) failed for array length 1"); - assertEquals(9, NumberUtils.max(6, 9), "max(byte[]) failed for array length 2"); - assertEquals(10, NumberUtils.max(-10, -5, 0, 5, 10), "max(byte[]) failed for array length 5"); - assertEquals(10, NumberUtils.max(-10, -5, 0, 5, 10)); - assertEquals(10, NumberUtils.max(-5, 0, 10, 5, -10)); + assertEquals((byte) 5, NumberUtils.max((byte) 5), "max(byte[]) failed for array length 1"); + assertEquals((byte) 9, NumberUtils.max((byte) 6, (byte) 9), "max(byte[]) failed for array length 2"); + assertEquals((byte) 10, NumberUtils.max((byte) -10, (byte) -5, (byte) 0, (byte) 5, (byte) 10), "max(byte[]) failed for array length 5"); + assertEquals((byte) 10, NumberUtils.max((byte) -10, (byte) -5, (byte) 0, (byte) 5, (byte) 10)); + assertEquals((byte) 10, NumberUtils.max((byte) -5, (byte) 0, (byte) 10, (byte) 5, (byte) -10)); } @Test From 75b4058ac4b57661f06a20b44bc0359e639484e7 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sun, 25 Oct 2020 10:18:00 -0400 Subject: [PATCH 0386/3230] NumberUtilsTest - incorrect types in min/max tests #634. - Document change. - Sort methods. - Format to max line length 120. --- src/changes/changes.xml | 1 + .../commons/lang3/math/NumberUtilsTest.java | 2336 +++++++++-------- 2 files changed, 1196 insertions(+), 1141 deletions(-) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index fdb5c698082..a38e9d84d49 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -51,6 +51,7 @@ The type attribute can be add,update,fix,remove. Restore handling of collections for non-JSON ToStringStyle #610. ContextedException Javadoc add missing semicolon #581. Resolve JUnit pioneer transitive dependencies using JUnit BOM. + NumberUtilsTest - incorrect types in min/max tests #634. Add BooleanUtils.booleanValues(). Add BooleanUtils.primitiveValues(). diff --git a/src/test/java/org/apache/commons/lang3/math/NumberUtilsTest.java b/src/test/java/org/apache/commons/lang3/math/NumberUtilsTest.java index cb78580aee3..dea507c68f2 100644 --- a/src/test/java/org/apache/commons/lang3/math/NumberUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/math/NumberUtilsTest.java @@ -36,150 +36,57 @@ */ public class NumberUtilsTest { - //----------------------------------------------------------------------- - @Test - public void testConstructor() { - assertNotNull(new NumberUtils()); - final Constructor[] cons = NumberUtils.class.getDeclaredConstructors(); - assertEquals(1, cons.length); - assertTrue(Modifier.isPublic(cons[0].getModifiers())); - assertTrue(Modifier.isPublic(NumberUtils.class.getModifiers())); - assertFalse(Modifier.isFinal(NumberUtils.class.getModifiers())); - } - - //--------------------------------------------------------------------- - - /** - * Test for {@link NumberUtils#toInt(String)}. - */ - @Test - public void testToIntString() { - assertEquals(12345, NumberUtils.toInt("12345"), "toInt(String) 1 failed"); - assertEquals(0, NumberUtils.toInt("abc"), "toInt(String) 2 failed"); - assertEquals(0, NumberUtils.toInt(""), "toInt(empty) failed"); - assertEquals(0, NumberUtils.toInt(null), "toInt(null) failed"); + private boolean checkCreateNumber(final String val) { + try { + final Object obj = NumberUtils.createNumber(val); + return obj != null; + } catch (final NumberFormatException e) { + return false; + } } - /** - * Test for {@link NumberUtils#toInt(String, int)}. - */ - @Test - public void testToIntStringI() { - assertEquals(12345, NumberUtils.toInt("12345", 5), "toInt(String, int) 1 failed"); - assertEquals(5, NumberUtils.toInt("1234.5", 5), "toInt(String, int) 2 failed"); - } + // --------------------------------------------------------------------- - /** - * Test for {@link NumberUtils#toLong(String)}. - */ @Test - public void testToLongString() { - assertEquals(12345L, NumberUtils.toLong("12345"), "toLong(String) 1 failed"); - assertEquals(0L, NumberUtils.toLong("abc"), "toLong(String) 2 failed"); - assertEquals(0L, NumberUtils.toLong("1L"), "toLong(String) 3 failed"); - assertEquals(0L, NumberUtils.toLong("1l"), "toLong(String) 4 failed"); - assertEquals(NumberUtils.toLong(Long.MAX_VALUE + ""), Long.MAX_VALUE, "toLong(Long.MAX_VALUE) failed"); - assertEquals(NumberUtils.toLong(Long.MIN_VALUE + ""), Long.MIN_VALUE, "toLong(Long.MIN_VALUE) failed"); - assertEquals(0L, NumberUtils.toLong(""), "toLong(empty) failed"); - assertEquals(0L, NumberUtils.toLong(null), "toLong(null) failed"); + public void compareByte() { + assertTrue(NumberUtils.compare((byte) -3, (byte) 0) < 0); + assertEquals(0, NumberUtils.compare((byte) 113, (byte) 113)); + assertTrue(NumberUtils.compare((byte) 123, (byte) 32) > 0); } - /** - * Test for {@link NumberUtils#toLong(String, long)}. - */ @Test - public void testToLongStringL() { - assertEquals(12345L, NumberUtils.toLong("12345", 5L), "toLong(String, long) 1 failed"); - assertEquals(5L, NumberUtils.toLong("1234.5", 5L), "toLong(String, long) 2 failed"); + public void compareInt() { + assertTrue(NumberUtils.compare(-3, 0) < 0); + assertEquals(0, NumberUtils.compare(113, 113)); + assertTrue(NumberUtils.compare(213, 32) > 0); } - /** - * Test for {@link NumberUtils#toFloat(String)}. - */ - @Test - public void testToFloatString() { - assertEquals(NumberUtils.toFloat("-1.2345"), -1.2345f, "toFloat(String) 1 failed"); - assertEquals(1.2345f, NumberUtils.toFloat("1.2345"), "toFloat(String) 2 failed"); - assertEquals(0.0f, NumberUtils.toFloat("abc"), "toFloat(String) 3 failed"); - // LANG-1060 - assertEquals(NumberUtils.toFloat("-001.2345"), -1.2345f, "toFloat(String) 4 failed"); - assertEquals(1.2345f, NumberUtils.toFloat("+001.2345"), "toFloat(String) 5 failed"); - assertEquals(1.2345f, NumberUtils.toFloat("001.2345"), "toFloat(String) 6 failed"); - assertEquals(0f, NumberUtils.toFloat("000.00"), "toFloat(String) 7 failed"); - - assertEquals(NumberUtils.toFloat(Float.MAX_VALUE + ""), Float.MAX_VALUE, "toFloat(Float.MAX_VALUE) failed"); - assertEquals(NumberUtils.toFloat(Float.MIN_VALUE + ""), Float.MIN_VALUE, "toFloat(Float.MIN_VALUE) failed"); - assertEquals(0.0f, NumberUtils.toFloat(""), "toFloat(empty) failed"); - assertEquals(0.0f, NumberUtils.toFloat(null), "toFloat(null) failed"); + private void compareIsCreatableWithCreateNumber(final String val, final boolean expected) { + final boolean isValid = NumberUtils.isCreatable(val); + final boolean canCreate = checkCreateNumber(val); + assertTrue(isValid == expected && canCreate == expected, "Expecting " + expected + + " for isCreatable/createNumber using \"" + val + "\" but got " + isValid + " and " + canCreate); } - /** - * Test for {@link NumberUtils#toFloat(String, float)}. - */ - @Test - public void testToFloatStringF() { - assertEquals(1.2345f, NumberUtils.toFloat("1.2345", 5.1f), "toFloat(String, int) 1 failed"); - assertEquals(5.0f, NumberUtils.toFloat("a", 5.0f), "toFloat(String, int) 2 failed"); - // LANG-1060 - assertEquals(5.0f, NumberUtils.toFloat("-001Z.2345", 5.0f), "toFloat(String, int) 3 failed"); - assertEquals(5.0f, NumberUtils.toFloat("+001AB.2345", 5.0f), "toFloat(String, int) 4 failed"); - assertEquals(5.0f, NumberUtils.toFloat("001Z.2345", 5.0f), "toFloat(String, int) 5 failed"); + private void compareIsNumberWithCreateNumber(final String val, final boolean expected) { + final boolean isValid = NumberUtils.isCreatable(val); + final boolean canCreate = checkCreateNumber(val); + assertTrue(isValid == expected && canCreate == expected, "Expecting " + expected + + " for isCreatable/createNumber using \"" + val + "\" but got " + isValid + " and " + canCreate); } - /** - * Test for {(@link NumberUtils#createNumber(String)} - */ - @Test - public void testStringCreateNumberEnsureNoPrecisionLoss() { - final String shouldBeFloat = "1.23"; - final String shouldBeDouble = "3.40282354e+38"; - final String shouldBeBigDecimal = "1.797693134862315759e+308"; - assertTrue(NumberUtils.createNumber(shouldBeFloat) instanceof Float); - assertTrue(NumberUtils.createNumber(shouldBeDouble) instanceof Double); - assertTrue(NumberUtils.createNumber(shouldBeBigDecimal) instanceof BigDecimal); - // LANG-1060 - assertTrue(NumberUtils.createNumber("001.12") instanceof Float); - assertTrue(NumberUtils.createNumber("-001.12") instanceof Float); - assertTrue(NumberUtils.createNumber("+001.12") instanceof Float); - assertTrue(NumberUtils.createNumber("003.40282354e+38") instanceof Double); - assertTrue(NumberUtils.createNumber("-003.40282354e+38") instanceof Double); - assertTrue(NumberUtils.createNumber("+003.40282354e+38") instanceof Double); - assertTrue(NumberUtils.createNumber("0001.797693134862315759e+308") instanceof BigDecimal); - assertTrue(NumberUtils.createNumber("-001.797693134862315759e+308") instanceof BigDecimal); - assertTrue(NumberUtils.createNumber("+001.797693134862315759e+308") instanceof BigDecimal); - } - /** - * Test for {@link NumberUtils#toDouble(String)}. - */ @Test - public void testStringToDoubleString() { - assertEquals(NumberUtils.toDouble("-1.2345"), -1.2345d, "toDouble(String) 1 failed"); - assertEquals(1.2345d, NumberUtils.toDouble("1.2345"), "toDouble(String) 2 failed"); - assertEquals(0.0d, NumberUtils.toDouble("abc"), "toDouble(String) 3 failed"); - // LANG-1060 - assertEquals(NumberUtils.toDouble("-001.2345"), -1.2345d, "toDouble(String) 4 failed"); - assertEquals(1.2345d, NumberUtils.toDouble("+001.2345"), "toDouble(String) 5 failed"); - assertEquals(1.2345d, NumberUtils.toDouble("001.2345"), "toDouble(String) 6 failed"); - assertEquals(0d, NumberUtils.toDouble("000.00000"), "toDouble(String) 7 failed"); - - assertEquals(NumberUtils.toDouble(Double.MAX_VALUE + ""), Double.MAX_VALUE, "toDouble(Double.MAX_VALUE) failed"); - assertEquals(NumberUtils.toDouble(Double.MIN_VALUE + ""), Double.MIN_VALUE, "toDouble(Double.MIN_VALUE) failed"); - assertEquals(0.0d, NumberUtils.toDouble(""), "toDouble(empty) failed"); - assertEquals(0.0d, NumberUtils.toDouble((String) null), "toDouble(null) failed"); + public void compareLong() { + assertTrue(NumberUtils.compare(-3L, 0L) < 0); + assertEquals(0, NumberUtils.compare(113L, 113L)); + assertTrue(NumberUtils.compare(213L, 32L) > 0); } - /** - * Test for {@link NumberUtils#toDouble(String, double)}. - */ @Test - public void testStringToDoubleStringD() { - assertEquals(1.2345d, NumberUtils.toDouble("1.2345", 5.1d), "toDouble(String, int) 1 failed"); - assertEquals(5.0d, NumberUtils.toDouble("a", 5.0d), "toDouble(String, int) 2 failed"); - // LANG-1060 - assertEquals(1.2345d, NumberUtils.toDouble("001.2345", 5.1d), "toDouble(String, int) 3 failed"); - assertEquals(NumberUtils.toDouble("-001.2345", 5.1d), -1.2345d, "toDouble(String, int) 4 failed"); - assertEquals(1.2345d, NumberUtils.toDouble("+001.2345", 5.1d), "toDouble(String, int) 5 failed"); - assertEquals(0d, NumberUtils.toDouble("000.00", 5.1d), "toDouble(String, int) 7 failed"); + public void compareShort() { + assertTrue(NumberUtils.compare((short) -3, (short) 0) < 0); + assertEquals(0, NumberUtils.compare((short) 113, (short) 113)); + assertTrue(NumberUtils.compare((short) 213, (short) 32) > 0); } /** @@ -200,159 +107,364 @@ public void testBigIntegerToDoubleBigIntegerD() { assertEquals(8.5d, NumberUtils.toDouble(BigDecimal.valueOf(8.5d), 1.1d), "toDouble(BigInteger) 2 failed"); } - /** - * Test for {@link NumberUtils#toByte(String)}. - */ + // Testing JDK against old Lang functionality @Test - public void testToByteString() { - assertEquals(123, NumberUtils.toByte("123"), "toByte(String) 1 failed"); - assertEquals(0, NumberUtils.toByte("abc"), "toByte(String) 2 failed"); - assertEquals(0, NumberUtils.toByte(""), "toByte(empty) failed"); - assertEquals(0, NumberUtils.toByte(null), "toByte(null) failed"); - } + public void testCompareDouble() { + assertEquals(0, Double.compare(Double.NaN, Double.NaN)); + assertEquals(Double.compare(Double.NaN, Double.POSITIVE_INFINITY), +1); + assertEquals(Double.compare(Double.NaN, Double.MAX_VALUE), +1); + assertEquals(Double.compare(Double.NaN, 1.2d), +1); + assertEquals(Double.compare(Double.NaN, 0.0d), +1); + assertEquals(Double.compare(Double.NaN, -0.0d), +1); + assertEquals(Double.compare(Double.NaN, -1.2d), +1); + assertEquals(Double.compare(Double.NaN, -Double.MAX_VALUE), +1); + assertEquals(Double.compare(Double.NaN, Double.NEGATIVE_INFINITY), +1); - /** - * Test for {@link NumberUtils#toByte(String, byte)}. - */ - @Test - public void testToByteStringI() { - assertEquals(123, NumberUtils.toByte("123", (byte) 5), "toByte(String, byte) 1 failed"); - assertEquals(5, NumberUtils.toByte("12.3", (byte) 5), "toByte(String, byte) 2 failed"); - } + assertEquals(Double.compare(Double.POSITIVE_INFINITY, Double.NaN), -1); + assertEquals(0, Double.compare(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY)); + assertEquals(Double.compare(Double.POSITIVE_INFINITY, Double.MAX_VALUE), +1); + assertEquals(Double.compare(Double.POSITIVE_INFINITY, 1.2d), +1); + assertEquals(Double.compare(Double.POSITIVE_INFINITY, 0.0d), +1); + assertEquals(Double.compare(Double.POSITIVE_INFINITY, -0.0d), +1); + assertEquals(Double.compare(Double.POSITIVE_INFINITY, -1.2d), +1); + assertEquals(Double.compare(Double.POSITIVE_INFINITY, -Double.MAX_VALUE), +1); + assertEquals(Double.compare(Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY), +1); - /** - * Test for {@link NumberUtils#toShort(String)}. - */ - @Test - public void testToShortString() { - assertEquals(12345, NumberUtils.toShort("12345"), "toShort(String) 1 failed"); - assertEquals(0, NumberUtils.toShort("abc"), "toShort(String) 2 failed"); - assertEquals(0, NumberUtils.toShort(""), "toShort(empty) failed"); - assertEquals(0, NumberUtils.toShort(null), "toShort(null) failed"); - } + assertEquals(Double.compare(Double.MAX_VALUE, Double.NaN), -1); + assertEquals(Double.compare(Double.MAX_VALUE, Double.POSITIVE_INFINITY), -1); + assertEquals(0, Double.compare(Double.MAX_VALUE, Double.MAX_VALUE)); + assertEquals(Double.compare(Double.MAX_VALUE, 1.2d), +1); + assertEquals(Double.compare(Double.MAX_VALUE, 0.0d), +1); + assertEquals(Double.compare(Double.MAX_VALUE, -0.0d), +1); + assertEquals(Double.compare(Double.MAX_VALUE, -1.2d), +1); + assertEquals(Double.compare(Double.MAX_VALUE, -Double.MAX_VALUE), +1); + assertEquals(Double.compare(Double.MAX_VALUE, Double.NEGATIVE_INFINITY), +1); - /** - * Test for {@link NumberUtils#toShort(String, short)}. - */ - @Test - public void testToShortStringI() { - assertEquals(12345, NumberUtils.toShort("12345", (short) 5), "toShort(String, short) 1 failed"); - assertEquals(5, NumberUtils.toShort("1234.5", (short) 5), "toShort(String, short) 2 failed"); - } + assertEquals(Double.compare(1.2d, Double.NaN), -1); + assertEquals(Double.compare(1.2d, Double.POSITIVE_INFINITY), -1); + assertEquals(Double.compare(1.2d, Double.MAX_VALUE), -1); + assertEquals(0, Double.compare(1.2d, 1.2d)); + assertEquals(Double.compare(1.2d, 0.0d), +1); + assertEquals(Double.compare(1.2d, -0.0d), +1); + assertEquals(Double.compare(1.2d, -1.2d), +1); + assertEquals(Double.compare(1.2d, -Double.MAX_VALUE), +1); + assertEquals(Double.compare(1.2d, Double.NEGATIVE_INFINITY), +1); - /** - * Test for {@link NumberUtils#toScaledBigDecimal(BigDecimal)}. - */ - @Test - public void testToScaledBigDecimalBigDecimal() { - assertEquals(NumberUtils.toScaledBigDecimal(BigDecimal.valueOf(123.456)), BigDecimal.valueOf(123.46), "toScaledBigDecimal(BigDecimal) 1 failed"); - // Test RoudingMode.HALF_EVEN default rounding. - assertEquals(NumberUtils.toScaledBigDecimal(BigDecimal.valueOf(23.515)), BigDecimal.valueOf(23.52), "toScaledBigDecimal(BigDecimal) 2 failed"); - assertEquals(NumberUtils.toScaledBigDecimal(BigDecimal.valueOf(23.525)), BigDecimal.valueOf(23.52), "toScaledBigDecimal(BigDecimal) 3 failed"); - assertEquals("2352.00", NumberUtils.toScaledBigDecimal(BigDecimal.valueOf(23.525)) - .multiply(BigDecimal.valueOf(100)).toString(), "toScaledBigDecimal(BigDecimal) 4 failed"); - assertEquals(NumberUtils.toScaledBigDecimal((BigDecimal) null), BigDecimal.ZERO, "toScaledBigDecimal(BigDecimal) 5 failed"); - } + assertEquals(Double.compare(0.0d, Double.NaN), -1); + assertEquals(Double.compare(0.0d, Double.POSITIVE_INFINITY), -1); + assertEquals(Double.compare(0.0d, Double.MAX_VALUE), -1); + assertEquals(Double.compare(0.0d, 1.2d), -1); + assertEquals(0, Double.compare(0.0d, 0.0d)); + assertEquals(Double.compare(0.0d, -0.0d), +1); + assertEquals(Double.compare(0.0d, -1.2d), +1); + assertEquals(Double.compare(0.0d, -Double.MAX_VALUE), +1); + assertEquals(Double.compare(0.0d, Double.NEGATIVE_INFINITY), +1); - /** - * Test for {@link NumberUtils#toScaledBigDecimal(BigDecimal, int, RoundingMode)}. - */ - @Test - public void testToScaledBigDecimalBigDecimalIRM() { - assertEquals(NumberUtils.toScaledBigDecimal(BigDecimal.valueOf(123.456), 1, RoundingMode.CEILING), BigDecimal.valueOf(123.5), "toScaledBigDecimal(BigDecimal, int, RoudingMode) 1 failed"); - assertEquals(NumberUtils.toScaledBigDecimal(BigDecimal.valueOf(23.5159), 3, RoundingMode.FLOOR), BigDecimal.valueOf(23.515), "toScaledBigDecimal(BigDecimal, int, RoudingMode) 2 failed"); - assertEquals(NumberUtils.toScaledBigDecimal(BigDecimal.valueOf(23.525), 2, RoundingMode.HALF_UP), BigDecimal.valueOf(23.53), "toScaledBigDecimal(BigDecimal, int, RoudingMode) 3 failed"); - assertEquals("23521.0000", NumberUtils.toScaledBigDecimal(BigDecimal.valueOf(23.521), 4, RoundingMode.HALF_EVEN) - .multiply(BigDecimal.valueOf(1000)) - .toString(), "toScaledBigDecimal(BigDecimal, int, RoudingMode) 4 failed"); - assertEquals(NumberUtils.toScaledBigDecimal((BigDecimal) null, 2, RoundingMode.HALF_UP), BigDecimal.ZERO, "toScaledBigDecimal(BigDecimal, int, RoudingMode) 5 failed"); - } + assertEquals(Double.compare(-0.0d, Double.NaN), -1); + assertEquals(Double.compare(-0.0d, Double.POSITIVE_INFINITY), -1); + assertEquals(Double.compare(-0.0d, Double.MAX_VALUE), -1); + assertEquals(Double.compare(-0.0d, 1.2d), -1); + assertEquals(Double.compare(-0.0d, 0.0d), -1); + assertEquals(0, Double.compare(-0.0d, -0.0d)); + assertEquals(Double.compare(-0.0d, -1.2d), +1); + assertEquals(Double.compare(-0.0d, -Double.MAX_VALUE), +1); + assertEquals(Double.compare(-0.0d, Double.NEGATIVE_INFINITY), +1); + + assertEquals(Double.compare(-1.2d, Double.NaN), -1); + assertEquals(Double.compare(-1.2d, Double.POSITIVE_INFINITY), -1); + assertEquals(Double.compare(-1.2d, Double.MAX_VALUE), -1); + assertEquals(Double.compare(-1.2d, 1.2d), -1); + assertEquals(Double.compare(-1.2d, 0.0d), -1); + assertEquals(Double.compare(-1.2d, -0.0d), -1); + assertEquals(0, Double.compare(-1.2d, -1.2d)); + assertEquals(Double.compare(-1.2d, -Double.MAX_VALUE), +1); + assertEquals(Double.compare(-1.2d, Double.NEGATIVE_INFINITY), +1); + + assertEquals(Double.compare(-Double.MAX_VALUE, Double.NaN), -1); + assertEquals(Double.compare(-Double.MAX_VALUE, Double.POSITIVE_INFINITY), -1); + assertEquals(Double.compare(-Double.MAX_VALUE, Double.MAX_VALUE), -1); + assertEquals(Double.compare(-Double.MAX_VALUE, 1.2d), -1); + assertEquals(Double.compare(-Double.MAX_VALUE, 0.0d), -1); + assertEquals(Double.compare(-Double.MAX_VALUE, -0.0d), -1); + assertEquals(Double.compare(-Double.MAX_VALUE, -1.2d), -1); + assertEquals(0, Double.compare(-Double.MAX_VALUE, -Double.MAX_VALUE)); + assertEquals(Double.compare(-Double.MAX_VALUE, Double.NEGATIVE_INFINITY), +1); + + assertEquals(Double.compare(Double.NEGATIVE_INFINITY, Double.NaN), -1); + assertEquals(Double.compare(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY), -1); + assertEquals(Double.compare(Double.NEGATIVE_INFINITY, Double.MAX_VALUE), -1); + assertEquals(Double.compare(Double.NEGATIVE_INFINITY, 1.2d), -1); + assertEquals(Double.compare(Double.NEGATIVE_INFINITY, 0.0d), -1); + assertEquals(Double.compare(Double.NEGATIVE_INFINITY, -0.0d), -1); + assertEquals(Double.compare(Double.NEGATIVE_INFINITY, -1.2d), -1); + assertEquals(Double.compare(Double.NEGATIVE_INFINITY, -Double.MAX_VALUE), -1); + assertEquals(0, Double.compare(Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY)); + } - /** - * Test for {@link NumberUtils#toScaledBigDecimal(Float)}. - */ @Test - public void testToScaledBigDecimalFloat() { - assertEquals(NumberUtils.toScaledBigDecimal(Float.valueOf(123.456f)), BigDecimal.valueOf(123.46), "toScaledBigDecimal(Float) 1 failed"); - // Test RoudingMode.HALF_EVEN default rounding. - assertEquals(NumberUtils.toScaledBigDecimal(Float.valueOf(23.515f)), BigDecimal.valueOf(23.51), "toScaledBigDecimal(Float) 2 failed"); - // Note. NumberUtils.toScaledBigDecimal(Float.valueOf(23.515f)).equals(BigDecimal.valueOf(23.51)) - // because of roundoff error. It is ok. - assertEquals(NumberUtils.toScaledBigDecimal(Float.valueOf(23.525f)), BigDecimal.valueOf(23.52), "toScaledBigDecimal(Float) 3 failed"); - assertEquals("2352.00", NumberUtils.toScaledBigDecimal(Float.valueOf(23.525f)) - .multiply(BigDecimal.valueOf(100)).toString(), "toScaledBigDecimal(Float) 4 failed"); - assertEquals(NumberUtils.toScaledBigDecimal((Float) null), BigDecimal.ZERO, "toScaledBigDecimal(Float) 5 failed"); + public void testCompareFloat() { + assertEquals(0, Float.compare(Float.NaN, Float.NaN)); + assertEquals(Float.compare(Float.NaN, Float.POSITIVE_INFINITY), +1); + assertEquals(Float.compare(Float.NaN, Float.MAX_VALUE), +1); + assertEquals(Float.compare(Float.NaN, 1.2f), +1); + assertEquals(Float.compare(Float.NaN, 0.0f), +1); + assertEquals(Float.compare(Float.NaN, -0.0f), +1); + assertEquals(Float.compare(Float.NaN, -1.2f), +1); + assertEquals(Float.compare(Float.NaN, -Float.MAX_VALUE), +1); + assertEquals(Float.compare(Float.NaN, Float.NEGATIVE_INFINITY), +1); + + assertEquals(Float.compare(Float.POSITIVE_INFINITY, Float.NaN), -1); + assertEquals(0, Float.compare(Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY)); + assertEquals(Float.compare(Float.POSITIVE_INFINITY, Float.MAX_VALUE), +1); + assertEquals(Float.compare(Float.POSITIVE_INFINITY, 1.2f), +1); + assertEquals(Float.compare(Float.POSITIVE_INFINITY, 0.0f), +1); + assertEquals(Float.compare(Float.POSITIVE_INFINITY, -0.0f), +1); + assertEquals(Float.compare(Float.POSITIVE_INFINITY, -1.2f), +1); + assertEquals(Float.compare(Float.POSITIVE_INFINITY, -Float.MAX_VALUE), +1); + assertEquals(Float.compare(Float.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY), +1); + + assertEquals(Float.compare(Float.MAX_VALUE, Float.NaN), -1); + assertEquals(Float.compare(Float.MAX_VALUE, Float.POSITIVE_INFINITY), -1); + assertEquals(0, Float.compare(Float.MAX_VALUE, Float.MAX_VALUE)); + assertEquals(Float.compare(Float.MAX_VALUE, 1.2f), +1); + assertEquals(Float.compare(Float.MAX_VALUE, 0.0f), +1); + assertEquals(Float.compare(Float.MAX_VALUE, -0.0f), +1); + assertEquals(Float.compare(Float.MAX_VALUE, -1.2f), +1); + assertEquals(Float.compare(Float.MAX_VALUE, -Float.MAX_VALUE), +1); + assertEquals(Float.compare(Float.MAX_VALUE, Float.NEGATIVE_INFINITY), +1); + + assertEquals(Float.compare(1.2f, Float.NaN), -1); + assertEquals(Float.compare(1.2f, Float.POSITIVE_INFINITY), -1); + assertEquals(Float.compare(1.2f, Float.MAX_VALUE), -1); + assertEquals(0, Float.compare(1.2f, 1.2f)); + assertEquals(Float.compare(1.2f, 0.0f), +1); + assertEquals(Float.compare(1.2f, -0.0f), +1); + assertEquals(Float.compare(1.2f, -1.2f), +1); + assertEquals(Float.compare(1.2f, -Float.MAX_VALUE), +1); + assertEquals(Float.compare(1.2f, Float.NEGATIVE_INFINITY), +1); + + assertEquals(Float.compare(0.0f, Float.NaN), -1); + assertEquals(Float.compare(0.0f, Float.POSITIVE_INFINITY), -1); + assertEquals(Float.compare(0.0f, Float.MAX_VALUE), -1); + assertEquals(Float.compare(0.0f, 1.2f), -1); + assertEquals(0, Float.compare(0.0f, 0.0f)); + assertEquals(Float.compare(0.0f, -0.0f), +1); + assertEquals(Float.compare(0.0f, -1.2f), +1); + assertEquals(Float.compare(0.0f, -Float.MAX_VALUE), +1); + assertEquals(Float.compare(0.0f, Float.NEGATIVE_INFINITY), +1); + + assertEquals(Float.compare(-0.0f, Float.NaN), -1); + assertEquals(Float.compare(-0.0f, Float.POSITIVE_INFINITY), -1); + assertEquals(Float.compare(-0.0f, Float.MAX_VALUE), -1); + assertEquals(Float.compare(-0.0f, 1.2f), -1); + assertEquals(Float.compare(-0.0f, 0.0f), -1); + assertEquals(0, Float.compare(-0.0f, -0.0f)); + assertEquals(Float.compare(-0.0f, -1.2f), +1); + assertEquals(Float.compare(-0.0f, -Float.MAX_VALUE), +1); + assertEquals(Float.compare(-0.0f, Float.NEGATIVE_INFINITY), +1); + + assertEquals(Float.compare(-1.2f, Float.NaN), -1); + assertEquals(Float.compare(-1.2f, Float.POSITIVE_INFINITY), -1); + assertEquals(Float.compare(-1.2f, Float.MAX_VALUE), -1); + assertEquals(Float.compare(-1.2f, 1.2f), -1); + assertEquals(Float.compare(-1.2f, 0.0f), -1); + assertEquals(Float.compare(-1.2f, -0.0f), -1); + assertEquals(0, Float.compare(-1.2f, -1.2f)); + assertEquals(Float.compare(-1.2f, -Float.MAX_VALUE), +1); + assertEquals(Float.compare(-1.2f, Float.NEGATIVE_INFINITY), +1); + + assertEquals(Float.compare(-Float.MAX_VALUE, Float.NaN), -1); + assertEquals(Float.compare(-Float.MAX_VALUE, Float.POSITIVE_INFINITY), -1); + assertEquals(Float.compare(-Float.MAX_VALUE, Float.MAX_VALUE), -1); + assertEquals(Float.compare(-Float.MAX_VALUE, 1.2f), -1); + assertEquals(Float.compare(-Float.MAX_VALUE, 0.0f), -1); + assertEquals(Float.compare(-Float.MAX_VALUE, -0.0f), -1); + assertEquals(Float.compare(-Float.MAX_VALUE, -1.2f), -1); + assertEquals(0, Float.compare(-Float.MAX_VALUE, -Float.MAX_VALUE)); + assertEquals(Float.compare(-Float.MAX_VALUE, Float.NEGATIVE_INFINITY), +1); + + assertEquals(Float.compare(Float.NEGATIVE_INFINITY, Float.NaN), -1); + assertEquals(Float.compare(Float.NEGATIVE_INFINITY, Float.POSITIVE_INFINITY), -1); + assertEquals(Float.compare(Float.NEGATIVE_INFINITY, Float.MAX_VALUE), -1); + assertEquals(Float.compare(Float.NEGATIVE_INFINITY, 1.2f), -1); + assertEquals(Float.compare(Float.NEGATIVE_INFINITY, 0.0f), -1); + assertEquals(Float.compare(Float.NEGATIVE_INFINITY, -0.0f), -1); + assertEquals(Float.compare(Float.NEGATIVE_INFINITY, -1.2f), -1); + assertEquals(Float.compare(Float.NEGATIVE_INFINITY, -Float.MAX_VALUE), -1); + assertEquals(0, Float.compare(Float.NEGATIVE_INFINITY, Float.NEGATIVE_INFINITY)); } - /** - * Test for {@link NumberUtils#toScaledBigDecimal(Float, int, RoundingMode)}. - */ + @SuppressWarnings("cast") // suppress instanceof warning check @Test - public void testToScaledBigDecimalFloatIRM() { - assertEquals(NumberUtils.toScaledBigDecimal(Float.valueOf(123.456f), 1, RoundingMode.CEILING), BigDecimal.valueOf(123.5), "toScaledBigDecimal(Float, int, RoudingMode) 1 failed"); - assertEquals(NumberUtils.toScaledBigDecimal(Float.valueOf(23.5159f), 3, RoundingMode.FLOOR), BigDecimal.valueOf(23.515), "toScaledBigDecimal(Float, int, RoudingMode) 2 failed"); - // The following happens due to roundoff error. We're ok with this. - assertEquals(NumberUtils.toScaledBigDecimal(Float.valueOf(23.525f), 2, RoundingMode.HALF_UP), BigDecimal.valueOf(23.52), "toScaledBigDecimal(Float, int, RoudingMode) 3 failed"); - assertEquals("23521.0000", NumberUtils.toScaledBigDecimal(Float.valueOf(23.521f), 4, RoundingMode.HALF_EVEN) - .multiply(BigDecimal.valueOf(1000)) - .toString(), "toScaledBigDecimal(Float, int, RoudingMode) 4 failed"); - assertEquals(NumberUtils.toScaledBigDecimal((Float) null, 2, RoundingMode.HALF_UP), BigDecimal.ZERO, "toScaledBigDecimal(Float, int, RoudingMode) 5 failed"); + public void testConstants() { + assertTrue(NumberUtils.LONG_ZERO instanceof Long); + assertTrue(NumberUtils.LONG_ONE instanceof Long); + assertTrue(NumberUtils.LONG_MINUS_ONE instanceof Long); + assertTrue(NumberUtils.INTEGER_ZERO instanceof Integer); + assertTrue(NumberUtils.INTEGER_ONE instanceof Integer); + assertTrue(NumberUtils.INTEGER_MINUS_ONE instanceof Integer); + assertTrue(NumberUtils.SHORT_ZERO instanceof Short); + assertTrue(NumberUtils.SHORT_ONE instanceof Short); + assertTrue(NumberUtils.SHORT_MINUS_ONE instanceof Short); + assertTrue(NumberUtils.BYTE_ZERO instanceof Byte); + assertTrue(NumberUtils.BYTE_ONE instanceof Byte); + assertTrue(NumberUtils.BYTE_MINUS_ONE instanceof Byte); + assertTrue(NumberUtils.DOUBLE_ZERO instanceof Double); + assertTrue(NumberUtils.DOUBLE_ONE instanceof Double); + assertTrue(NumberUtils.DOUBLE_MINUS_ONE instanceof Double); + assertTrue(NumberUtils.FLOAT_ZERO instanceof Float); + assertTrue(NumberUtils.FLOAT_ONE instanceof Float); + assertTrue(NumberUtils.FLOAT_MINUS_ONE instanceof Float); + + assertEquals(0, NumberUtils.LONG_ZERO.longValue()); + assertEquals(1, NumberUtils.LONG_ONE.longValue()); + assertEquals(NumberUtils.LONG_MINUS_ONE.longValue(), -1); + assertEquals(0, NumberUtils.INTEGER_ZERO.intValue()); + assertEquals(1, NumberUtils.INTEGER_ONE.intValue()); + assertEquals(NumberUtils.INTEGER_MINUS_ONE.intValue(), -1); + assertEquals(0, NumberUtils.SHORT_ZERO.shortValue()); + assertEquals(1, NumberUtils.SHORT_ONE.shortValue()); + assertEquals(NumberUtils.SHORT_MINUS_ONE.shortValue(), -1); + assertEquals(0, NumberUtils.BYTE_ZERO.byteValue()); + assertEquals(1, NumberUtils.BYTE_ONE.byteValue()); + assertEquals(NumberUtils.BYTE_MINUS_ONE.byteValue(), -1); + assertEquals(0.0d, NumberUtils.DOUBLE_ZERO.doubleValue()); + assertEquals(1.0d, NumberUtils.DOUBLE_ONE.doubleValue()); + assertEquals(NumberUtils.DOUBLE_MINUS_ONE.doubleValue(), -1.0d); + assertEquals(0.0f, NumberUtils.FLOAT_ZERO.floatValue()); + assertEquals(1.0f, NumberUtils.FLOAT_ONE.floatValue()); + assertEquals(NumberUtils.FLOAT_MINUS_ONE.floatValue(), -1.0f); } - /** - * Test for {@link NumberUtils#toScaledBigDecimal(Double)}. - */ + // ----------------------------------------------------------------------- @Test - public void testToScaledBigDecimalDouble() { - assertEquals(NumberUtils.toScaledBigDecimal(Double.valueOf(123.456d)), BigDecimal.valueOf(123.46), "toScaledBigDecimal(Double) 1 failed"); - // Test RoudingMode.HALF_EVEN default rounding. - assertEquals(NumberUtils.toScaledBigDecimal(Double.valueOf(23.515d)), BigDecimal.valueOf(23.52), "toScaledBigDecimal(Double) 2 failed"); - assertEquals(NumberUtils.toScaledBigDecimal(Double.valueOf(23.525d)), BigDecimal.valueOf(23.52), "toScaledBigDecimal(Double) 3 failed"); - assertEquals("2352.00", NumberUtils.toScaledBigDecimal(Double.valueOf(23.525d)) - .multiply(BigDecimal.valueOf(100)).toString(), "toScaledBigDecimal(Double) 4 failed"); - assertEquals(NumberUtils.toScaledBigDecimal((Double) null), BigDecimal.ZERO, "toScaledBigDecimal(Double) 5 failed"); + public void testConstructor() { + assertNotNull(new NumberUtils()); + final Constructor[] cons = NumberUtils.class.getDeclaredConstructors(); + assertEquals(1, cons.length); + assertTrue(Modifier.isPublic(cons[0].getModifiers())); + assertTrue(Modifier.isPublic(NumberUtils.class.getModifiers())); + assertFalse(Modifier.isFinal(NumberUtils.class.getModifiers())); } - /** - * Test for {@link NumberUtils#toScaledBigDecimal(Double, int, RoundingMode)}. - */ @Test - public void testToScaledBigDecimalDoubleIRM() { - assertEquals(NumberUtils.toScaledBigDecimal(Double.valueOf(123.456d), 1, RoundingMode.CEILING), BigDecimal.valueOf(123.5), "toScaledBigDecimal(Double, int, RoudingMode) 1 failed"); - assertEquals(NumberUtils.toScaledBigDecimal(Double.valueOf(23.5159d), 3, RoundingMode.FLOOR), BigDecimal.valueOf(23.515), "toScaledBigDecimal(Double, int, RoudingMode) 2 failed"); - assertEquals(NumberUtils.toScaledBigDecimal(Double.valueOf(23.525d), 2, RoundingMode.HALF_UP), BigDecimal.valueOf(23.53), "toScaledBigDecimal(Double, int, RoudingMode) 3 failed"); - assertEquals("23521.0000", NumberUtils.toScaledBigDecimal(Double.valueOf(23.521d), 4, RoundingMode.HALF_EVEN) - .multiply(BigDecimal.valueOf(1000)) - .toString(), "toScaledBigDecimal(Double, int, RoudingMode) 4 failed"); - assertEquals(NumberUtils.toScaledBigDecimal((Double) null, 2, RoundingMode.HALF_UP), BigDecimal.ZERO, "toScaledBigDecimal(Double, int, RoudingMode) 5 failed"); + public void testCreateBigDecimal() { + assertEquals(new BigDecimal("1234.5"), NumberUtils.createBigDecimal("1234.5"), + "createBigDecimal(String) failed"); + assertNull(NumberUtils.createBigDecimal(null), "createBigDecimal(null) failed"); + this.testCreateBigDecimalFailure(""); + this.testCreateBigDecimalFailure(" "); + this.testCreateBigDecimalFailure("\b\t\n\f\r"); + // Funky whitespaces + this.testCreateBigDecimalFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F"); + // sign alone not valid + this.testCreateBigDecimalFailure("-"); + // comment in NumberUtils suggests some implementations may incorrectly allow this + this.testCreateBigDecimalFailure("--"); + this.testCreateBigDecimalFailure("--0"); + // sign alone not valid + this.testCreateBigDecimalFailure("+"); + // in case this was also allowed by some JVMs + this.testCreateBigDecimalFailure("++"); + this.testCreateBigDecimalFailure("++0"); + } + + protected void testCreateBigDecimalFailure(final String str) { + assertThrows(NumberFormatException.class, () -> NumberUtils.createBigDecimal(str), + "createBigDecimal(\"" + str + "\") should have failed."); } - /** - * Test for {@link NumberUtils#toScaledBigDecimal(Double)}. - */ @Test - public void testToScaledBigDecimalString() { - assertEquals(NumberUtils.toScaledBigDecimal("123.456"), BigDecimal.valueOf(123.46), "toScaledBigDecimal(String) 1 failed"); - // Test RoudingMode.HALF_EVEN default rounding. - assertEquals(NumberUtils.toScaledBigDecimal("23.515"), BigDecimal.valueOf(23.52), "toScaledBigDecimal(String) 2 failed"); - assertEquals(NumberUtils.toScaledBigDecimal("23.525"), BigDecimal.valueOf(23.52), "toScaledBigDecimal(String) 3 failed"); - assertEquals("2352.00", NumberUtils.toScaledBigDecimal("23.525") - .multiply(BigDecimal.valueOf(100)).toString(), "toScaledBigDecimal(String) 4 failed"); - assertEquals(NumberUtils.toScaledBigDecimal((String) null), BigDecimal.ZERO, "toScaledBigDecimal(String) 5 failed"); + public void testCreateBigInteger() { + assertEquals(new BigInteger("12345"), NumberUtils.createBigInteger("12345"), "createBigInteger(String) failed"); + assertNull(NumberUtils.createBigInteger(null), "createBigInteger(null) failed"); + this.testCreateBigIntegerFailure(""); + this.testCreateBigIntegerFailure(" "); + this.testCreateBigIntegerFailure("\b\t\n\f\r"); + // Funky whitespaces + this.testCreateBigIntegerFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F"); + assertEquals(new BigInteger("255"), NumberUtils.createBigInteger("0xff"), "createBigInteger(String) failed"); + assertEquals(new BigInteger("255"), NumberUtils.createBigInteger("0Xff"), "createBigInteger(String) failed"); + assertEquals(new BigInteger("255"), NumberUtils.createBigInteger("#ff"), "createBigInteger(String) failed"); + assertEquals(new BigInteger("-255"), NumberUtils.createBigInteger("-0xff"), "createBigInteger(String) failed"); + assertEquals(new BigInteger("255"), NumberUtils.createBigInteger("0377"), "createBigInteger(String) failed"); + assertEquals(new BigInteger("-255"), NumberUtils.createBigInteger("-0377"), "createBigInteger(String) failed"); + assertEquals(new BigInteger("-255"), NumberUtils.createBigInteger("-0377"), "createBigInteger(String) failed"); + assertEquals(new BigInteger("-0"), NumberUtils.createBigInteger("-0"), "createBigInteger(String) failed"); + assertEquals(new BigInteger("0"), NumberUtils.createBigInteger("0"), "createBigInteger(String) failed"); + testCreateBigIntegerFailure("#"); + testCreateBigIntegerFailure("-#"); + testCreateBigIntegerFailure("0x"); + testCreateBigIntegerFailure("-0x"); + } + + protected void testCreateBigIntegerFailure(final String str) { + assertThrows(NumberFormatException.class, () -> NumberUtils.createBigInteger(str), + "createBigInteger(\"" + str + "\") should have failed."); } - /** - * Test for {@link NumberUtils#toScaledBigDecimal(Double, int, RoundingMode)}. - */ @Test - public void testToScaledBigDecimalStringIRM() { - assertEquals(NumberUtils.toScaledBigDecimal("123.456", 1, RoundingMode.CEILING), BigDecimal.valueOf(123.5), "toScaledBigDecimal(String, int, RoudingMode) 1 failed"); - assertEquals(NumberUtils.toScaledBigDecimal("23.5159", 3, RoundingMode.FLOOR), BigDecimal.valueOf(23.515), "toScaledBigDecimal(String, int, RoudingMode) 2 failed"); - assertEquals(NumberUtils.toScaledBigDecimal("23.525", 2, RoundingMode.HALF_UP), BigDecimal.valueOf(23.53), "toScaledBigDecimal(String, int, RoudingMode) 3 failed"); - assertEquals("23521.0000", NumberUtils.toScaledBigDecimal("23.521", 4, RoundingMode.HALF_EVEN) - .multiply(BigDecimal.valueOf(1000)) - .toString(), "toScaledBigDecimal(String, int, RoudingMode) 4 failed"); - assertEquals(NumberUtils.toScaledBigDecimal((String) null, 2, RoundingMode.HALF_UP), BigDecimal.ZERO, "toScaledBigDecimal(String, int, RoudingMode) 5 failed"); + public void testCreateDouble() { + assertEquals(Double.valueOf("1234.5"), NumberUtils.createDouble("1234.5"), "createDouble(String) failed"); + assertNull(NumberUtils.createDouble(null), "createDouble(null) failed"); + this.testCreateDoubleFailure(""); + this.testCreateDoubleFailure(" "); + this.testCreateDoubleFailure("\b\t\n\f\r"); + // Funky whitespaces + this.testCreateDoubleFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F"); + } + + protected void testCreateDoubleFailure(final String str) { + assertThrows(NumberFormatException.class, () -> NumberUtils.createDouble(str), + "createDouble(\"" + str + "\") should have failed."); + } + + @Test + public void testCreateFloat() { + assertEquals(Float.valueOf("1234.5"), NumberUtils.createFloat("1234.5"), "createFloat(String) failed"); + assertNull(NumberUtils.createFloat(null), "createFloat(null) failed"); + this.testCreateFloatFailure(""); + this.testCreateFloatFailure(" "); + this.testCreateFloatFailure("\b\t\n\f\r"); + // Funky whitespaces + this.testCreateFloatFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F"); + } + + protected void testCreateFloatFailure(final String str) { + assertThrows(NumberFormatException.class, () -> NumberUtils.createFloat(str), + "createFloat(\"" + str + "\") should have failed."); + } + + @Test + public void testCreateInteger() { + assertEquals(Integer.valueOf("12345"), NumberUtils.createInteger("12345"), "createInteger(String) failed"); + assertNull(NumberUtils.createInteger(null), "createInteger(null) failed"); + this.testCreateIntegerFailure(""); + this.testCreateIntegerFailure(" "); + this.testCreateIntegerFailure("\b\t\n\f\r"); + // Funky whitespaces + this.testCreateIntegerFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F"); + } + + protected void testCreateIntegerFailure(final String str) { + assertThrows(NumberFormatException.class, () -> NumberUtils.createInteger(str), + "createInteger(\"" + str + "\") should have failed."); + } + + @Test + public void testCreateLong() { + assertEquals(Long.valueOf("12345"), NumberUtils.createLong("12345"), "createLong(String) failed"); + assertNull(NumberUtils.createLong(null), "createLong(null) failed"); + this.testCreateLongFailure(""); + this.testCreateLongFailure(" "); + this.testCreateLongFailure("\b\t\n\f\r"); + // Funky whitespaces + this.testCreateLongFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F"); + } + + protected void testCreateLongFailure(final String str) { + assertThrows(NumberFormatException.class, () -> NumberUtils.createLong(str), + "createLong(\"" + str + "\") should have failed."); } @Test @@ -364,8 +476,8 @@ public void testCreateNumber() { assertEquals(Double.valueOf("1234.5"), NumberUtils.createNumber("1234.5d"), "createNumber(String) 3 failed"); assertEquals(Float.valueOf("1234.5"), NumberUtils.createNumber("1234.5F"), "createNumber(String) 4 failed"); assertEquals(Float.valueOf("1234.5"), NumberUtils.createNumber("1234.5f"), "createNumber(String) 4 failed"); - assertEquals(Long.valueOf(Integer.MAX_VALUE + 1L), NumberUtils.createNumber("" - + (Integer.MAX_VALUE + 1L)), "createNumber(String) 5 failed"); + assertEquals(Long.valueOf(Integer.MAX_VALUE + 1L), NumberUtils.createNumber("" + (Integer.MAX_VALUE + 1L)), + "createNumber(String) 5 failed"); assertEquals(Long.valueOf(12345), NumberUtils.createNumber("12345L"), "createNumber(String) 6 failed"); assertEquals(Long.valueOf(12345), NumberUtils.createNumber("12345l"), "createNumber(String) 6 failed"); assertEquals(Float.valueOf("-1234.5"), NumberUtils.createNumber("-1234.5"), "createNumber(String) 7 failed"); @@ -376,16 +488,23 @@ public void testCreateNumber() { assertEquals(-0xFADE, NumberUtils.createNumber("-0Xfade").intValue(), "createNumber(String) 10b failed"); assertEquals(Double.valueOf("1.1E200"), NumberUtils.createNumber("1.1E200"), "createNumber(String) 11 failed"); assertEquals(Float.valueOf("1.1E20"), NumberUtils.createNumber("1.1E20"), "createNumber(String) 12 failed"); - assertEquals(Double.valueOf("-1.1E200"), NumberUtils.createNumber("-1.1E200"), "createNumber(String) 13 failed"); - assertEquals(Double.valueOf("1.1E-200"), NumberUtils.createNumber("1.1E-200"), "createNumber(String) 14 failed"); + assertEquals(Double.valueOf("-1.1E200"), NumberUtils.createNumber("-1.1E200"), + "createNumber(String) 13 failed"); + assertEquals(Double.valueOf("1.1E-200"), NumberUtils.createNumber("1.1E-200"), + "createNumber(String) 14 failed"); assertNull(NumberUtils.createNumber(null), "createNumber(null) failed"); - assertEquals(new BigInteger("12345678901234567890"), NumberUtils.createNumber("12345678901234567890L"), "createNumber(String) failed"); + assertEquals(new BigInteger("12345678901234567890"), NumberUtils.createNumber("12345678901234567890L"), + "createNumber(String) failed"); - assertEquals(new BigDecimal("1.1E-700"), NumberUtils.createNumber("1.1E-700F"), "createNumber(String) 15 failed"); + assertEquals(new BigDecimal("1.1E-700"), NumberUtils.createNumber("1.1E-700F"), + "createNumber(String) 15 failed"); - assertEquals(Long.valueOf("10" + Integer.MAX_VALUE), NumberUtils.createNumber("10" + Integer.MAX_VALUE + "L"), "createNumber(String) 16 failed"); - assertEquals(Long.valueOf("10" + Integer.MAX_VALUE), NumberUtils.createNumber("10" + Integer.MAX_VALUE), "createNumber(String) 17 failed"); - assertEquals(new BigInteger("10" + Long.MAX_VALUE), NumberUtils.createNumber("10" + Long.MAX_VALUE), "createNumber(String) 18 failed"); + assertEquals(Long.valueOf("10" + Integer.MAX_VALUE), NumberUtils.createNumber("10" + Integer.MAX_VALUE + "L"), + "createNumber(String) 16 failed"); + assertEquals(Long.valueOf("10" + Integer.MAX_VALUE), NumberUtils.createNumber("10" + Integer.MAX_VALUE), + "createNumber(String) 17 failed"); + assertEquals(new BigInteger("10" + Long.MAX_VALUE), NumberUtils.createNumber("10" + Long.MAX_VALUE), + "createNumber(String) 18 failed"); // LANG-521 assertEquals(Float.valueOf("2."), NumberUtils.createNumber("2."), "createNumber(String) LANG-521 failed"); @@ -394,7 +513,8 @@ public void testCreateNumber() { assertFalse(checkCreateNumber("1eE"), "createNumber(String) succeeded"); // LANG-693 - assertEquals(Double.valueOf(Double.MAX_VALUE), NumberUtils.createNumber("" + Double.MAX_VALUE), "createNumber(String) LANG-693 failed"); + assertEquals(Double.valueOf(Double.MAX_VALUE), NumberUtils.createNumber("" + Double.MAX_VALUE), + "createNumber(String) LANG-693 failed"); // LANG-822 // ensure that the underlying negative number would create a BigDecimal @@ -404,408 +524,563 @@ public void testCreateNumber() { // LANG-1018 assertEquals(Double.valueOf("-160952.54"), NumberUtils.createNumber("-160952.54"), - "createNumber(String) LANG-1018 failed"); + "createNumber(String) LANG-1018 failed"); // LANG-1187 assertEquals(Double.valueOf("6264583.33"), NumberUtils.createNumber("6264583.33"), - "createNumber(String) LANG-1187 failed"); + "createNumber(String) LANG-1187 failed"); // LANG-1215 assertEquals(Double.valueOf("193343.82"), NumberUtils.createNumber("193343.82"), - "createNumber(String) LANG-1215 failed"); + "createNumber(String) LANG-1215 failed"); // LANG-1060 - assertEquals(Double.valueOf("001234.5678"), NumberUtils.createNumber("001234.5678"), "createNumber(String) LANG-1060a failed"); - assertEquals(Double.valueOf("+001234.5678"), NumberUtils.createNumber("+001234.5678"), "createNumber(String) LANG-1060b failed"); - assertEquals(Double.valueOf("-001234.5678"), NumberUtils.createNumber("-001234.5678"), "createNumber(String) LANG-1060c failed"); - assertEquals(Double.valueOf("0000.00000"), NumberUtils.createNumber("0000.00000d"), "createNumber(String) LANG-1060d failed"); - assertEquals(Float.valueOf("001234.56"), NumberUtils.createNumber("001234.56"), "createNumber(String) LANG-1060e failed"); - assertEquals(Float.valueOf("+001234.56"), NumberUtils.createNumber("+001234.56"), "createNumber(String) LANG-1060f failed"); - assertEquals(Float.valueOf("-001234.56"), NumberUtils.createNumber("-001234.56"), "createNumber(String) LANG-1060g failed"); - assertEquals(Float.valueOf("0000.10"), NumberUtils.createNumber("0000.10"), "createNumber(String) LANG-1060h failed"); - assertEquals(Float.valueOf("001.1E20"), NumberUtils.createNumber("001.1E20"), "createNumber(String) LANG-1060i failed"); - assertEquals(Float.valueOf("+001.1E20"), NumberUtils.createNumber("+001.1E20"), "createNumber(String) LANG-1060j failed"); - assertEquals(Float.valueOf("-001.1E20"), NumberUtils.createNumber("-001.1E20"), "createNumber(String) LANG-1060k failed"); - assertEquals(Double.valueOf("001.1E200"), NumberUtils.createNumber("001.1E200"), "createNumber(String) LANG-1060l failed"); - assertEquals(Double.valueOf("+001.1E200"), NumberUtils.createNumber("+001.1E200"), "createNumber(String) LANG-1060m failed"); - assertEquals(Double.valueOf("-001.1E200"), NumberUtils.createNumber("-001.1E200"), "createNumber(String) LANG-1060n failed"); + assertEquals(Double.valueOf("001234.5678"), NumberUtils.createNumber("001234.5678"), + "createNumber(String) LANG-1060a failed"); + assertEquals(Double.valueOf("+001234.5678"), NumberUtils.createNumber("+001234.5678"), + "createNumber(String) LANG-1060b failed"); + assertEquals(Double.valueOf("-001234.5678"), NumberUtils.createNumber("-001234.5678"), + "createNumber(String) LANG-1060c failed"); + assertEquals(Double.valueOf("0000.00000"), NumberUtils.createNumber("0000.00000d"), + "createNumber(String) LANG-1060d failed"); + assertEquals(Float.valueOf("001234.56"), NumberUtils.createNumber("001234.56"), + "createNumber(String) LANG-1060e failed"); + assertEquals(Float.valueOf("+001234.56"), NumberUtils.createNumber("+001234.56"), + "createNumber(String) LANG-1060f failed"); + assertEquals(Float.valueOf("-001234.56"), NumberUtils.createNumber("-001234.56"), + "createNumber(String) LANG-1060g failed"); + assertEquals(Float.valueOf("0000.10"), NumberUtils.createNumber("0000.10"), + "createNumber(String) LANG-1060h failed"); + assertEquals(Float.valueOf("001.1E20"), NumberUtils.createNumber("001.1E20"), + "createNumber(String) LANG-1060i failed"); + assertEquals(Float.valueOf("+001.1E20"), NumberUtils.createNumber("+001.1E20"), + "createNumber(String) LANG-1060j failed"); + assertEquals(Float.valueOf("-001.1E20"), NumberUtils.createNumber("-001.1E20"), + "createNumber(String) LANG-1060k failed"); + assertEquals(Double.valueOf("001.1E200"), NumberUtils.createNumber("001.1E200"), + "createNumber(String) LANG-1060l failed"); + assertEquals(Double.valueOf("+001.1E200"), NumberUtils.createNumber("+001.1E200"), + "createNumber(String) LANG-1060m failed"); + assertEquals(Double.valueOf("-001.1E200"), NumberUtils.createNumber("-001.1E200"), + "createNumber(String) LANG-1060n failed"); } @Test - public void testLang1087() { - // no sign cases - assertEquals(Float.class, NumberUtils.createNumber("0.0").getClass()); - assertEquals(Float.valueOf("0.0"), NumberUtils.createNumber("0.0")); - // explicit positive sign cases - assertEquals(Float.class, NumberUtils.createNumber("+0.0").getClass()); - assertEquals(Float.valueOf("+0.0"), NumberUtils.createNumber("+0.0")); - // negative sign cases - assertEquals(Float.class, NumberUtils.createNumber("-0.0").getClass()); - assertEquals(Float.valueOf("-0.0"), NumberUtils.createNumber("-0.0")); + // Check that the code fails to create a valid number when preceded by -- rather than - + public void testCreateNumberFailure_1() { + assertThrows(NumberFormatException.class, () -> NumberUtils.createNumber("--1.1E-700F")); } @Test - public void TestLang747() { - assertEquals(Integer.valueOf(0x8000), NumberUtils.createNumber("0x8000")); - assertEquals(Integer.valueOf(0x80000), NumberUtils.createNumber("0x80000")); - assertEquals(Integer.valueOf(0x800000), NumberUtils.createNumber("0x800000")); - assertEquals(Integer.valueOf(0x8000000), NumberUtils.createNumber("0x8000000")); - assertEquals(Integer.valueOf(0x7FFFFFFF), NumberUtils.createNumber("0x7FFFFFFF")); - assertEquals(Long.valueOf(0x80000000L), NumberUtils.createNumber("0x80000000")); - assertEquals(Long.valueOf(0xFFFFFFFFL), NumberUtils.createNumber("0xFFFFFFFF")); + // Check that the code fails to create a valid number when both e and E are present (with decimal) + public void testCreateNumberFailure_2() { + assertThrows(NumberFormatException.class, () -> NumberUtils.createNumber("-1.1E+0-7e00")); + } - // Leading zero tests - assertEquals(Integer.valueOf(0x8000000), NumberUtils.createNumber("0x08000000")); - assertEquals(Integer.valueOf(0x7FFFFFFF), NumberUtils.createNumber("0x007FFFFFFF")); - assertEquals(Long.valueOf(0x80000000L), NumberUtils.createNumber("0x080000000")); - assertEquals(Long.valueOf(0xFFFFFFFFL), NumberUtils.createNumber("0x00FFFFFFFF")); - - assertEquals(Long.valueOf(0x800000000L), NumberUtils.createNumber("0x800000000")); - assertEquals(Long.valueOf(0x8000000000L), NumberUtils.createNumber("0x8000000000")); - assertEquals(Long.valueOf(0x80000000000L), NumberUtils.createNumber("0x80000000000")); - assertEquals(Long.valueOf(0x800000000000L), NumberUtils.createNumber("0x800000000000")); - assertEquals(Long.valueOf(0x8000000000000L), NumberUtils.createNumber("0x8000000000000")); - assertEquals(Long.valueOf(0x80000000000000L), NumberUtils.createNumber("0x80000000000000")); - assertEquals(Long.valueOf(0x800000000000000L), NumberUtils.createNumber("0x800000000000000")); - assertEquals(Long.valueOf(0x7FFFFFFFFFFFFFFFL), NumberUtils.createNumber("0x7FFFFFFFFFFFFFFF")); - // N.B. Cannot use a hex constant such as 0x8000000000000000L here as that is interpreted as a negative long - assertEquals(new BigInteger("8000000000000000", 16), NumberUtils.createNumber("0x8000000000000000")); - assertEquals(new BigInteger("FFFFFFFFFFFFFFFF", 16), NumberUtils.createNumber("0xFFFFFFFFFFFFFFFF")); + @Test + // Check that the code fails to create a valid number when both e and E are present (no decimal) + public void testCreateNumberFailure_3() { + assertThrows(NumberFormatException.class, () -> NumberUtils.createNumber("-11E+0-7e00")); + } - // Leading zero tests - assertEquals(Long.valueOf(0x80000000000000L), NumberUtils.createNumber("0x00080000000000000")); - assertEquals(Long.valueOf(0x800000000000000L), NumberUtils.createNumber("0x0800000000000000")); - assertEquals(Long.valueOf(0x7FFFFFFFFFFFFFFFL), NumberUtils.createNumber("0x07FFFFFFFFFFFFFFF")); - // N.B. Cannot use a hex constant such as 0x8000000000000000L here as that is interpreted as a negative long - assertEquals(new BigInteger("8000000000000000", 16), NumberUtils.createNumber("0x00008000000000000000")); - assertEquals(new BigInteger("FFFFFFFFFFFFFFFF", 16), NumberUtils.createNumber("0x0FFFFFFFFFFFFFFFF")); + @Test + // Check that the code fails to create a valid number when both e and E are present (no decimal) + public void testCreateNumberFailure_4() { + assertThrows(NumberFormatException.class, () -> NumberUtils.createNumber("1eE+00001")); } - @Test - // Check that the code fails to create a valid number when preceded by -- rather than - - public void testCreateNumberFailure_1() { - assertThrows(NumberFormatException.class, () -> NumberUtils.createNumber("--1.1E-700F")); + @Test + // Check that the code fails to create a valid number when there are multiple trailing 'f' characters (LANG-1205) + public void testCreateNumberFailure_5() { + assertThrows(NumberFormatException.class, () -> NumberUtils.createNumber("1234.5ff")); + } + + @Test + // Check that the code fails to create a valid number when there are multiple trailing 'F' characters (LANG-1205) + public void testCreateNumberFailure_6() { + assertThrows(NumberFormatException.class, () -> NumberUtils.createNumber("1234.5FF")); + } + + @Test + // Check that the code fails to create a valid number when there are multiple trailing 'd' characters (LANG-1205) + public void testCreateNumberFailure_7() { + assertThrows(NumberFormatException.class, () -> NumberUtils.createNumber("1234.5dd")); + } + + @Test + // Check that the code fails to create a valid number when there are multiple trailing 'D' characters (LANG-1205) + public void testCreateNumberFailure_8() { + assertThrows(NumberFormatException.class, () -> NumberUtils.createNumber("1234.5DD")); + } + + // Tests to show when magnitude causes switch to next Number type + // Will probably need to be adjusted if code is changed to check precision (LANG-693) + @Test + public void testCreateNumberMagnitude() { + // Test Float.MAX_VALUE, and same with +1 in final digit to check conversion changes to next Number type + assertEquals(Float.valueOf(Float.MAX_VALUE), NumberUtils.createNumber("3.4028235e+38")); + assertEquals(Double.valueOf(3.4028236e+38), NumberUtils.createNumber("3.4028236e+38")); + + // Test Double.MAX_VALUE + assertEquals(Double.valueOf(Double.MAX_VALUE), NumberUtils.createNumber("1.7976931348623157e+308")); + // Test with +2 in final digit (+1 does not cause roll-over to BigDecimal) + assertEquals(new BigDecimal("1.7976931348623159e+308"), NumberUtils.createNumber("1.7976931348623159e+308")); + + assertEquals(Integer.valueOf(0x12345678), NumberUtils.createNumber("0x12345678")); + assertEquals(Long.valueOf(0x123456789L), NumberUtils.createNumber("0x123456789")); + + assertEquals(Long.valueOf(0x7fffffffffffffffL), NumberUtils.createNumber("0x7fffffffffffffff")); + // Does not appear to be a way to create a literal BigInteger of this magnitude + assertEquals(new BigInteger("7fffffffffffffff0", 16), NumberUtils.createNumber("0x7fffffffffffffff0")); + + assertEquals(Long.valueOf(0x7fffffffffffffffL), NumberUtils.createNumber("#7fffffffffffffff")); + assertEquals(new BigInteger("7fffffffffffffff0", 16), NumberUtils.createNumber("#7fffffffffffffff0")); + + assertEquals(Integer.valueOf(017777777777), NumberUtils.createNumber("017777777777")); // 31 bits + assertEquals(Long.valueOf(037777777777L), NumberUtils.createNumber("037777777777")); // 32 bits + + // 63 bits + assertEquals(Long.valueOf(0777777777777777777777L), NumberUtils.createNumber("0777777777777777777777")); + // 64 bits + assertEquals(new BigInteger("1777777777777777777777", 8), NumberUtils.createNumber("01777777777777777777777")); + } + + /** + * Tests isCreatable(String) and tests that createNumber(String) returns a valid number iff isCreatable(String) + * returns false. + */ + @Test + public void testIsCreatable() { + compareIsCreatableWithCreateNumber("12345", true); + compareIsCreatableWithCreateNumber("1234.5", true); + compareIsCreatableWithCreateNumber(".12345", true); + compareIsCreatableWithCreateNumber("1234E5", true); + compareIsCreatableWithCreateNumber("1234E+5", true); + compareIsCreatableWithCreateNumber("1234E-5", true); + compareIsCreatableWithCreateNumber("123.4E5", true); + compareIsCreatableWithCreateNumber("-1234", true); + compareIsCreatableWithCreateNumber("-1234.5", true); + compareIsCreatableWithCreateNumber("-.12345", true); + compareIsCreatableWithCreateNumber("-1234E5", true); + compareIsCreatableWithCreateNumber("0", true); + compareIsCreatableWithCreateNumber("0.1", true); // LANG-1216 + compareIsCreatableWithCreateNumber("-0", true); + compareIsCreatableWithCreateNumber("01234", true); + compareIsCreatableWithCreateNumber("-01234", true); + compareIsCreatableWithCreateNumber("-0xABC123", true); + compareIsCreatableWithCreateNumber("-0x0", true); + compareIsCreatableWithCreateNumber("123.4E21D", true); + compareIsCreatableWithCreateNumber("-221.23F", true); + compareIsCreatableWithCreateNumber("22338L", true); + + compareIsCreatableWithCreateNumber(null, false); + compareIsCreatableWithCreateNumber("", false); + compareIsCreatableWithCreateNumber(" ", false); + compareIsCreatableWithCreateNumber("\r\n\t", false); + compareIsCreatableWithCreateNumber("--2.3", false); + compareIsCreatableWithCreateNumber(".12.3", false); + compareIsCreatableWithCreateNumber("-123E", false); + compareIsCreatableWithCreateNumber("-123E+-212", false); + compareIsCreatableWithCreateNumber("-123E2.12", false); + compareIsCreatableWithCreateNumber("0xGF", false); + compareIsCreatableWithCreateNumber("0xFAE-1", false); + compareIsCreatableWithCreateNumber(".", false); + compareIsCreatableWithCreateNumber("-0ABC123", false); + compareIsCreatableWithCreateNumber("123.4E-D", false); + compareIsCreatableWithCreateNumber("123.4ED", false); + compareIsCreatableWithCreateNumber("1234E5l", false); + compareIsCreatableWithCreateNumber("11a", false); + compareIsCreatableWithCreateNumber("1a", false); + compareIsCreatableWithCreateNumber("a", false); + compareIsCreatableWithCreateNumber("11g", false); + compareIsCreatableWithCreateNumber("11z", false); + compareIsCreatableWithCreateNumber("11def", false); + compareIsCreatableWithCreateNumber("11d11", false); + compareIsCreatableWithCreateNumber("11 11", false); + compareIsCreatableWithCreateNumber(" 1111", false); + compareIsCreatableWithCreateNumber("1111 ", false); + + compareIsCreatableWithCreateNumber("2.", true); // LANG-521 + compareIsCreatableWithCreateNumber("1.1L", false); // LANG-664 } @Test - // Check that the code fails to create a valid number when both e and E are present (with decimal) - public void testCreateNumberFailure_2() { - assertThrows(NumberFormatException.class, () -> NumberUtils.createNumber("-1.1E+0-7e00")); + public void testIsDigits() { + assertFalse(NumberUtils.isDigits(null), "isDigits(null) failed"); + assertFalse(NumberUtils.isDigits(""), "isDigits('') failed"); + assertTrue(NumberUtils.isDigits("12345"), "isDigits(String) failed"); + assertFalse(NumberUtils.isDigits("1234.5"), "isDigits(String) neg 1 failed"); + assertFalse(NumberUtils.isDigits("1ab"), "isDigits(String) neg 3 failed"); + assertFalse(NumberUtils.isDigits("abc"), "isDigits(String) neg 4 failed"); } + /** + * Tests isCreatable(String) and tests that createNumber(String) returns a valid number iff isCreatable(String) + * returns false. + */ @Test - // Check that the code fails to create a valid number when both e and E are present (no decimal) - public void testCreateNumberFailure_3() { - assertThrows(NumberFormatException.class, () -> NumberUtils.createNumber("-11E+0-7e00")); - } + public void testIsNumber() { + compareIsNumberWithCreateNumber("12345", true); + compareIsNumberWithCreateNumber("1234.5", true); + compareIsNumberWithCreateNumber(".12345", true); + compareIsNumberWithCreateNumber("1234E5", true); + compareIsNumberWithCreateNumber("1234E+5", true); + compareIsNumberWithCreateNumber("1234E-5", true); + compareIsNumberWithCreateNumber("123.4E5", true); + compareIsNumberWithCreateNumber("-1234", true); + compareIsNumberWithCreateNumber("-1234.5", true); + compareIsNumberWithCreateNumber("-.12345", true); + compareIsNumberWithCreateNumber("-0001.12345", true); + compareIsNumberWithCreateNumber("-000.12345", true); + compareIsNumberWithCreateNumber("+00.12345", true); + compareIsNumberWithCreateNumber("+0002.12345", true); + compareIsNumberWithCreateNumber("-1234E5", true); + compareIsNumberWithCreateNumber("0", true); + compareIsNumberWithCreateNumber("-0", true); + compareIsNumberWithCreateNumber("01234", true); + compareIsNumberWithCreateNumber("-01234", true); + compareIsNumberWithCreateNumber("-0xABC123", true); + compareIsNumberWithCreateNumber("-0x0", true); + compareIsNumberWithCreateNumber("123.4E21D", true); + compareIsNumberWithCreateNumber("-221.23F", true); + compareIsNumberWithCreateNumber("22338L", true); - @Test - // Check that the code fails to create a valid number when both e and E are present (no decimal) - public void testCreateNumberFailure_4() { - assertThrows(NumberFormatException.class, () -> NumberUtils.createNumber("1eE+00001")); + compareIsNumberWithCreateNumber(null, false); + compareIsNumberWithCreateNumber("", false); + compareIsNumberWithCreateNumber(" ", false); + compareIsNumberWithCreateNumber("\r\n\t", false); + compareIsNumberWithCreateNumber("--2.3", false); + + compareIsNumberWithCreateNumber(".12.3", false); + compareIsNumberWithCreateNumber("-123E", false); + compareIsNumberWithCreateNumber("-123E+-212", false); + compareIsNumberWithCreateNumber("-123E2.12", false); + compareIsNumberWithCreateNumber("0xGF", false); + compareIsNumberWithCreateNumber("0xFAE-1", false); + compareIsNumberWithCreateNumber(".", false); + compareIsNumberWithCreateNumber("-0ABC123", false); + compareIsNumberWithCreateNumber("123.4E-D", false); + compareIsNumberWithCreateNumber("123.4ED", false); + compareIsNumberWithCreateNumber("+000E.12345", false); + compareIsNumberWithCreateNumber("-000E.12345", false); + compareIsNumberWithCreateNumber("1234E5l", false); + compareIsNumberWithCreateNumber("11a", false); + compareIsNumberWithCreateNumber("1a", false); + compareIsNumberWithCreateNumber("a", false); + compareIsNumberWithCreateNumber("11g", false); + compareIsNumberWithCreateNumber("11z", false); + compareIsNumberWithCreateNumber("11def", false); + compareIsNumberWithCreateNumber("11d11", false); + compareIsNumberWithCreateNumber("11 11", false); + compareIsNumberWithCreateNumber(" 1111", false); + compareIsNumberWithCreateNumber("1111 ", false); + + compareIsNumberWithCreateNumber("2.", true); // LANG-521 + compareIsNumberWithCreateNumber("1.1L", false); // LANG-664 } @Test - // Check that the code fails to create a valid number when there are multiple trailing 'f' characters (LANG-1205) - public void testCreateNumberFailure_5() { - assertThrows(NumberFormatException.class, () -> NumberUtils.createNumber("1234.5ff")); + public void testIsNumberLANG1252() { + compareIsNumberWithCreateNumber("+2", true); + compareIsNumberWithCreateNumber("+2.0", true); } @Test - // Check that the code fails to create a valid number when there are multiple trailing 'F' characters (LANG-1205) - public void testCreateNumberFailure_6() { - assertThrows(NumberFormatException.class, () -> NumberUtils.createNumber("1234.5FF")); + public void testIsNumberLANG1385() { + compareIsNumberWithCreateNumber("L", false); } @Test - // Check that the code fails to create a valid number when there are multiple trailing 'd' characters (LANG-1205) - public void testCreateNumberFailure_7() { - assertThrows(NumberFormatException.class, () -> NumberUtils.createNumber("1234.5dd")); + public void testIsNumberLANG971() { + compareIsNumberWithCreateNumber("0085", false); + compareIsNumberWithCreateNumber("085", false); + compareIsNumberWithCreateNumber("08", false); + compareIsNumberWithCreateNumber("07", true); + compareIsNumberWithCreateNumber("00", true); } @Test - // Check that the code fails to create a valid number when there are multiple trailing 'D' characters (LANG-1205) - public void testCreateNumberFailure_8() { - assertThrows(NumberFormatException.class, () -> NumberUtils.createNumber("1234.5DD")); + public void testIsNumberLANG972() { + compareIsNumberWithCreateNumber("0xABCD", true); + compareIsNumberWithCreateNumber("0XABCD", true); } - // Tests to show when magnitude causes switch to next Number type - // Will probably need to be adjusted if code is changed to check precision (LANG-693) @Test - public void testCreateNumberMagnitude() { - // Test Float.MAX_VALUE, and same with +1 in final digit to check conversion changes to next Number type - assertEquals(Float.valueOf(Float.MAX_VALUE), NumberUtils.createNumber("3.4028235e+38")); - assertEquals(Double.valueOf(3.4028236e+38), NumberUtils.createNumber("3.4028236e+38")); - - // Test Double.MAX_VALUE - assertEquals(Double.valueOf(Double.MAX_VALUE), NumberUtils.createNumber("1.7976931348623157e+308")); - // Test with +2 in final digit (+1 does not cause roll-over to BigDecimal) - assertEquals(new BigDecimal("1.7976931348623159e+308"), NumberUtils.createNumber("1.7976931348623159e+308")); - - assertEquals(Integer.valueOf(0x12345678), NumberUtils.createNumber("0x12345678")); - assertEquals(Long.valueOf(0x123456789L), NumberUtils.createNumber("0x123456789")); - - assertEquals(Long.valueOf(0x7fffffffffffffffL), NumberUtils.createNumber("0x7fffffffffffffff")); - // Does not appear to be a way to create a literal BigInteger of this magnitude - assertEquals(new BigInteger("7fffffffffffffff0", 16), NumberUtils.createNumber("0x7fffffffffffffff0")); - - assertEquals(Long.valueOf(0x7fffffffffffffffL), NumberUtils.createNumber("#7fffffffffffffff")); - assertEquals(new BigInteger("7fffffffffffffff0", 16), NumberUtils.createNumber("#7fffffffffffffff0")); - - assertEquals(Integer.valueOf(017777777777), NumberUtils.createNumber("017777777777")); // 31 bits - assertEquals(Long.valueOf(037777777777L), NumberUtils.createNumber("037777777777")); // 32 bits - - assertEquals(Long.valueOf(0777777777777777777777L), NumberUtils.createNumber("0777777777777777777777")); // 63 bits - assertEquals(new BigInteger("1777777777777777777777", 8), NumberUtils.createNumber("01777777777777777777777")); // 64 bits + public void testIsNumberLANG992() { + compareIsNumberWithCreateNumber("0.0", true); + compareIsNumberWithCreateNumber("0.4790", true); } @Test - public void testCreateFloat() { - assertEquals(Float.valueOf("1234.5"), NumberUtils.createFloat("1234.5"), "createFloat(String) failed"); - assertNull(NumberUtils.createFloat(null), "createFloat(null) failed"); - this.testCreateFloatFailure(""); - this.testCreateFloatFailure(" "); - this.testCreateFloatFailure("\b\t\n\f\r"); - // Funky whitespaces - this.testCreateFloatFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F"); + public void testIsParsable() { + assertFalse(NumberUtils.isParsable(null)); + assertFalse(NumberUtils.isParsable("")); + assertFalse(NumberUtils.isParsable("0xC1AB")); + assertFalse(NumberUtils.isParsable("65CBA2")); + assertFalse(NumberUtils.isParsable("pendro")); + assertFalse(NumberUtils.isParsable("64, 2")); + assertFalse(NumberUtils.isParsable("64.2.2")); + assertFalse(NumberUtils.isParsable("64.")); + assertFalse(NumberUtils.isParsable("64L")); + assertFalse(NumberUtils.isParsable("-")); + assertFalse(NumberUtils.isParsable("--2")); + assertTrue(NumberUtils.isParsable("64.2")); + assertTrue(NumberUtils.isParsable("64")); + assertTrue(NumberUtils.isParsable("018")); + assertTrue(NumberUtils.isParsable(".18")); + assertTrue(NumberUtils.isParsable("-65")); + assertTrue(NumberUtils.isParsable("-018")); + assertTrue(NumberUtils.isParsable("-018.2")); + assertTrue(NumberUtils.isParsable("-.236")); } - protected void testCreateFloatFailure(final String str) { - assertThrows( - NumberFormatException.class, - () -> NumberUtils.createFloat(str), "createFloat(\"" + str + "\") should have failed."); + @Test + public void testLang1087() { + // no sign cases + assertEquals(Float.class, NumberUtils.createNumber("0.0").getClass()); + assertEquals(Float.valueOf("0.0"), NumberUtils.createNumber("0.0")); + // explicit positive sign cases + assertEquals(Float.class, NumberUtils.createNumber("+0.0").getClass()); + assertEquals(Float.valueOf("+0.0"), NumberUtils.createNumber("+0.0")); + // negative sign cases + assertEquals(Float.class, NumberUtils.createNumber("-0.0").getClass()); + assertEquals(Float.valueOf("-0.0"), NumberUtils.createNumber("-0.0")); } @Test - public void testCreateDouble() { - assertEquals(Double.valueOf("1234.5"), NumberUtils.createDouble("1234.5"), "createDouble(String) failed"); - assertNull(NumberUtils.createDouble(null), "createDouble(null) failed"); - this.testCreateDoubleFailure(""); - this.testCreateDoubleFailure(" "); - this.testCreateDoubleFailure("\b\t\n\f\r"); - // Funky whitespaces - this.testCreateDoubleFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F"); + public void testLANG1252() { + compareIsCreatableWithCreateNumber("+2", true); + compareIsCreatableWithCreateNumber("+2.0", true); } - protected void testCreateDoubleFailure(final String str) { - assertThrows( - NumberFormatException.class, - () -> NumberUtils.createDouble(str), - "createDouble(\"" + str + "\") should have failed."); + @Test + public void testLang300() { + NumberUtils.createNumber("-1l"); + NumberUtils.createNumber("01l"); + NumberUtils.createNumber("1l"); } @Test - public void testCreateInteger() { - assertEquals(Integer.valueOf("12345"), NumberUtils.createInteger("12345"), "createInteger(String) failed"); - assertNull(NumberUtils.createInteger(null), "createInteger(null) failed"); - this.testCreateIntegerFailure(""); - this.testCreateIntegerFailure(" "); - this.testCreateIntegerFailure("\b\t\n\f\r"); - // Funky whitespaces - this.testCreateIntegerFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F"); - } + public void testLang381() { + assertTrue(Double.isNaN(NumberUtils.min(1.2, 2.5, Double.NaN))); + assertTrue(Double.isNaN(NumberUtils.max(1.2, 2.5, Double.NaN))); + assertTrue(Float.isNaN(NumberUtils.min(1.2f, 2.5f, Float.NaN))); + assertTrue(Float.isNaN(NumberUtils.max(1.2f, 2.5f, Float.NaN))); - protected void testCreateIntegerFailure(final String str) { - assertThrows( - NumberFormatException.class, - () -> NumberUtils.createInteger(str), - "createInteger(\"" + str + "\") should have failed."); - } + final double[] a = new double[] {1.2, Double.NaN, 3.7, 27.0, 42.0, Double.NaN}; + assertTrue(Double.isNaN(NumberUtils.max(a))); + assertTrue(Double.isNaN(NumberUtils.min(a))); - @Test - public void testCreateLong() { - assertEquals(Long.valueOf("12345"), NumberUtils.createLong("12345"), "createLong(String) failed"); - assertNull(NumberUtils.createLong(null), "createLong(null) failed"); - this.testCreateLongFailure(""); - this.testCreateLongFailure(" "); - this.testCreateLongFailure("\b\t\n\f\r"); - // Funky whitespaces - this.testCreateLongFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F"); - } + final double[] b = new double[] {Double.NaN, 1.2, Double.NaN, 3.7, 27.0, 42.0, Double.NaN}; + assertTrue(Double.isNaN(NumberUtils.max(b))); + assertTrue(Double.isNaN(NumberUtils.min(b))); - protected void testCreateLongFailure(final String str) { - assertThrows( - NumberFormatException.class, - () -> NumberUtils.createLong(str), - "createLong(\"" + str + "\") should have failed."); + final float[] aF = new float[] {1.2f, Float.NaN, 3.7f, 27.0f, 42.0f, Float.NaN}; + assertTrue(Float.isNaN(NumberUtils.max(aF))); + + final float[] bF = new float[] {Float.NaN, 1.2f, Float.NaN, 3.7f, 27.0f, 42.0f, Float.NaN}; + assertTrue(Float.isNaN(NumberUtils.max(bF))); } @Test - public void testCreateBigInteger() { - assertEquals(new BigInteger("12345"), NumberUtils.createBigInteger("12345"), "createBigInteger(String) failed"); - assertNull(NumberUtils.createBigInteger(null), "createBigInteger(null) failed"); - this.testCreateBigIntegerFailure(""); - this.testCreateBigIntegerFailure(" "); - this.testCreateBigIntegerFailure("\b\t\n\f\r"); - // Funky whitespaces - this.testCreateBigIntegerFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F"); - assertEquals(new BigInteger("255"), NumberUtils.createBigInteger("0xff"), "createBigInteger(String) failed"); - assertEquals(new BigInteger("255"), NumberUtils.createBigInteger("0Xff"), "createBigInteger(String) failed"); - assertEquals(new BigInteger("255"), NumberUtils.createBigInteger("#ff"), "createBigInteger(String) failed"); - assertEquals(new BigInteger("-255"), NumberUtils.createBigInteger("-0xff"), "createBigInteger(String) failed"); - assertEquals(new BigInteger("255"), NumberUtils.createBigInteger("0377"), "createBigInteger(String) failed"); - assertEquals(new BigInteger("-255"), NumberUtils.createBigInteger("-0377"), "createBigInteger(String) failed"); - assertEquals(new BigInteger("-255"), NumberUtils.createBigInteger("-0377"), "createBigInteger(String) failed"); - assertEquals(new BigInteger("-0"), NumberUtils.createBigInteger("-0"), "createBigInteger(String) failed"); - assertEquals(new BigInteger("0"), NumberUtils.createBigInteger("0"), "createBigInteger(String) failed"); - testCreateBigIntegerFailure("#"); - testCreateBigIntegerFailure("-#"); - testCreateBigIntegerFailure("0x"); - testCreateBigIntegerFailure("-0x"); - } + public void TestLang747() { + assertEquals(Integer.valueOf(0x8000), NumberUtils.createNumber("0x8000")); + assertEquals(Integer.valueOf(0x80000), NumberUtils.createNumber("0x80000")); + assertEquals(Integer.valueOf(0x800000), NumberUtils.createNumber("0x800000")); + assertEquals(Integer.valueOf(0x8000000), NumberUtils.createNumber("0x8000000")); + assertEquals(Integer.valueOf(0x7FFFFFFF), NumberUtils.createNumber("0x7FFFFFFF")); + assertEquals(Long.valueOf(0x80000000L), NumberUtils.createNumber("0x80000000")); + assertEquals(Long.valueOf(0xFFFFFFFFL), NumberUtils.createNumber("0xFFFFFFFF")); - protected void testCreateBigIntegerFailure(final String str) { - assertThrows( - NumberFormatException.class, - () -> NumberUtils.createBigInteger(str), - "createBigInteger(\"" + str + "\") should have failed."); + // Leading zero tests + assertEquals(Integer.valueOf(0x8000000), NumberUtils.createNumber("0x08000000")); + assertEquals(Integer.valueOf(0x7FFFFFFF), NumberUtils.createNumber("0x007FFFFFFF")); + assertEquals(Long.valueOf(0x80000000L), NumberUtils.createNumber("0x080000000")); + assertEquals(Long.valueOf(0xFFFFFFFFL), NumberUtils.createNumber("0x00FFFFFFFF")); + + assertEquals(Long.valueOf(0x800000000L), NumberUtils.createNumber("0x800000000")); + assertEquals(Long.valueOf(0x8000000000L), NumberUtils.createNumber("0x8000000000")); + assertEquals(Long.valueOf(0x80000000000L), NumberUtils.createNumber("0x80000000000")); + assertEquals(Long.valueOf(0x800000000000L), NumberUtils.createNumber("0x800000000000")); + assertEquals(Long.valueOf(0x8000000000000L), NumberUtils.createNumber("0x8000000000000")); + assertEquals(Long.valueOf(0x80000000000000L), NumberUtils.createNumber("0x80000000000000")); + assertEquals(Long.valueOf(0x800000000000000L), NumberUtils.createNumber("0x800000000000000")); + assertEquals(Long.valueOf(0x7FFFFFFFFFFFFFFFL), NumberUtils.createNumber("0x7FFFFFFFFFFFFFFF")); + // N.B. Cannot use a hex constant such as 0x8000000000000000L here as that is interpreted as a negative long + assertEquals(new BigInteger("8000000000000000", 16), NumberUtils.createNumber("0x8000000000000000")); + assertEquals(new BigInteger("FFFFFFFFFFFFFFFF", 16), NumberUtils.createNumber("0xFFFFFFFFFFFFFFFF")); + + // Leading zero tests + assertEquals(Long.valueOf(0x80000000000000L), NumberUtils.createNumber("0x00080000000000000")); + assertEquals(Long.valueOf(0x800000000000000L), NumberUtils.createNumber("0x0800000000000000")); + assertEquals(Long.valueOf(0x7FFFFFFFFFFFFFFFL), NumberUtils.createNumber("0x07FFFFFFFFFFFFFFF")); + // N.B. Cannot use a hex constant such as 0x8000000000000000L here as that is interpreted as a negative long + assertEquals(new BigInteger("8000000000000000", 16), NumberUtils.createNumber("0x00008000000000000000")); + assertEquals(new BigInteger("FFFFFFFFFFFFFFFF", 16), NumberUtils.createNumber("0x0FFFFFFFFFFFFFFFF")); } @Test - public void testCreateBigDecimal() { - assertEquals(new BigDecimal("1234.5"), NumberUtils.createBigDecimal("1234.5"), "createBigDecimal(String) failed"); - assertNull(NumberUtils.createBigDecimal(null), "createBigDecimal(null) failed"); - this.testCreateBigDecimalFailure(""); - this.testCreateBigDecimalFailure(" "); - this.testCreateBigDecimalFailure("\b\t\n\f\r"); - // Funky whitespaces - this.testCreateBigDecimalFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F"); - this.testCreateBigDecimalFailure("-"); // sign alone not valid - this.testCreateBigDecimalFailure("--"); // comment in NumberUtils suggests some implementations may incorrectly allow this - this.testCreateBigDecimalFailure("--0"); - this.testCreateBigDecimalFailure("+"); // sign alone not valid - this.testCreateBigDecimalFailure("++"); // in case this was also allowed by some JVMs - this.testCreateBigDecimalFailure("++0"); - } - - protected void testCreateBigDecimalFailure(final String str) { - assertThrows( - NumberFormatException.class, - () -> NumberUtils.createBigDecimal(str), - "createBigDecimal(\"" + str + "\") should have failed."); + public void testLANG971() { + compareIsCreatableWithCreateNumber("0085", false); + compareIsCreatableWithCreateNumber("085", false); + compareIsCreatableWithCreateNumber("08", false); + compareIsCreatableWithCreateNumber("07", true); + compareIsCreatableWithCreateNumber("00", true); } - // min/max tests - // ---------------------------------------------------------------------- @Test - public void testMinLong_nullArray() { - assertThrows(NullPointerException.class, () -> NumberUtils.min((long[]) null)); + public void testLANG972() { + compareIsCreatableWithCreateNumber("0xABCD", true); + compareIsCreatableWithCreateNumber("0XABCD", true); } @Test - public void testMinLong_emptyArray() { - assertThrows(IllegalArgumentException.class, NumberUtils::min); + public void testLANG992() { + compareIsCreatableWithCreateNumber("0.0", true); + compareIsCreatableWithCreateNumber("0.4790", true); } @Test - public void testMinLong() { - assertEquals(5L, NumberUtils.min(5L), "min(long[]) failed for array length 1"); - assertEquals(6L, NumberUtils.min(6L, 9L), "min(long[]) failed for array length 2"); - - assertEquals(-10L, NumberUtils.min(-10L, -5L, 0L, 5L, 10L)); - assertEquals(-10L, NumberUtils.min(-5L, 0L, -10L, 5L, 10L)); + public void testMaxByte() { + assertEquals((byte) 5, NumberUtils.max((byte) 5), "max(byte[]) failed for array length 1"); + assertEquals((byte) 9, NumberUtils.max((byte) 6, (byte) 9), "max(byte[]) failed for array length 2"); + assertEquals((byte) 10, NumberUtils.max((byte) -10, (byte) -5, (byte) 0, (byte) 5, (byte) 10), + "max(byte[]) failed for array length 5"); + assertEquals((byte) 10, NumberUtils.max((byte) -10, (byte) -5, (byte) 0, (byte) 5, (byte) 10)); + assertEquals((byte) 10, NumberUtils.max((byte) -5, (byte) 0, (byte) 10, (byte) 5, (byte) -10)); } @Test - public void testMinInt_nullArray() { - assertThrows(NullPointerException.class, () -> NumberUtils.min((int[]) null)); + public void testMaxByte_emptyArray() { + assertThrows(IllegalArgumentException.class, NumberUtils::max); } @Test - public void testMinInt_emptyArray() { - assertThrows(IllegalArgumentException.class, NumberUtils::min); + public void testMaxByte_nullArray() { + assertThrows(NullPointerException.class, () -> NumberUtils.max((byte[]) null)); } @Test - public void testMinInt() { - assertEquals(5, NumberUtils.min(5), "min(int[]) failed for array length 1"); - assertEquals(6, NumberUtils.min(6, 9), "min(int[]) failed for array length 2"); + public void testMaxDouble() { + final double[] d = null; + assertThrows(NullPointerException.class, () -> NumberUtils.max(d), "No exception was thrown for null input."); - assertEquals(-10, NumberUtils.min(-10, -5, 0, 5, 10)); - assertEquals(-10, NumberUtils.min(-5, 0, -10, 5, 10)); + assertThrows(IllegalArgumentException.class, NumberUtils::max, "No exception was thrown for empty input."); + + assertEquals(5.1f, NumberUtils.max(5.1f), "max(double[]) failed for array length 1"); + assertEquals(9.2f, NumberUtils.max(6.3f, 9.2f), "max(double[]) failed for array length 2"); + assertEquals(10.4f, NumberUtils.max(-10.5f, -5.6f, 0, 5.7f, 10.4f), "max(double[]) failed for float length 5"); + assertEquals(10, NumberUtils.max(-10, -5, 0, 5, 10), 0.0001); + assertEquals(10, NumberUtils.max(-5, 0, 10, 5, -10), 0.0001); } @Test - public void testMinShort_nullArray() { - assertThrows(NullPointerException.class, () -> NumberUtils.min((short[]) null)); + public void testMaxDouble_emptyArray() { + assertThrows(IllegalArgumentException.class, NumberUtils::max); } @Test - public void testMinShort_emptyArray() { - assertThrows(IllegalArgumentException.class, NumberUtils::min); + public void testMaxDouble_nullArray() { + assertThrows(NullPointerException.class, () -> NumberUtils.max((double[]) null)); } @Test - public void testMinShort() { - assertEquals((short) 5, NumberUtils.min((short) 5), "min(short[]) failed for array length 1"); - assertEquals((short) 6, NumberUtils.min((short) 6, (short) 9), "min(short[]) failed for array length 2"); - - assertEquals((short) -10, NumberUtils.min((short) -10, (short) -5, (short) 0, (short) 5, (short) 10)); - assertEquals((short) -10, NumberUtils.min((short) -5, (short) 0, (short) -10, (short) 5, (short) 10)); + public void testMaxFloat() { + assertEquals(5.1f, NumberUtils.max(5.1f), "max(float[]) failed for array length 1"); + assertEquals(9.2f, NumberUtils.max(6.3f, 9.2f), "max(float[]) failed for array length 2"); + assertEquals(10.4f, NumberUtils.max(-10.5f, -5.6f, 0, 5.7f, 10.4f), "max(float[]) failed for float length 5"); + assertEquals(10, NumberUtils.max(-10, -5, 0, 5, 10), 0.0001f); + assertEquals(10, NumberUtils.max(-5, 0, 10, 5, -10), 0.0001f); } @Test - public void testMinByte_nullArray() { - assertThrows(NullPointerException.class, () -> NumberUtils.min((byte[]) null)); + public void testMaxFloat_emptyArray() { + assertThrows(IllegalArgumentException.class, NumberUtils::max); } @Test - public void testMinByte_emptyArray() { - assertThrows(IllegalArgumentException.class, NumberUtils::min); + public void testMaxFloat_nullArray() { + assertThrows(NullPointerException.class, () -> NumberUtils.max((float[]) null)); } @Test - public void testMinByte() { - assertEquals((byte) 5, NumberUtils.min((byte) 5), "min(byte[]) failed for array length 1"); - assertEquals((byte) 6, NumberUtils.min((byte) 6, (byte) 9), "min(byte[]) failed for array length 2"); - - assertEquals((byte) -10, NumberUtils.min((byte) -10, (byte) -5, (byte) 0, (byte) 5, (byte) 10)); - assertEquals((byte) -10, NumberUtils.min((byte) -5, (byte) 0, (byte) -10, (byte) 5, (byte) 10)); + public void testMaximumByte() { + final byte low = 123; + final byte mid = 123 + 1; + final byte high = 123 + 2; + assertEquals(high, NumberUtils.max(low, mid, high), "maximum(byte, byte, byte) 1 failed"); + assertEquals(high, NumberUtils.max(mid, low, high), "maximum(byte, byte, byte) 2 failed"); + assertEquals(high, NumberUtils.max(mid, high, low), "maximum(byte, byte, byte) 3 failed"); + assertEquals(high, NumberUtils.max(high, mid, high), "maximum(byte, byte, byte) 4 failed"); } @Test - public void testMinDouble_nullArray() { - assertThrows(NullPointerException.class, () -> NumberUtils.min((double[]) null)); + public void testMaximumDouble() { + final double low = 12.3; + final double mid = 12.3 + 1; + final double high = 12.3 + 2; + assertEquals(high, NumberUtils.max(low, mid, high), 0.0001); + assertEquals(high, NumberUtils.max(mid, low, high), 0.0001); + assertEquals(high, NumberUtils.max(mid, high, low), 0.0001); + assertEquals(mid, NumberUtils.max(low, mid, low), 0.0001); + assertEquals(high, NumberUtils.max(high, mid, high), 0.0001); } @Test - public void testMinDouble_emptyArray() { - assertThrows(IllegalArgumentException.class, NumberUtils::min); + public void testMaximumFloat() { + final float low = 12.3f; + final float mid = 12.3f + 1; + final float high = 12.3f + 2; + assertEquals(high, NumberUtils.max(low, mid, high), 0.0001f); + assertEquals(high, NumberUtils.max(mid, low, high), 0.0001f); + assertEquals(high, NumberUtils.max(mid, high, low), 0.0001f); + assertEquals(mid, NumberUtils.max(low, mid, low), 0.0001f); + assertEquals(high, NumberUtils.max(high, mid, high), 0.0001f); } @Test - public void testMinDouble() { - assertEquals(5.12, NumberUtils.min(5.12), "min(double[]) failed for array length 1"); - assertEquals(6.23, NumberUtils.min(6.23, 9.34), "min(double[]) failed for array length 2"); - assertEquals(-10.45, NumberUtils.min(-10.45, -5.56, 0, 5.67, 10.78), "min(double[]) failed for array length 5"); - assertEquals(-10, NumberUtils.min(-10, -5, 0, 5, 10), 0.0001); - assertEquals(-10, NumberUtils.min(-5, 0, -10, 5, 10), 0.0001); + public void testMaximumInt() { + assertEquals(12345, NumberUtils.max(12345, 12345 - 1, 12345 - 2), "maximum(int, int, int) 1 failed"); + assertEquals(12345, NumberUtils.max(12345 - 1, 12345, 12345 - 2), "maximum(int, int, int) 2 failed"); + assertEquals(12345, NumberUtils.max(12345 - 1, 12345 - 2, 12345), "maximum(int, int, int) 3 failed"); + assertEquals(12345, NumberUtils.max(12345 - 1, 12345, 12345), "maximum(int, int, int) 4 failed"); + assertEquals(12345, NumberUtils.max(12345, 12345, 12345), "maximum(int, int, int) 5 failed"); } @Test - public void testMinFloat_nullArray() { - assertThrows(NullPointerException.class, () -> NumberUtils.min((float[]) null)); + public void testMaximumLong() { + assertEquals(12345L, NumberUtils.max(12345L, 12345L - 1L, 12345L - 2L), "maximum(long, long, long) 1 failed"); + assertEquals(12345L, NumberUtils.max(12345L - 1L, 12345L, 12345L - 2L), "maximum(long, long, long) 2 failed"); + assertEquals(12345L, NumberUtils.max(12345L - 1L, 12345L - 2L, 12345L), "maximum(long, long, long) 3 failed"); + assertEquals(12345L, NumberUtils.max(12345L - 1L, 12345L, 12345L), "maximum(long, long, long) 4 failed"); + assertEquals(12345L, NumberUtils.max(12345L, 12345L, 12345L), "maximum(long, long, long) 5 failed"); } @Test - public void testMinFloat_emptyArray() { - assertThrows(IllegalArgumentException.class, NumberUtils::min); + public void testMaximumShort() { + final short low = 1234; + final short mid = 1234 + 1; + final short high = 1234 + 2; + assertEquals(high, NumberUtils.max(low, mid, high), "maximum(short, short, short) 1 failed"); + assertEquals(high, NumberUtils.max(mid, low, high), "maximum(short, short, short) 2 failed"); + assertEquals(high, NumberUtils.max(mid, high, low), "maximum(short, short, short) 3 failed"); + assertEquals(high, NumberUtils.max(high, mid, high), "maximum(short, short, short) 4 failed"); } @Test - public void testMinFloat() { - assertEquals(5.9f, NumberUtils.min(5.9f), "min(float[]) failed for array length 1"); - assertEquals(6.8f, NumberUtils.min(6.8f, 9.7f), "min(float[]) failed for array length 2"); - assertEquals(-10.6f, NumberUtils.min(-10.6f, -5.5f, 0, 5.4f, 10.3f), "min(float[]) failed for array length 5"); - assertEquals(-10, NumberUtils.min(-10, -5, 0, 5, 10), 0.0001f); - assertEquals(-10, NumberUtils.min(-5, 0, -10, 5, 10), 0.0001f); + public void testMaxInt() { + assertEquals(5, NumberUtils.max(5), "max(int[]) failed for array length 1"); + assertEquals(9, NumberUtils.max(6, 9), "max(int[]) failed for array length 2"); + assertEquals(10, NumberUtils.max(-10, -5, 0, 5, 10), "max(int[]) failed for array length 5"); + assertEquals(10, NumberUtils.max(-10, -5, 0, 5, 10)); + assertEquals(10, NumberUtils.max(-5, 0, 10, 5, -10)); } @Test - public void testMaxLong_nullArray() { - assertThrows(NullPointerException.class, () -> NumberUtils.max((long[]) null)); + public void testMaxInt_emptyArray() { + assertThrows(IllegalArgumentException.class, NumberUtils::max); } @Test - public void testMaxLong_emptyArray() { - assertThrows(IllegalArgumentException.class, NumberUtils::max); + public void testMaxInt_nullArray() { + assertThrows(NullPointerException.class, () -> NumberUtils.max((int[]) null)); } @Test @@ -818,136 +1093,90 @@ public void testMaxLong() { } @Test - public void testMaxInt_nullArray() { - assertThrows(NullPointerException.class, () -> NumberUtils.max((int[]) null)); - } - - @Test - public void testMaxInt_emptyArray() { + public void testMaxLong_emptyArray() { assertThrows(IllegalArgumentException.class, NumberUtils::max); } @Test - public void testMaxInt() { - assertEquals(5, NumberUtils.max(5), "max(int[]) failed for array length 1"); - assertEquals(9, NumberUtils.max(6, 9), "max(int[]) failed for array length 2"); - assertEquals(10, NumberUtils.max(-10, -5, 0, 5, 10), "max(int[]) failed for array length 5"); - assertEquals(10, NumberUtils.max(-10, -5, 0, 5, 10)); - assertEquals(10, NumberUtils.max(-5, 0, 10, 5, -10)); - } - - @Test - public void testMaxShort_nullArray() { - assertThrows(NullPointerException.class, () -> NumberUtils.max((short[]) null)); - } - - @Test - public void testMaxShort_emptyArray() { - assertThrows(IllegalArgumentException.class, NumberUtils::max); + public void testMaxLong_nullArray() { + assertThrows(NullPointerException.class, () -> NumberUtils.max((long[]) null)); } @Test public void testMaxShort() { assertEquals((short) 5, NumberUtils.max((short) 5), "max(short[]) failed for array length 1"); assertEquals((short) 9, NumberUtils.max((short) 6, (short) 9), "max(short[]) failed for array length 2"); - assertEquals((short) 10, NumberUtils.max((short) -10, (short) -5, (short) 0, (short) 5, (short) 10), "max(short[]) failed for array length 5"); + assertEquals((short) 10, NumberUtils.max((short) -10, (short) -5, (short) 0, (short) 5, (short) 10), + "max(short[]) failed for array length 5"); assertEquals((short) 10, NumberUtils.max((short) -10, (short) -5, (short) 0, (short) 5, (short) 10)); assertEquals((short) 10, NumberUtils.max((short) -5, (short) 0, (short) 10, (short) 5, (short) -10)); } @Test - public void testMaxByte_nullArray() { - assertThrows(NullPointerException.class, () -> NumberUtils.max((byte[]) null)); - } - - @Test - public void testMaxByte_emptyArray() { + public void testMaxShort_emptyArray() { assertThrows(IllegalArgumentException.class, NumberUtils::max); } @Test - public void testMaxByte() { - assertEquals((byte) 5, NumberUtils.max((byte) 5), "max(byte[]) failed for array length 1"); - assertEquals((byte) 9, NumberUtils.max((byte) 6, (byte) 9), "max(byte[]) failed for array length 2"); - assertEquals((byte) 10, NumberUtils.max((byte) -10, (byte) -5, (byte) 0, (byte) 5, (byte) 10), "max(byte[]) failed for array length 5"); - assertEquals((byte) 10, NumberUtils.max((byte) -10, (byte) -5, (byte) 0, (byte) 5, (byte) 10)); - assertEquals((byte) 10, NumberUtils.max((byte) -5, (byte) 0, (byte) 10, (byte) 5, (byte) -10)); + public void testMaxShort_nullArray() { + assertThrows(NullPointerException.class, () -> NumberUtils.max((short[]) null)); } @Test - public void testMaxDouble_nullArray() { - assertThrows(NullPointerException.class, () -> NumberUtils.max((double[]) null)); + public void testMinByte() { + assertEquals((byte) 5, NumberUtils.min((byte) 5), "min(byte[]) failed for array length 1"); + assertEquals((byte) 6, NumberUtils.min((byte) 6, (byte) 9), "min(byte[]) failed for array length 2"); + + assertEquals((byte) -10, NumberUtils.min((byte) -10, (byte) -5, (byte) 0, (byte) 5, (byte) 10)); + assertEquals((byte) -10, NumberUtils.min((byte) -5, (byte) 0, (byte) -10, (byte) 5, (byte) 10)); } @Test - public void testMaxDouble_emptyArray() { - assertThrows(IllegalArgumentException.class, NumberUtils::max); + public void testMinByte_emptyArray() { + assertThrows(IllegalArgumentException.class, NumberUtils::min); } @Test - public void testMaxDouble() { - final double[] d = null; - assertThrows( - NullPointerException.class, () -> NumberUtils.max(d), "No exception was thrown for null input."); - - assertThrows( - IllegalArgumentException.class, - NumberUtils::max, - "No exception was thrown for empty input."); - - assertEquals(5.1f, NumberUtils.max(5.1f), "max(double[]) failed for array length 1"); - assertEquals(9.2f, NumberUtils.max(6.3f, 9.2f), "max(double[]) failed for array length 2"); - assertEquals(10.4f, NumberUtils.max(-10.5f, -5.6f, 0, 5.7f, 10.4f), "max(double[]) failed for float length 5"); - assertEquals(10, NumberUtils.max(-10, -5, 0, 5, 10), 0.0001); - assertEquals(10, NumberUtils.max(-5, 0, 10, 5, -10), 0.0001); + public void testMinByte_nullArray() { + assertThrows(NullPointerException.class, () -> NumberUtils.min((byte[]) null)); } @Test - public void testMaxFloat_nullArray() { - assertThrows(NullPointerException.class, () -> NumberUtils.max((float[]) null)); + public void testMinDouble() { + assertEquals(5.12, NumberUtils.min(5.12), "min(double[]) failed for array length 1"); + assertEquals(6.23, NumberUtils.min(6.23, 9.34), "min(double[]) failed for array length 2"); + assertEquals(-10.45, NumberUtils.min(-10.45, -5.56, 0, 5.67, 10.78), "min(double[]) failed for array length 5"); + assertEquals(-10, NumberUtils.min(-10, -5, 0, 5, 10), 0.0001); + assertEquals(-10, NumberUtils.min(-5, 0, -10, 5, 10), 0.0001); } @Test - public void testMaxFloat_emptyArray() { - assertThrows(IllegalArgumentException.class, NumberUtils::max); + public void testMinDouble_emptyArray() { + assertThrows(IllegalArgumentException.class, NumberUtils::min); } @Test - public void testMaxFloat() { - assertEquals(5.1f, NumberUtils.max(5.1f), "max(float[]) failed for array length 1"); - assertEquals(9.2f, NumberUtils.max(6.3f, 9.2f), "max(float[]) failed for array length 2"); - assertEquals(10.4f, NumberUtils.max(-10.5f, -5.6f, 0, 5.7f, 10.4f), "max(float[]) failed for float length 5"); - assertEquals(10, NumberUtils.max(-10, -5, 0, 5, 10), 0.0001f); - assertEquals(10, NumberUtils.max(-5, 0, 10, 5, -10), 0.0001f); + public void testMinDouble_nullArray() { + assertThrows(NullPointerException.class, () -> NumberUtils.min((double[]) null)); } @Test - public void testMinimumLong() { - assertEquals(12345L, NumberUtils.min(12345L, 12345L + 1L, 12345L + 2L), "minimum(long, long, long) 1 failed"); - assertEquals(12345L, NumberUtils.min(12345L + 1L, 12345L, 12345 + 2L), "minimum(long, long, long) 2 failed"); - assertEquals(12345L, NumberUtils.min(12345L + 1L, 12345L + 2L, 12345L), "minimum(long, long, long) 3 failed"); - assertEquals(12345L, NumberUtils.min(12345L + 1L, 12345L, 12345L), "minimum(long, long, long) 4 failed"); - assertEquals(12345L, NumberUtils.min(12345L, 12345L, 12345L), "minimum(long, long, long) 5 failed"); + public void testMinFloat() { + assertEquals(5.9f, NumberUtils.min(5.9f), "min(float[]) failed for array length 1"); + assertEquals(6.8f, NumberUtils.min(6.8f, 9.7f), "min(float[]) failed for array length 2"); + assertEquals(-10.6f, NumberUtils.min(-10.6f, -5.5f, 0, 5.4f, 10.3f), "min(float[]) failed for array length 5"); + assertEquals(-10, NumberUtils.min(-10, -5, 0, 5, 10), 0.0001f); + assertEquals(-10, NumberUtils.min(-5, 0, -10, 5, 10), 0.0001f); } @Test - public void testMinimumInt() { - assertEquals(12345, NumberUtils.min(12345, 12345 + 1, 12345 + 2), "minimum(int, int, int) 1 failed"); - assertEquals(12345, NumberUtils.min(12345 + 1, 12345, 12345 + 2), "minimum(int, int, int) 2 failed"); - assertEquals(12345, NumberUtils.min(12345 + 1, 12345 + 2, 12345), "minimum(int, int, int) 3 failed"); - assertEquals(12345, NumberUtils.min(12345 + 1, 12345, 12345), "minimum(int, int, int) 4 failed"); - assertEquals(12345, NumberUtils.min(12345, 12345, 12345), "minimum(int, int, int) 5 failed"); + public void testMinFloat_emptyArray() { + assertThrows(IllegalArgumentException.class, NumberUtils::min); } @Test - public void testMinimumShort() { - final short low = 1234; - final short mid = 1234 + 1; - final short high = 1234 + 2; - assertEquals(low, NumberUtils.min(low, mid, high), "minimum(short, short, short) 1 failed"); - assertEquals(low, NumberUtils.min(mid, low, high), "minimum(short, short, short) 2 failed"); - assertEquals(low, NumberUtils.min(mid, high, low), "minimum(short, short, short) 3 failed"); - assertEquals(low, NumberUtils.min(low, mid, low), "minimum(short, short, short) 4 failed"); + public void testMinFloat_nullArray() { + assertThrows(NullPointerException.class, () -> NumberUtils.min((float[]) null)); } @Test @@ -986,593 +1215,418 @@ public void testMinimumFloat() { } @Test - public void testMaximumLong() { - assertEquals(12345L, NumberUtils.max(12345L, 12345L - 1L, 12345L - 2L), "maximum(long, long, long) 1 failed"); - assertEquals(12345L, NumberUtils.max(12345L - 1L, 12345L, 12345L - 2L), "maximum(long, long, long) 2 failed"); - assertEquals(12345L, NumberUtils.max(12345L - 1L, 12345L - 2L, 12345L), "maximum(long, long, long) 3 failed"); - assertEquals(12345L, NumberUtils.max(12345L - 1L, 12345L, 12345L), "maximum(long, long, long) 4 failed"); - assertEquals(12345L, NumberUtils.max(12345L, 12345L, 12345L), "maximum(long, long, long) 5 failed"); - } - - @Test - public void testMaximumInt() { - assertEquals(12345, NumberUtils.max(12345, 12345 - 1, 12345 - 2), "maximum(int, int, int) 1 failed"); - assertEquals(12345, NumberUtils.max(12345 - 1, 12345, 12345 - 2), "maximum(int, int, int) 2 failed"); - assertEquals(12345, NumberUtils.max(12345 - 1, 12345 - 2, 12345), "maximum(int, int, int) 3 failed"); - assertEquals(12345, NumberUtils.max(12345 - 1, 12345, 12345), "maximum(int, int, int) 4 failed"); - assertEquals(12345, NumberUtils.max(12345, 12345, 12345), "maximum(int, int, int) 5 failed"); - } - - @Test - public void testMaximumShort() { - final short low = 1234; - final short mid = 1234 + 1; - final short high = 1234 + 2; - assertEquals(high, NumberUtils.max(low, mid, high), "maximum(short, short, short) 1 failed"); - assertEquals(high, NumberUtils.max(mid, low, high), "maximum(short, short, short) 2 failed"); - assertEquals(high, NumberUtils.max(mid, high, low), "maximum(short, short, short) 3 failed"); - assertEquals(high, NumberUtils.max(high, mid, high), "maximum(short, short, short) 4 failed"); - } - - @Test - public void testMaximumByte() { - final byte low = 123; - final byte mid = 123 + 1; - final byte high = 123 + 2; - assertEquals(high, NumberUtils.max(low, mid, high), "maximum(byte, byte, byte) 1 failed"); - assertEquals(high, NumberUtils.max(mid, low, high), "maximum(byte, byte, byte) 2 failed"); - assertEquals(high, NumberUtils.max(mid, high, low), "maximum(byte, byte, byte) 3 failed"); - assertEquals(high, NumberUtils.max(high, mid, high), "maximum(byte, byte, byte) 4 failed"); - } - - @Test - public void testMaximumDouble() { - final double low = 12.3; - final double mid = 12.3 + 1; - final double high = 12.3 + 2; - assertEquals(high, NumberUtils.max(low, mid, high), 0.0001); - assertEquals(high, NumberUtils.max(mid, low, high), 0.0001); - assertEquals(high, NumberUtils.max(mid, high, low), 0.0001); - assertEquals(mid, NumberUtils.max(low, mid, low), 0.0001); - assertEquals(high, NumberUtils.max(high, mid, high), 0.0001); - } - - @Test - public void testMaximumFloat() { - final float low = 12.3f; - final float mid = 12.3f + 1; - final float high = 12.3f + 2; - assertEquals(high, NumberUtils.max(low, mid, high), 0.0001f); - assertEquals(high, NumberUtils.max(mid, low, high), 0.0001f); - assertEquals(high, NumberUtils.max(mid, high, low), 0.0001f); - assertEquals(mid, NumberUtils.max(low, mid, low), 0.0001f); - assertEquals(high, NumberUtils.max(high, mid, high), 0.0001f); - } - - // Testing JDK against old Lang functionality - @Test - public void testCompareDouble() { - assertEquals(0, Double.compare(Double.NaN, Double.NaN)); - assertEquals(Double.compare(Double.NaN, Double.POSITIVE_INFINITY), +1); - assertEquals(Double.compare(Double.NaN, Double.MAX_VALUE), +1); - assertEquals(Double.compare(Double.NaN, 1.2d), +1); - assertEquals(Double.compare(Double.NaN, 0.0d), +1); - assertEquals(Double.compare(Double.NaN, -0.0d), +1); - assertEquals(Double.compare(Double.NaN, -1.2d), +1); - assertEquals(Double.compare(Double.NaN, -Double.MAX_VALUE), +1); - assertEquals(Double.compare(Double.NaN, Double.NEGATIVE_INFINITY), +1); - - assertEquals(Double.compare(Double.POSITIVE_INFINITY, Double.NaN), -1); - assertEquals(0, Double.compare(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY)); - assertEquals(Double.compare(Double.POSITIVE_INFINITY, Double.MAX_VALUE), +1); - assertEquals(Double.compare(Double.POSITIVE_INFINITY, 1.2d), +1); - assertEquals(Double.compare(Double.POSITIVE_INFINITY, 0.0d), +1); - assertEquals(Double.compare(Double.POSITIVE_INFINITY, -0.0d), +1); - assertEquals(Double.compare(Double.POSITIVE_INFINITY, -1.2d), +1); - assertEquals(Double.compare(Double.POSITIVE_INFINITY, -Double.MAX_VALUE), +1); - assertEquals(Double.compare(Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY), +1); - - assertEquals(Double.compare(Double.MAX_VALUE, Double.NaN), -1); - assertEquals(Double.compare(Double.MAX_VALUE, Double.POSITIVE_INFINITY), -1); - assertEquals(0, Double.compare(Double.MAX_VALUE, Double.MAX_VALUE)); - assertEquals(Double.compare(Double.MAX_VALUE, 1.2d), +1); - assertEquals(Double.compare(Double.MAX_VALUE, 0.0d), +1); - assertEquals(Double.compare(Double.MAX_VALUE, -0.0d), +1); - assertEquals(Double.compare(Double.MAX_VALUE, -1.2d), +1); - assertEquals(Double.compare(Double.MAX_VALUE, -Double.MAX_VALUE), +1); - assertEquals(Double.compare(Double.MAX_VALUE, Double.NEGATIVE_INFINITY), +1); - - assertEquals(Double.compare(1.2d, Double.NaN), -1); - assertEquals(Double.compare(1.2d, Double.POSITIVE_INFINITY), -1); - assertEquals(Double.compare(1.2d, Double.MAX_VALUE), -1); - assertEquals(0, Double.compare(1.2d, 1.2d)); - assertEquals(Double.compare(1.2d, 0.0d), +1); - assertEquals(Double.compare(1.2d, -0.0d), +1); - assertEquals(Double.compare(1.2d, -1.2d), +1); - assertEquals(Double.compare(1.2d, -Double.MAX_VALUE), +1); - assertEquals(Double.compare(1.2d, Double.NEGATIVE_INFINITY), +1); - - assertEquals(Double.compare(0.0d, Double.NaN), -1); - assertEquals(Double.compare(0.0d, Double.POSITIVE_INFINITY), -1); - assertEquals(Double.compare(0.0d, Double.MAX_VALUE), -1); - assertEquals(Double.compare(0.0d, 1.2d), -1); - assertEquals(0, Double.compare(0.0d, 0.0d)); - assertEquals(Double.compare(0.0d, -0.0d), +1); - assertEquals(Double.compare(0.0d, -1.2d), +1); - assertEquals(Double.compare(0.0d, -Double.MAX_VALUE), +1); - assertEquals(Double.compare(0.0d, Double.NEGATIVE_INFINITY), +1); - - assertEquals(Double.compare(-0.0d, Double.NaN), -1); - assertEquals(Double.compare(-0.0d, Double.POSITIVE_INFINITY), -1); - assertEquals(Double.compare(-0.0d, Double.MAX_VALUE), -1); - assertEquals(Double.compare(-0.0d, 1.2d), -1); - assertEquals(Double.compare(-0.0d, 0.0d), -1); - assertEquals(0, Double.compare(-0.0d, -0.0d)); - assertEquals(Double.compare(-0.0d, -1.2d), +1); - assertEquals(Double.compare(-0.0d, -Double.MAX_VALUE), +1); - assertEquals(Double.compare(-0.0d, Double.NEGATIVE_INFINITY), +1); - - assertEquals(Double.compare(-1.2d, Double.NaN), -1); - assertEquals(Double.compare(-1.2d, Double.POSITIVE_INFINITY), -1); - assertEquals(Double.compare(-1.2d, Double.MAX_VALUE), -1); - assertEquals(Double.compare(-1.2d, 1.2d), -1); - assertEquals(Double.compare(-1.2d, 0.0d), -1); - assertEquals(Double.compare(-1.2d, -0.0d), -1); - assertEquals(0, Double.compare(-1.2d, -1.2d)); - assertEquals(Double.compare(-1.2d, -Double.MAX_VALUE), +1); - assertEquals(Double.compare(-1.2d, Double.NEGATIVE_INFINITY), +1); - - assertEquals(Double.compare(-Double.MAX_VALUE, Double.NaN), -1); - assertEquals(Double.compare(-Double.MAX_VALUE, Double.POSITIVE_INFINITY), -1); - assertEquals(Double.compare(-Double.MAX_VALUE, Double.MAX_VALUE), -1); - assertEquals(Double.compare(-Double.MAX_VALUE, 1.2d), -1); - assertEquals(Double.compare(-Double.MAX_VALUE, 0.0d), -1); - assertEquals(Double.compare(-Double.MAX_VALUE, -0.0d), -1); - assertEquals(Double.compare(-Double.MAX_VALUE, -1.2d), -1); - assertEquals(0, Double.compare(-Double.MAX_VALUE, -Double.MAX_VALUE)); - assertEquals(Double.compare(-Double.MAX_VALUE, Double.NEGATIVE_INFINITY), +1); - - assertEquals(Double.compare(Double.NEGATIVE_INFINITY, Double.NaN), -1); - assertEquals(Double.compare(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY), -1); - assertEquals(Double.compare(Double.NEGATIVE_INFINITY, Double.MAX_VALUE), -1); - assertEquals(Double.compare(Double.NEGATIVE_INFINITY, 1.2d), -1); - assertEquals(Double.compare(Double.NEGATIVE_INFINITY, 0.0d), -1); - assertEquals(Double.compare(Double.NEGATIVE_INFINITY, -0.0d), -1); - assertEquals(Double.compare(Double.NEGATIVE_INFINITY, -1.2d), -1); - assertEquals(Double.compare(Double.NEGATIVE_INFINITY, -Double.MAX_VALUE), -1); - assertEquals(0, Double.compare(Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY)); - } - - @Test - public void testCompareFloat() { - assertEquals(0, Float.compare(Float.NaN, Float.NaN)); - assertEquals(Float.compare(Float.NaN, Float.POSITIVE_INFINITY), +1); - assertEquals(Float.compare(Float.NaN, Float.MAX_VALUE), +1); - assertEquals(Float.compare(Float.NaN, 1.2f), +1); - assertEquals(Float.compare(Float.NaN, 0.0f), +1); - assertEquals(Float.compare(Float.NaN, -0.0f), +1); - assertEquals(Float.compare(Float.NaN, -1.2f), +1); - assertEquals(Float.compare(Float.NaN, -Float.MAX_VALUE), +1); - assertEquals(Float.compare(Float.NaN, Float.NEGATIVE_INFINITY), +1); - - assertEquals(Float.compare(Float.POSITIVE_INFINITY, Float.NaN), -1); - assertEquals(0, Float.compare(Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY)); - assertEquals(Float.compare(Float.POSITIVE_INFINITY, Float.MAX_VALUE), +1); - assertEquals(Float.compare(Float.POSITIVE_INFINITY, 1.2f), +1); - assertEquals(Float.compare(Float.POSITIVE_INFINITY, 0.0f), +1); - assertEquals(Float.compare(Float.POSITIVE_INFINITY, -0.0f), +1); - assertEquals(Float.compare(Float.POSITIVE_INFINITY, -1.2f), +1); - assertEquals(Float.compare(Float.POSITIVE_INFINITY, -Float.MAX_VALUE), +1); - assertEquals(Float.compare(Float.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY), +1); - - assertEquals(Float.compare(Float.MAX_VALUE, Float.NaN), -1); - assertEquals(Float.compare(Float.MAX_VALUE, Float.POSITIVE_INFINITY), -1); - assertEquals(0, Float.compare(Float.MAX_VALUE, Float.MAX_VALUE)); - assertEquals(Float.compare(Float.MAX_VALUE, 1.2f), +1); - assertEquals(Float.compare(Float.MAX_VALUE, 0.0f), +1); - assertEquals(Float.compare(Float.MAX_VALUE, -0.0f), +1); - assertEquals(Float.compare(Float.MAX_VALUE, -1.2f), +1); - assertEquals(Float.compare(Float.MAX_VALUE, -Float.MAX_VALUE), +1); - assertEquals(Float.compare(Float.MAX_VALUE, Float.NEGATIVE_INFINITY), +1); - - assertEquals(Float.compare(1.2f, Float.NaN), -1); - assertEquals(Float.compare(1.2f, Float.POSITIVE_INFINITY), -1); - assertEquals(Float.compare(1.2f, Float.MAX_VALUE), -1); - assertEquals(0, Float.compare(1.2f, 1.2f)); - assertEquals(Float.compare(1.2f, 0.0f), +1); - assertEquals(Float.compare(1.2f, -0.0f), +1); - assertEquals(Float.compare(1.2f, -1.2f), +1); - assertEquals(Float.compare(1.2f, -Float.MAX_VALUE), +1); - assertEquals(Float.compare(1.2f, Float.NEGATIVE_INFINITY), +1); - - assertEquals(Float.compare(0.0f, Float.NaN), -1); - assertEquals(Float.compare(0.0f, Float.POSITIVE_INFINITY), -1); - assertEquals(Float.compare(0.0f, Float.MAX_VALUE), -1); - assertEquals(Float.compare(0.0f, 1.2f), -1); - assertEquals(0, Float.compare(0.0f, 0.0f)); - assertEquals(Float.compare(0.0f, -0.0f), +1); - assertEquals(Float.compare(0.0f, -1.2f), +1); - assertEquals(Float.compare(0.0f, -Float.MAX_VALUE), +1); - assertEquals(Float.compare(0.0f, Float.NEGATIVE_INFINITY), +1); - - assertEquals(Float.compare(-0.0f, Float.NaN), -1); - assertEquals(Float.compare(-0.0f, Float.POSITIVE_INFINITY), -1); - assertEquals(Float.compare(-0.0f, Float.MAX_VALUE), -1); - assertEquals(Float.compare(-0.0f, 1.2f), -1); - assertEquals(Float.compare(-0.0f, 0.0f), -1); - assertEquals(0, Float.compare(-0.0f, -0.0f)); - assertEquals(Float.compare(-0.0f, -1.2f), +1); - assertEquals(Float.compare(-0.0f, -Float.MAX_VALUE), +1); - assertEquals(Float.compare(-0.0f, Float.NEGATIVE_INFINITY), +1); + public void testMinimumInt() { + assertEquals(12345, NumberUtils.min(12345, 12345 + 1, 12345 + 2), "minimum(int, int, int) 1 failed"); + assertEquals(12345, NumberUtils.min(12345 + 1, 12345, 12345 + 2), "minimum(int, int, int) 2 failed"); + assertEquals(12345, NumberUtils.min(12345 + 1, 12345 + 2, 12345), "minimum(int, int, int) 3 failed"); + assertEquals(12345, NumberUtils.min(12345 + 1, 12345, 12345), "minimum(int, int, int) 4 failed"); + assertEquals(12345, NumberUtils.min(12345, 12345, 12345), "minimum(int, int, int) 5 failed"); + } - assertEquals(Float.compare(-1.2f, Float.NaN), -1); - assertEquals(Float.compare(-1.2f, Float.POSITIVE_INFINITY), -1); - assertEquals(Float.compare(-1.2f, Float.MAX_VALUE), -1); - assertEquals(Float.compare(-1.2f, 1.2f), -1); - assertEquals(Float.compare(-1.2f, 0.0f), -1); - assertEquals(Float.compare(-1.2f, -0.0f), -1); - assertEquals(0, Float.compare(-1.2f, -1.2f)); - assertEquals(Float.compare(-1.2f, -Float.MAX_VALUE), +1); - assertEquals(Float.compare(-1.2f, Float.NEGATIVE_INFINITY), +1); + @Test + public void testMinimumLong() { + assertEquals(12345L, NumberUtils.min(12345L, 12345L + 1L, 12345L + 2L), "minimum(long, long, long) 1 failed"); + assertEquals(12345L, NumberUtils.min(12345L + 1L, 12345L, 12345 + 2L), "minimum(long, long, long) 2 failed"); + assertEquals(12345L, NumberUtils.min(12345L + 1L, 12345L + 2L, 12345L), "minimum(long, long, long) 3 failed"); + assertEquals(12345L, NumberUtils.min(12345L + 1L, 12345L, 12345L), "minimum(long, long, long) 4 failed"); + assertEquals(12345L, NumberUtils.min(12345L, 12345L, 12345L), "minimum(long, long, long) 5 failed"); + } - assertEquals(Float.compare(-Float.MAX_VALUE, Float.NaN), -1); - assertEquals(Float.compare(-Float.MAX_VALUE, Float.POSITIVE_INFINITY), -1); - assertEquals(Float.compare(-Float.MAX_VALUE, Float.MAX_VALUE), -1); - assertEquals(Float.compare(-Float.MAX_VALUE, 1.2f), -1); - assertEquals(Float.compare(-Float.MAX_VALUE, 0.0f), -1); - assertEquals(Float.compare(-Float.MAX_VALUE, -0.0f), -1); - assertEquals(Float.compare(-Float.MAX_VALUE, -1.2f), -1); - assertEquals(0, Float.compare(-Float.MAX_VALUE, -Float.MAX_VALUE)); - assertEquals(Float.compare(-Float.MAX_VALUE, Float.NEGATIVE_INFINITY), +1); + @Test + public void testMinimumShort() { + final short low = 1234; + final short mid = 1234 + 1; + final short high = 1234 + 2; + assertEquals(low, NumberUtils.min(low, mid, high), "minimum(short, short, short) 1 failed"); + assertEquals(low, NumberUtils.min(mid, low, high), "minimum(short, short, short) 2 failed"); + assertEquals(low, NumberUtils.min(mid, high, low), "minimum(short, short, short) 3 failed"); + assertEquals(low, NumberUtils.min(low, mid, low), "minimum(short, short, short) 4 failed"); + } - assertEquals(Float.compare(Float.NEGATIVE_INFINITY, Float.NaN), -1); - assertEquals(Float.compare(Float.NEGATIVE_INFINITY, Float.POSITIVE_INFINITY), -1); - assertEquals(Float.compare(Float.NEGATIVE_INFINITY, Float.MAX_VALUE), -1); - assertEquals(Float.compare(Float.NEGATIVE_INFINITY, 1.2f), -1); - assertEquals(Float.compare(Float.NEGATIVE_INFINITY, 0.0f), -1); - assertEquals(Float.compare(Float.NEGATIVE_INFINITY, -0.0f), -1); - assertEquals(Float.compare(Float.NEGATIVE_INFINITY, -1.2f), -1); - assertEquals(Float.compare(Float.NEGATIVE_INFINITY, -Float.MAX_VALUE), -1); - assertEquals(0, Float.compare(Float.NEGATIVE_INFINITY, Float.NEGATIVE_INFINITY)); + @Test + public void testMinInt() { + assertEquals(5, NumberUtils.min(5), "min(int[]) failed for array length 1"); + assertEquals(6, NumberUtils.min(6, 9), "min(int[]) failed for array length 2"); + + assertEquals(-10, NumberUtils.min(-10, -5, 0, 5, 10)); + assertEquals(-10, NumberUtils.min(-5, 0, -10, 5, 10)); } @Test - public void testIsDigits() { - assertFalse(NumberUtils.isDigits(null), "isDigits(null) failed"); - assertFalse(NumberUtils.isDigits(""), "isDigits('') failed"); - assertTrue(NumberUtils.isDigits("12345"), "isDigits(String) failed"); - assertFalse(NumberUtils.isDigits("1234.5"), "isDigits(String) neg 1 failed"); - assertFalse(NumberUtils.isDigits("1ab"), "isDigits(String) neg 3 failed"); - assertFalse(NumberUtils.isDigits("abc"), "isDigits(String) neg 4 failed"); + public void testMinInt_emptyArray() { + assertThrows(IllegalArgumentException.class, NumberUtils::min); } - /** - * Tests isCreatable(String) and tests that createNumber(String) returns - * a valid number iff isCreatable(String) returns false. - */ @Test - public void testIsCreatable() { - compareIsCreatableWithCreateNumber("12345", true); - compareIsCreatableWithCreateNumber("1234.5", true); - compareIsCreatableWithCreateNumber(".12345", true); - compareIsCreatableWithCreateNumber("1234E5", true); - compareIsCreatableWithCreateNumber("1234E+5", true); - compareIsCreatableWithCreateNumber("1234E-5", true); - compareIsCreatableWithCreateNumber("123.4E5", true); - compareIsCreatableWithCreateNumber("-1234", true); - compareIsCreatableWithCreateNumber("-1234.5", true); - compareIsCreatableWithCreateNumber("-.12345", true); - compareIsCreatableWithCreateNumber("-1234E5", true); - compareIsCreatableWithCreateNumber("0", true); - compareIsCreatableWithCreateNumber("0.1", true); // LANG-1216 - compareIsCreatableWithCreateNumber("-0", true); - compareIsCreatableWithCreateNumber("01234", true); - compareIsCreatableWithCreateNumber("-01234", true); - compareIsCreatableWithCreateNumber("-0xABC123", true); - compareIsCreatableWithCreateNumber("-0x0", true); - compareIsCreatableWithCreateNumber("123.4E21D", true); - compareIsCreatableWithCreateNumber("-221.23F", true); - compareIsCreatableWithCreateNumber("22338L", true); + public void testMinInt_nullArray() { + assertThrows(NullPointerException.class, () -> NumberUtils.min((int[]) null)); + } - compareIsCreatableWithCreateNumber(null, false); - compareIsCreatableWithCreateNumber("", false); - compareIsCreatableWithCreateNumber(" ", false); - compareIsCreatableWithCreateNumber("\r\n\t", false); - compareIsCreatableWithCreateNumber("--2.3", false); - compareIsCreatableWithCreateNumber(".12.3", false); - compareIsCreatableWithCreateNumber("-123E", false); - compareIsCreatableWithCreateNumber("-123E+-212", false); - compareIsCreatableWithCreateNumber("-123E2.12", false); - compareIsCreatableWithCreateNumber("0xGF", false); - compareIsCreatableWithCreateNumber("0xFAE-1", false); - compareIsCreatableWithCreateNumber(".", false); - compareIsCreatableWithCreateNumber("-0ABC123", false); - compareIsCreatableWithCreateNumber("123.4E-D", false); - compareIsCreatableWithCreateNumber("123.4ED", false); - compareIsCreatableWithCreateNumber("1234E5l", false); - compareIsCreatableWithCreateNumber("11a", false); - compareIsCreatableWithCreateNumber("1a", false); - compareIsCreatableWithCreateNumber("a", false); - compareIsCreatableWithCreateNumber("11g", false); - compareIsCreatableWithCreateNumber("11z", false); - compareIsCreatableWithCreateNumber("11def", false); - compareIsCreatableWithCreateNumber("11d11", false); - compareIsCreatableWithCreateNumber("11 11", false); - compareIsCreatableWithCreateNumber(" 1111", false); - compareIsCreatableWithCreateNumber("1111 ", false); + @Test + public void testMinLong() { + assertEquals(5L, NumberUtils.min(5L), "min(long[]) failed for array length 1"); + assertEquals(6L, NumberUtils.min(6L, 9L), "min(long[]) failed for array length 2"); - compareIsCreatableWithCreateNumber("2.", true); // LANG-521 - compareIsCreatableWithCreateNumber("1.1L", false); // LANG-664 + assertEquals(-10L, NumberUtils.min(-10L, -5L, 0L, 5L, 10L)); + assertEquals(-10L, NumberUtils.min(-5L, 0L, -10L, 5L, 10L)); } @Test - public void testLANG971() { - compareIsCreatableWithCreateNumber("0085", false); - compareIsCreatableWithCreateNumber("085", false); - compareIsCreatableWithCreateNumber("08", false); - compareIsCreatableWithCreateNumber("07", true); - compareIsCreatableWithCreateNumber("00", true); + public void testMinLong_emptyArray() { + assertThrows(IllegalArgumentException.class, NumberUtils::min); } + // min/max tests + // ---------------------------------------------------------------------- @Test - public void testLANG992() { - compareIsCreatableWithCreateNumber("0.0", true); - compareIsCreatableWithCreateNumber("0.4790", true); + public void testMinLong_nullArray() { + assertThrows(NullPointerException.class, () -> NumberUtils.min((long[]) null)); } @Test - public void testLANG972() { - compareIsCreatableWithCreateNumber("0xABCD", true); - compareIsCreatableWithCreateNumber("0XABCD", true); + public void testMinShort() { + assertEquals((short) 5, NumberUtils.min((short) 5), "min(short[]) failed for array length 1"); + assertEquals((short) 6, NumberUtils.min((short) 6, (short) 9), "min(short[]) failed for array length 2"); + + assertEquals((short) -10, NumberUtils.min((short) -10, (short) -5, (short) 0, (short) 5, (short) 10)); + assertEquals((short) -10, NumberUtils.min((short) -5, (short) 0, (short) -10, (short) 5, (short) 10)); } @Test - public void testLANG1252() { - compareIsCreatableWithCreateNumber("+2", true); - compareIsCreatableWithCreateNumber("+2.0", true); + public void testMinShort_emptyArray() { + assertThrows(IllegalArgumentException.class, NumberUtils::min); } - private void compareIsCreatableWithCreateNumber(final String val, final boolean expected) { - final boolean isValid = NumberUtils.isCreatable(val); - final boolean canCreate = checkCreateNumber(val); - assertTrue( - isValid == expected && canCreate == expected, - "Expecting " + expected + " for isCreatable/createNumber using \"" + val + "\" but got " + isValid + " and " + canCreate); + @Test + public void testMinShort_nullArray() { + assertThrows(NullPointerException.class, () -> NumberUtils.min((short[]) null)); } /** - * Tests isCreatable(String) and tests that createNumber(String) returns - * a valid number iff isCreatable(String) returns false. + * Test for {(@link NumberUtils#createNumber(String)} */ @Test - public void testIsNumber() { - compareIsNumberWithCreateNumber("12345", true); - compareIsNumberWithCreateNumber("1234.5", true); - compareIsNumberWithCreateNumber(".12345", true); - compareIsNumberWithCreateNumber("1234E5", true); - compareIsNumberWithCreateNumber("1234E+5", true); - compareIsNumberWithCreateNumber("1234E-5", true); - compareIsNumberWithCreateNumber("123.4E5", true); - compareIsNumberWithCreateNumber("-1234", true); - compareIsNumberWithCreateNumber("-1234.5", true); - compareIsNumberWithCreateNumber("-.12345", true); - compareIsNumberWithCreateNumber("-0001.12345", true); - compareIsNumberWithCreateNumber("-000.12345", true); - compareIsNumberWithCreateNumber("+00.12345", true); - compareIsNumberWithCreateNumber("+0002.12345", true); - compareIsNumberWithCreateNumber("-1234E5", true); - compareIsNumberWithCreateNumber("0", true); - compareIsNumberWithCreateNumber("-0", true); - compareIsNumberWithCreateNumber("01234", true); - compareIsNumberWithCreateNumber("-01234", true); - compareIsNumberWithCreateNumber("-0xABC123", true); - compareIsNumberWithCreateNumber("-0x0", true); - compareIsNumberWithCreateNumber("123.4E21D", true); - compareIsNumberWithCreateNumber("-221.23F", true); - compareIsNumberWithCreateNumber("22338L", true); + public void testStringCreateNumberEnsureNoPrecisionLoss() { + final String shouldBeFloat = "1.23"; + final String shouldBeDouble = "3.40282354e+38"; + final String shouldBeBigDecimal = "1.797693134862315759e+308"; + assertTrue(NumberUtils.createNumber(shouldBeFloat) instanceof Float); + assertTrue(NumberUtils.createNumber(shouldBeDouble) instanceof Double); + assertTrue(NumberUtils.createNumber(shouldBeBigDecimal) instanceof BigDecimal); + // LANG-1060 + assertTrue(NumberUtils.createNumber("001.12") instanceof Float); + assertTrue(NumberUtils.createNumber("-001.12") instanceof Float); + assertTrue(NumberUtils.createNumber("+001.12") instanceof Float); + assertTrue(NumberUtils.createNumber("003.40282354e+38") instanceof Double); + assertTrue(NumberUtils.createNumber("-003.40282354e+38") instanceof Double); + assertTrue(NumberUtils.createNumber("+003.40282354e+38") instanceof Double); + assertTrue(NumberUtils.createNumber("0001.797693134862315759e+308") instanceof BigDecimal); + assertTrue(NumberUtils.createNumber("-001.797693134862315759e+308") instanceof BigDecimal); + assertTrue(NumberUtils.createNumber("+001.797693134862315759e+308") instanceof BigDecimal); + } - compareIsNumberWithCreateNumber(null, false); - compareIsNumberWithCreateNumber("", false); - compareIsNumberWithCreateNumber(" ", false); - compareIsNumberWithCreateNumber("\r\n\t", false); - compareIsNumberWithCreateNumber("--2.3", false); + /** + * Test for {@link NumberUtils#toDouble(String)}. + */ + @Test + public void testStringToDoubleString() { + assertEquals(NumberUtils.toDouble("-1.2345"), -1.2345d, "toDouble(String) 1 failed"); + assertEquals(1.2345d, NumberUtils.toDouble("1.2345"), "toDouble(String) 2 failed"); + assertEquals(0.0d, NumberUtils.toDouble("abc"), "toDouble(String) 3 failed"); + // LANG-1060 + assertEquals(NumberUtils.toDouble("-001.2345"), -1.2345d, "toDouble(String) 4 failed"); + assertEquals(1.2345d, NumberUtils.toDouble("+001.2345"), "toDouble(String) 5 failed"); + assertEquals(1.2345d, NumberUtils.toDouble("001.2345"), "toDouble(String) 6 failed"); + assertEquals(0d, NumberUtils.toDouble("000.00000"), "toDouble(String) 7 failed"); - compareIsNumberWithCreateNumber(".12.3", false); - compareIsNumberWithCreateNumber("-123E", false); - compareIsNumberWithCreateNumber("-123E+-212", false); - compareIsNumberWithCreateNumber("-123E2.12", false); - compareIsNumberWithCreateNumber("0xGF", false); - compareIsNumberWithCreateNumber("0xFAE-1", false); - compareIsNumberWithCreateNumber(".", false); - compareIsNumberWithCreateNumber("-0ABC123", false); - compareIsNumberWithCreateNumber("123.4E-D", false); - compareIsNumberWithCreateNumber("123.4ED", false); - compareIsNumberWithCreateNumber("+000E.12345", false); - compareIsNumberWithCreateNumber("-000E.12345", false); - compareIsNumberWithCreateNumber("1234E5l", false); - compareIsNumberWithCreateNumber("11a", false); - compareIsNumberWithCreateNumber("1a", false); - compareIsNumberWithCreateNumber("a", false); - compareIsNumberWithCreateNumber("11g", false); - compareIsNumberWithCreateNumber("11z", false); - compareIsNumberWithCreateNumber("11def", false); - compareIsNumberWithCreateNumber("11d11", false); - compareIsNumberWithCreateNumber("11 11", false); - compareIsNumberWithCreateNumber(" 1111", false); - compareIsNumberWithCreateNumber("1111 ", false); + assertEquals(NumberUtils.toDouble(Double.MAX_VALUE + ""), Double.MAX_VALUE, + "toDouble(Double.MAX_VALUE) failed"); + assertEquals(NumberUtils.toDouble(Double.MIN_VALUE + ""), Double.MIN_VALUE, + "toDouble(Double.MIN_VALUE) failed"); + assertEquals(0.0d, NumberUtils.toDouble(""), "toDouble(empty) failed"); + assertEquals(0.0d, NumberUtils.toDouble((String) null), "toDouble(null) failed"); + } - compareIsNumberWithCreateNumber("2.", true); // LANG-521 - compareIsNumberWithCreateNumber("1.1L", false); // LANG-664 + /** + * Test for {@link NumberUtils#toDouble(String, double)}. + */ + @Test + public void testStringToDoubleStringD() { + assertEquals(1.2345d, NumberUtils.toDouble("1.2345", 5.1d), "toDouble(String, int) 1 failed"); + assertEquals(5.0d, NumberUtils.toDouble("a", 5.0d), "toDouble(String, int) 2 failed"); + // LANG-1060 + assertEquals(1.2345d, NumberUtils.toDouble("001.2345", 5.1d), "toDouble(String, int) 3 failed"); + assertEquals(NumberUtils.toDouble("-001.2345", 5.1d), -1.2345d, "toDouble(String, int) 4 failed"); + assertEquals(1.2345d, NumberUtils.toDouble("+001.2345", 5.1d), "toDouble(String, int) 5 failed"); + assertEquals(0d, NumberUtils.toDouble("000.00", 5.1d), "toDouble(String, int) 7 failed"); } + /** + * Test for {@link NumberUtils#toByte(String)}. + */ @Test - public void testIsNumberLANG971() { - compareIsNumberWithCreateNumber("0085", false); - compareIsNumberWithCreateNumber("085", false); - compareIsNumberWithCreateNumber("08", false); - compareIsNumberWithCreateNumber("07", true); - compareIsNumberWithCreateNumber("00", true); + public void testToByteString() { + assertEquals(123, NumberUtils.toByte("123"), "toByte(String) 1 failed"); + assertEquals(0, NumberUtils.toByte("abc"), "toByte(String) 2 failed"); + assertEquals(0, NumberUtils.toByte(""), "toByte(empty) failed"); + assertEquals(0, NumberUtils.toByte(null), "toByte(null) failed"); } + /** + * Test for {@link NumberUtils#toByte(String, byte)}. + */ @Test - public void testIsNumberLANG992() { - compareIsNumberWithCreateNumber("0.0", true); - compareIsNumberWithCreateNumber("0.4790", true); + public void testToByteStringI() { + assertEquals(123, NumberUtils.toByte("123", (byte) 5), "toByte(String, byte) 1 failed"); + assertEquals(5, NumberUtils.toByte("12.3", (byte) 5), "toByte(String, byte) 2 failed"); } + /** + * Test for {@link NumberUtils#toFloat(String)}. + */ @Test - public void testIsNumberLANG972() { - compareIsNumberWithCreateNumber("0xABCD", true); - compareIsNumberWithCreateNumber("0XABCD", true); + public void testToFloatString() { + assertEquals(NumberUtils.toFloat("-1.2345"), -1.2345f, "toFloat(String) 1 failed"); + assertEquals(1.2345f, NumberUtils.toFloat("1.2345"), "toFloat(String) 2 failed"); + assertEquals(0.0f, NumberUtils.toFloat("abc"), "toFloat(String) 3 failed"); + // LANG-1060 + assertEquals(NumberUtils.toFloat("-001.2345"), -1.2345f, "toFloat(String) 4 failed"); + assertEquals(1.2345f, NumberUtils.toFloat("+001.2345"), "toFloat(String) 5 failed"); + assertEquals(1.2345f, NumberUtils.toFloat("001.2345"), "toFloat(String) 6 failed"); + assertEquals(0f, NumberUtils.toFloat("000.00"), "toFloat(String) 7 failed"); + + assertEquals(NumberUtils.toFloat(Float.MAX_VALUE + ""), Float.MAX_VALUE, "toFloat(Float.MAX_VALUE) failed"); + assertEquals(NumberUtils.toFloat(Float.MIN_VALUE + ""), Float.MIN_VALUE, "toFloat(Float.MIN_VALUE) failed"); + assertEquals(0.0f, NumberUtils.toFloat(""), "toFloat(empty) failed"); + assertEquals(0.0f, NumberUtils.toFloat(null), "toFloat(null) failed"); } + /** + * Test for {@link NumberUtils#toFloat(String, float)}. + */ @Test - public void testIsNumberLANG1252() { - compareIsNumberWithCreateNumber("+2", true); - compareIsNumberWithCreateNumber("+2.0", true); + public void testToFloatStringF() { + assertEquals(1.2345f, NumberUtils.toFloat("1.2345", 5.1f), "toFloat(String, int) 1 failed"); + assertEquals(5.0f, NumberUtils.toFloat("a", 5.0f), "toFloat(String, int) 2 failed"); + // LANG-1060 + assertEquals(5.0f, NumberUtils.toFloat("-001Z.2345", 5.0f), "toFloat(String, int) 3 failed"); + assertEquals(5.0f, NumberUtils.toFloat("+001AB.2345", 5.0f), "toFloat(String, int) 4 failed"); + assertEquals(5.0f, NumberUtils.toFloat("001Z.2345", 5.0f), "toFloat(String, int) 5 failed"); } + /** + * Test for {@link NumberUtils#toInt(String)}. + */ @Test - public void testIsNumberLANG1385() { - compareIsNumberWithCreateNumber("L", false); + public void testToIntString() { + assertEquals(12345, NumberUtils.toInt("12345"), "toInt(String) 1 failed"); + assertEquals(0, NumberUtils.toInt("abc"), "toInt(String) 2 failed"); + assertEquals(0, NumberUtils.toInt(""), "toInt(empty) failed"); + assertEquals(0, NumberUtils.toInt(null), "toInt(null) failed"); } - private void compareIsNumberWithCreateNumber(final String val, final boolean expected) { - final boolean isValid = NumberUtils.isCreatable(val); - final boolean canCreate = checkCreateNumber(val); - assertTrue( - isValid == expected && canCreate == expected, - "Expecting "+ expected + " for isCreatable/createNumber using \"" + val + "\" but got " + isValid + " and " + canCreate); + /** + * Test for {@link NumberUtils#toInt(String, int)}. + */ + @Test + public void testToIntStringI() { + assertEquals(12345, NumberUtils.toInt("12345", 5), "toInt(String, int) 1 failed"); + assertEquals(5, NumberUtils.toInt("1234.5", 5), "toInt(String, int) 2 failed"); } + /** + * Test for {@link NumberUtils#toLong(String)}. + */ @Test - public void testIsParsable() { - assertFalse(NumberUtils.isParsable(null)); - assertFalse(NumberUtils.isParsable("")); - assertFalse(NumberUtils.isParsable("0xC1AB")); - assertFalse(NumberUtils.isParsable("65CBA2")); - assertFalse(NumberUtils.isParsable("pendro")); - assertFalse(NumberUtils.isParsable("64, 2")); - assertFalse(NumberUtils.isParsable("64.2.2")); - assertFalse(NumberUtils.isParsable("64.")); - assertFalse(NumberUtils.isParsable("64L")); - assertFalse(NumberUtils.isParsable("-")); - assertFalse(NumberUtils.isParsable("--2")); - assertTrue(NumberUtils.isParsable("64.2")); - assertTrue(NumberUtils.isParsable("64")); - assertTrue(NumberUtils.isParsable("018")); - assertTrue(NumberUtils.isParsable(".18")); - assertTrue(NumberUtils.isParsable("-65")); - assertTrue(NumberUtils.isParsable("-018")); - assertTrue(NumberUtils.isParsable("-018.2")); - assertTrue(NumberUtils.isParsable("-.236")); + public void testToLongString() { + assertEquals(12345L, NumberUtils.toLong("12345"), "toLong(String) 1 failed"); + assertEquals(0L, NumberUtils.toLong("abc"), "toLong(String) 2 failed"); + assertEquals(0L, NumberUtils.toLong("1L"), "toLong(String) 3 failed"); + assertEquals(0L, NumberUtils.toLong("1l"), "toLong(String) 4 failed"); + assertEquals(NumberUtils.toLong(Long.MAX_VALUE + ""), Long.MAX_VALUE, "toLong(Long.MAX_VALUE) failed"); + assertEquals(NumberUtils.toLong(Long.MIN_VALUE + ""), Long.MIN_VALUE, "toLong(Long.MIN_VALUE) failed"); + assertEquals(0L, NumberUtils.toLong(""), "toLong(empty) failed"); + assertEquals(0L, NumberUtils.toLong(null), "toLong(null) failed"); } - private boolean checkCreateNumber(final String val) { - try { - final Object obj = NumberUtils.createNumber(val); - return obj != null; - } catch (final NumberFormatException e) { - return false; - } + /** + * Test for {@link NumberUtils#toLong(String, long)}. + */ + @Test + public void testToLongStringL() { + assertEquals(12345L, NumberUtils.toLong("12345", 5L), "toLong(String, long) 1 failed"); + assertEquals(5L, NumberUtils.toLong("1234.5", 5L), "toLong(String, long) 2 failed"); } - @SuppressWarnings("cast") // suppress instanceof warning check + /** + * Test for {@link NumberUtils#toScaledBigDecimal(BigDecimal)}. + */ @Test - public void testConstants() { - assertTrue(NumberUtils.LONG_ZERO instanceof Long); - assertTrue(NumberUtils.LONG_ONE instanceof Long); - assertTrue(NumberUtils.LONG_MINUS_ONE instanceof Long); - assertTrue(NumberUtils.INTEGER_ZERO instanceof Integer); - assertTrue(NumberUtils.INTEGER_ONE instanceof Integer); - assertTrue(NumberUtils.INTEGER_MINUS_ONE instanceof Integer); - assertTrue(NumberUtils.SHORT_ZERO instanceof Short); - assertTrue(NumberUtils.SHORT_ONE instanceof Short); - assertTrue(NumberUtils.SHORT_MINUS_ONE instanceof Short); - assertTrue(NumberUtils.BYTE_ZERO instanceof Byte); - assertTrue(NumberUtils.BYTE_ONE instanceof Byte); - assertTrue(NumberUtils.BYTE_MINUS_ONE instanceof Byte); - assertTrue(NumberUtils.DOUBLE_ZERO instanceof Double); - assertTrue(NumberUtils.DOUBLE_ONE instanceof Double); - assertTrue(NumberUtils.DOUBLE_MINUS_ONE instanceof Double); - assertTrue(NumberUtils.FLOAT_ZERO instanceof Float); - assertTrue(NumberUtils.FLOAT_ONE instanceof Float); - assertTrue(NumberUtils.FLOAT_MINUS_ONE instanceof Float); - - assertEquals(0, NumberUtils.LONG_ZERO.longValue()); - assertEquals(1, NumberUtils.LONG_ONE.longValue()); - assertEquals(NumberUtils.LONG_MINUS_ONE.longValue(), -1); - assertEquals(0, NumberUtils.INTEGER_ZERO.intValue()); - assertEquals(1, NumberUtils.INTEGER_ONE.intValue()); - assertEquals(NumberUtils.INTEGER_MINUS_ONE.intValue(), -1); - assertEquals(0, NumberUtils.SHORT_ZERO.shortValue()); - assertEquals(1, NumberUtils.SHORT_ONE.shortValue()); - assertEquals(NumberUtils.SHORT_MINUS_ONE.shortValue(), -1); - assertEquals(0, NumberUtils.BYTE_ZERO.byteValue()); - assertEquals(1, NumberUtils.BYTE_ONE.byteValue()); - assertEquals(NumberUtils.BYTE_MINUS_ONE.byteValue(), -1); - assertEquals(0.0d, NumberUtils.DOUBLE_ZERO.doubleValue()); - assertEquals(1.0d, NumberUtils.DOUBLE_ONE.doubleValue()); - assertEquals(NumberUtils.DOUBLE_MINUS_ONE.doubleValue(), -1.0d); - assertEquals(0.0f, NumberUtils.FLOAT_ZERO.floatValue()); - assertEquals(1.0f, NumberUtils.FLOAT_ONE.floatValue()); - assertEquals(NumberUtils.FLOAT_MINUS_ONE.floatValue(), -1.0f); + public void testToScaledBigDecimalBigDecimal() { + assertEquals(NumberUtils.toScaledBigDecimal(BigDecimal.valueOf(123.456)), BigDecimal.valueOf(123.46), + "toScaledBigDecimal(BigDecimal) 1 failed"); + // Test RoudingMode.HALF_EVEN default rounding. + assertEquals(NumberUtils.toScaledBigDecimal(BigDecimal.valueOf(23.515)), BigDecimal.valueOf(23.52), + "toScaledBigDecimal(BigDecimal) 2 failed"); + assertEquals(NumberUtils.toScaledBigDecimal(BigDecimal.valueOf(23.525)), BigDecimal.valueOf(23.52), + "toScaledBigDecimal(BigDecimal) 3 failed"); + assertEquals("2352.00", + NumberUtils.toScaledBigDecimal(BigDecimal.valueOf(23.525)).multiply(BigDecimal.valueOf(100)).toString(), + "toScaledBigDecimal(BigDecimal) 4 failed"); + assertEquals(NumberUtils.toScaledBigDecimal((BigDecimal) null), BigDecimal.ZERO, + "toScaledBigDecimal(BigDecimal) 5 failed"); } + /** + * Test for {@link NumberUtils#toScaledBigDecimal(BigDecimal, int, RoundingMode)}. + */ @Test - public void testLang300() { - NumberUtils.createNumber("-1l"); - NumberUtils.createNumber("01l"); - NumberUtils.createNumber("1l"); + public void testToScaledBigDecimalBigDecimalIRM() { + assertEquals(NumberUtils.toScaledBigDecimal(BigDecimal.valueOf(123.456), 1, RoundingMode.CEILING), + BigDecimal.valueOf(123.5), "toScaledBigDecimal(BigDecimal, int, RoudingMode) 1 failed"); + assertEquals(NumberUtils.toScaledBigDecimal(BigDecimal.valueOf(23.5159), 3, RoundingMode.FLOOR), + BigDecimal.valueOf(23.515), "toScaledBigDecimal(BigDecimal, int, RoudingMode) 2 failed"); + assertEquals(NumberUtils.toScaledBigDecimal(BigDecimal.valueOf(23.525), 2, RoundingMode.HALF_UP), + BigDecimal.valueOf(23.53), "toScaledBigDecimal(BigDecimal, int, RoudingMode) 3 failed"); + assertEquals("23521.0000", + NumberUtils.toScaledBigDecimal(BigDecimal.valueOf(23.521), 4, RoundingMode.HALF_EVEN) + .multiply(BigDecimal.valueOf(1000)).toString(), + "toScaledBigDecimal(BigDecimal, int, RoudingMode) 4 failed"); + assertEquals(NumberUtils.toScaledBigDecimal((BigDecimal) null, 2, RoundingMode.HALF_UP), BigDecimal.ZERO, + "toScaledBigDecimal(BigDecimal, int, RoudingMode) 5 failed"); } + /** + * Test for {@link NumberUtils#toScaledBigDecimal(Double)}. + */ @Test - public void testLang381() { - assertTrue(Double.isNaN(NumberUtils.min(1.2, 2.5, Double.NaN))); - assertTrue(Double.isNaN(NumberUtils.max(1.2, 2.5, Double.NaN))); - assertTrue(Float.isNaN(NumberUtils.min(1.2f, 2.5f, Float.NaN))); - assertTrue(Float.isNaN(NumberUtils.max(1.2f, 2.5f, Float.NaN))); - - final double[] a = new double[] { 1.2, Double.NaN, 3.7, 27.0, 42.0, Double.NaN }; - assertTrue(Double.isNaN(NumberUtils.max(a))); - assertTrue(Double.isNaN(NumberUtils.min(a))); + public void testToScaledBigDecimalDouble() { + assertEquals(NumberUtils.toScaledBigDecimal(Double.valueOf(123.456d)), BigDecimal.valueOf(123.46), + "toScaledBigDecimal(Double) 1 failed"); + // Test RoudingMode.HALF_EVEN default rounding. + assertEquals(NumberUtils.toScaledBigDecimal(Double.valueOf(23.515d)), BigDecimal.valueOf(23.52), + "toScaledBigDecimal(Double) 2 failed"); + assertEquals(NumberUtils.toScaledBigDecimal(Double.valueOf(23.525d)), BigDecimal.valueOf(23.52), + "toScaledBigDecimal(Double) 3 failed"); + assertEquals("2352.00", + NumberUtils.toScaledBigDecimal(Double.valueOf(23.525d)).multiply(BigDecimal.valueOf(100)).toString(), + "toScaledBigDecimal(Double) 4 failed"); + assertEquals(NumberUtils.toScaledBigDecimal((Double) null), BigDecimal.ZERO, + "toScaledBigDecimal(Double) 5 failed"); + } - final double[] b = new double[] { Double.NaN, 1.2, Double.NaN, 3.7, 27.0, 42.0, Double.NaN }; - assertTrue(Double.isNaN(NumberUtils.max(b))); - assertTrue(Double.isNaN(NumberUtils.min(b))); + /** + * Test for {@link NumberUtils#toScaledBigDecimal(Double, int, RoundingMode)}. + */ + @Test + public void testToScaledBigDecimalDoubleIRM() { + assertEquals(NumberUtils.toScaledBigDecimal(Double.valueOf(123.456d), 1, RoundingMode.CEILING), + BigDecimal.valueOf(123.5), "toScaledBigDecimal(Double, int, RoudingMode) 1 failed"); + assertEquals(NumberUtils.toScaledBigDecimal(Double.valueOf(23.5159d), 3, RoundingMode.FLOOR), + BigDecimal.valueOf(23.515), "toScaledBigDecimal(Double, int, RoudingMode) 2 failed"); + assertEquals(NumberUtils.toScaledBigDecimal(Double.valueOf(23.525d), 2, RoundingMode.HALF_UP), + BigDecimal.valueOf(23.53), "toScaledBigDecimal(Double, int, RoudingMode) 3 failed"); + assertEquals("23521.0000", + NumberUtils.toScaledBigDecimal(Double.valueOf(23.521d), 4, RoundingMode.HALF_EVEN) + .multiply(BigDecimal.valueOf(1000)).toString(), + "toScaledBigDecimal(Double, int, RoudingMode) 4 failed"); + assertEquals(NumberUtils.toScaledBigDecimal((Double) null, 2, RoundingMode.HALF_UP), BigDecimal.ZERO, + "toScaledBigDecimal(Double, int, RoudingMode) 5 failed"); + } - final float[] aF = new float[] { 1.2f, Float.NaN, 3.7f, 27.0f, 42.0f, Float.NaN }; - assertTrue(Float.isNaN(NumberUtils.max(aF))); + /** + * Test for {@link NumberUtils#toScaledBigDecimal(Float)}. + */ + @Test + public void testToScaledBigDecimalFloat() { + assertEquals(NumberUtils.toScaledBigDecimal(Float.valueOf(123.456f)), BigDecimal.valueOf(123.46), + "toScaledBigDecimal(Float) 1 failed"); + // Test RoudingMode.HALF_EVEN default rounding. + assertEquals(NumberUtils.toScaledBigDecimal(Float.valueOf(23.515f)), BigDecimal.valueOf(23.51), + "toScaledBigDecimal(Float) 2 failed"); + // Note. NumberUtils.toScaledBigDecimal(Float.valueOf(23.515f)).equals(BigDecimal.valueOf(23.51)) + // because of roundoff error. It is ok. + assertEquals(NumberUtils.toScaledBigDecimal(Float.valueOf(23.525f)), BigDecimal.valueOf(23.52), + "toScaledBigDecimal(Float) 3 failed"); + assertEquals("2352.00", + NumberUtils.toScaledBigDecimal(Float.valueOf(23.525f)).multiply(BigDecimal.valueOf(100)).toString(), + "toScaledBigDecimal(Float) 4 failed"); + assertEquals(NumberUtils.toScaledBigDecimal((Float) null), BigDecimal.ZERO, + "toScaledBigDecimal(Float) 5 failed"); + } - final float[] bF = new float[] { Float.NaN, 1.2f, Float.NaN, 3.7f, 27.0f, 42.0f, Float.NaN }; - assertTrue(Float.isNaN(NumberUtils.max(bF))); + /** + * Test for {@link NumberUtils#toScaledBigDecimal(Float, int, RoundingMode)}. + */ + @Test + public void testToScaledBigDecimalFloatIRM() { + assertEquals(NumberUtils.toScaledBigDecimal(Float.valueOf(123.456f), 1, RoundingMode.CEILING), + BigDecimal.valueOf(123.5), "toScaledBigDecimal(Float, int, RoudingMode) 1 failed"); + assertEquals(NumberUtils.toScaledBigDecimal(Float.valueOf(23.5159f), 3, RoundingMode.FLOOR), + BigDecimal.valueOf(23.515), "toScaledBigDecimal(Float, int, RoudingMode) 2 failed"); + // The following happens due to roundoff error. We're ok with this. + assertEquals(NumberUtils.toScaledBigDecimal(Float.valueOf(23.525f), 2, RoundingMode.HALF_UP), + BigDecimal.valueOf(23.52), "toScaledBigDecimal(Float, int, RoudingMode) 3 failed"); + assertEquals("23521.0000", NumberUtils.toScaledBigDecimal(Float.valueOf(23.521f), 4, RoundingMode.HALF_EVEN) + .multiply(BigDecimal.valueOf(1000)).toString(), "toScaledBigDecimal(Float, int, RoudingMode) 4 failed"); + assertEquals(NumberUtils.toScaledBigDecimal((Float) null, 2, RoundingMode.HALF_UP), BigDecimal.ZERO, + "toScaledBigDecimal(Float, int, RoudingMode) 5 failed"); } + /** + * Test for {@link NumberUtils#toScaledBigDecimal(Double)}. + */ @Test - public void compareInt() { - assertTrue(NumberUtils.compare(-3, 0) < 0); - assertEquals(0, NumberUtils.compare(113, 113)); - assertTrue(NumberUtils.compare(213, 32) > 0); + public void testToScaledBigDecimalString() { + assertEquals(NumberUtils.toScaledBigDecimal("123.456"), BigDecimal.valueOf(123.46), + "toScaledBigDecimal(String) 1 failed"); + // Test RoudingMode.HALF_EVEN default rounding. + assertEquals(NumberUtils.toScaledBigDecimal("23.515"), BigDecimal.valueOf(23.52), + "toScaledBigDecimal(String) 2 failed"); + assertEquals(NumberUtils.toScaledBigDecimal("23.525"), BigDecimal.valueOf(23.52), + "toScaledBigDecimal(String) 3 failed"); + assertEquals("2352.00", NumberUtils.toScaledBigDecimal("23.525").multiply(BigDecimal.valueOf(100)).toString(), + "toScaledBigDecimal(String) 4 failed"); + assertEquals(NumberUtils.toScaledBigDecimal((String) null), BigDecimal.ZERO, + "toScaledBigDecimal(String) 5 failed"); } + /** + * Test for {@link NumberUtils#toScaledBigDecimal(Double, int, RoundingMode)}. + */ @Test - public void compareLong() { - assertTrue(NumberUtils.compare(-3L, 0L) < 0); - assertEquals(0, NumberUtils.compare(113L, 113L)); - assertTrue(NumberUtils.compare(213L, 32L) > 0); + public void testToScaledBigDecimalStringIRM() { + assertEquals(NumberUtils.toScaledBigDecimal("123.456", 1, RoundingMode.CEILING), BigDecimal.valueOf(123.5), + "toScaledBigDecimal(String, int, RoudingMode) 1 failed"); + assertEquals(NumberUtils.toScaledBigDecimal("23.5159", 3, RoundingMode.FLOOR), BigDecimal.valueOf(23.515), + "toScaledBigDecimal(String, int, RoudingMode) 2 failed"); + assertEquals(NumberUtils.toScaledBigDecimal("23.525", 2, RoundingMode.HALF_UP), BigDecimal.valueOf(23.53), + "toScaledBigDecimal(String, int, RoudingMode) 3 failed"); + assertEquals( + "23521.0000", NumberUtils.toScaledBigDecimal("23.521", 4, RoundingMode.HALF_EVEN) + .multiply(BigDecimal.valueOf(1000)).toString(), + "toScaledBigDecimal(String, int, RoudingMode) 4 failed"); + assertEquals(NumberUtils.toScaledBigDecimal((String) null, 2, RoundingMode.HALF_UP), BigDecimal.ZERO, + "toScaledBigDecimal(String, int, RoudingMode) 5 failed"); } + /** + * Test for {@link NumberUtils#toShort(String)}. + */ @Test - public void compareShort() { - assertTrue(NumberUtils.compare((short) -3, (short) 0) < 0); - assertEquals(0, NumberUtils.compare((short) 113, (short) 113)); - assertTrue(NumberUtils.compare((short) 213, (short) 32) > 0); + public void testToShortString() { + assertEquals(12345, NumberUtils.toShort("12345"), "toShort(String) 1 failed"); + assertEquals(0, NumberUtils.toShort("abc"), "toShort(String) 2 failed"); + assertEquals(0, NumberUtils.toShort(""), "toShort(empty) failed"); + assertEquals(0, NumberUtils.toShort(null), "toShort(null) failed"); } + /** + * Test for {@link NumberUtils#toShort(String, short)}. + */ @Test - public void compareByte() { - assertTrue(NumberUtils.compare((byte) -3, (byte) 0) < 0); - assertEquals(0, NumberUtils.compare((byte) 113, (byte) 113)); - assertTrue(NumberUtils.compare((byte) 123, (byte) 32) > 0); + public void testToShortStringI() { + assertEquals(12345, NumberUtils.toShort("12345", (short) 5), "toShort(String, short) 1 failed"); + assertEquals(5, NumberUtils.toShort("1234.5", (short) 5), "toShort(String, short) 2 failed"); } } From faa48f6b6a6f0c1eed73ba0c69891f324f36829e Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sun, 25 Oct 2020 10:21:12 -0400 Subject: [PATCH 0387/3230] Fix generics warning. --- .../java/org/apache/commons/lang3/tuple/ImmutablePairTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/org/apache/commons/lang3/tuple/ImmutablePairTest.java b/src/test/java/org/apache/commons/lang3/tuple/ImmutablePairTest.java index 6dafe717445..d518fba523a 100644 --- a/src/test/java/org/apache/commons/lang3/tuple/ImmutablePairTest.java +++ b/src/test/java/org/apache/commons/lang3/tuple/ImmutablePairTest.java @@ -155,7 +155,7 @@ public void testPairOfObjects() { assertNull(pair2.getLeft()); assertEquals("bar", pair2.right); assertEquals("bar", pair2.getRight()); - final ImmutablePair pair3 = ImmutablePair.of(null, null); + final ImmutablePair pair3 = ImmutablePair.of(null, null); assertNull(pair3.left); assertNull(pair3.right); } From 8fbf27a830d79ffee5cd45030da098b4646c9215 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sun, 25 Oct 2020 10:29:58 -0400 Subject: [PATCH 0388/3230] Sort methods. --- .../commons/lang3/SerializationUtils.java | 274 +++++++++--------- 1 file changed, 134 insertions(+), 140 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/SerializationUtils.java b/src/main/java/org/apache/commons/lang3/SerializationUtils.java index ed46f2ab5d4..8e8ead58035 100644 --- a/src/main/java/org/apache/commons/lang3/SerializationUtils.java +++ b/src/main/java/org/apache/commons/lang3/SerializationUtils.java @@ -47,19 +47,76 @@ public class SerializationUtils { /** - *

      SerializationUtils instances should NOT be constructed in standard programming. - * Instead, the class should be used as {@code SerializationUtils.clone(object)}.

      + *

      Custom specialization of the standard JDK {@link java.io.ObjectInputStream} + * that uses a custom {@code ClassLoader} to resolve a class. + * If the specified {@code ClassLoader} is not able to resolve the class, + * the context classloader of the current thread will be used. + * This way, the standard deserialization work also in web-application + * containers and application servers, no matter in which of the + * {@code ClassLoader} the particular class that encapsulates + * serialization/deserialization lives.

      * - *

      This constructor is public to permit tools that require a JavaBean instance - * to operate.

      - * @since 2.0 + *

      For more in-depth information about the problem for which this + * class here is a workaround, see the JIRA issue LANG-626.

      */ - public SerializationUtils() { - super(); + static class ClassLoaderAwareObjectInputStream extends ObjectInputStream { + private static final Map> primitiveTypes = + new HashMap<>(); + + static { + primitiveTypes.put("byte", byte.class); + primitiveTypes.put("short", short.class); + primitiveTypes.put("int", int.class); + primitiveTypes.put("long", long.class); + primitiveTypes.put("float", float.class); + primitiveTypes.put("double", double.class); + primitiveTypes.put("boolean", boolean.class); + primitiveTypes.put("char", char.class); + primitiveTypes.put("void", void.class); + } + + private final ClassLoader classLoader; + + /** + * Constructor. + * @param in The {@code InputStream}. + * @param classLoader classloader to use + * @throws IOException if an I/O error occurs while reading stream header. + * @see java.io.ObjectInputStream + */ + ClassLoaderAwareObjectInputStream(final InputStream in, final ClassLoader classLoader) throws IOException { + super(in); + this.classLoader = classLoader; + } + + /** + * Overridden version that uses the parameterized {@code ClassLoader} or the {@code ClassLoader} + * of the current {@code Thread} to resolve the class. + * @param desc An instance of class {@code ObjectStreamClass}. + * @return A {@code Class} object corresponding to {@code desc}. + * @throws IOException Any of the usual Input/Output exceptions. + * @throws ClassNotFoundException If class of a serialized object cannot be found. + */ + @Override + protected Class resolveClass(final ObjectStreamClass desc) throws IOException, ClassNotFoundException { + final String name = desc.getName(); + try { + return Class.forName(name, false, classLoader); + } catch (final ClassNotFoundException ex) { + try { + return Class.forName(name, false, Thread.currentThread().getContextClassLoader()); + } catch (final ClassNotFoundException cnfe) { + final Class cls = primitiveTypes.get(name); + if (cls != null) { + return cls; + } + throw cnfe; + } + } + } + } - // Clone - //----------------------------------------------------------------------- /** *

      Deep clone an {@code Object} using serialization.

      * @@ -100,63 +157,28 @@ public static T clone(final T object) { } /** - * Performs a serialization roundtrip. Serializes and deserializes the given object, great for testing objects that - * implement {@link Serializable}. - * - * @param - * the type of the object involved - * @param msg - * the object to roundtrip - * @return the serialized and deserialized object - * @since 3.3 - */ - @SuppressWarnings("unchecked") // OK, because we serialized a type `T` - public static T roundtrip(final T msg) { - return (T) deserialize(serialize(msg)); - } - - // Serialize - //----------------------------------------------------------------------- - /** - *

      Serializes an {@code Object} to the specified stream.

      - * - *

      The stream will be closed once the object is written. - * This avoids the need for a finally clause, and maybe also exception - * handling, in the application code.

      - * - *

      The stream passed in is not buffered internally within this method. - * This is the responsibility of your application if desired.

      + *

      + * Deserializes a single {@code Object} from an array of bytes. + *

      * - * @param obj the object to serialize to bytes, may be null - * @param outputStream the stream to write to, must not be null - * @throws NullPointerException if {@code outputStream} is {@code null} - * @throws SerializationException (runtime) if the serialization fails - */ - public static void serialize(final Serializable obj, final OutputStream outputStream) { - Validate.notNull(outputStream, "The OutputStream must not be null"); - try (ObjectOutputStream out = new ObjectOutputStream(outputStream)) { - out.writeObject(obj); - } catch (final IOException ex) { - throw new SerializationException(ex); - } - } - - /** - *

      Serializes an {@code Object} to a byte array for - * storage/serialization.

      + *

      + * If the call site incorrectly types the return value, a {@link ClassCastException} is thrown from the call site. + * Without Generics in this declaration, the call site must type cast and can cause the same ClassCastException. + * Note that in both cases, the ClassCastException is in the call site, not in this method. + *

      * - * @param obj the object to serialize to bytes - * @return a byte[] with the converted Serializable + * @param the object type to be deserialized + * @param objectData + * the serialized object, must not be null + * @return the deserialized object + * @throws NullPointerException if {@code objectData} is {@code null} * @throws SerializationException (runtime) if the serialization fails */ - public static byte[] serialize(final Serializable obj) { - final ByteArrayOutputStream baos = new ByteArrayOutputStream(512); - serialize(obj, baos); - return baos.toByteArray(); + public static T deserialize(final byte[] objectData) { + Validate.notNull(objectData, "The byte[] must not be null"); + return deserialize(new ByteArrayInputStream(objectData)); } - // Deserialize - //----------------------------------------------------------------------- /** *

      * Deserializes an {@code Object} from the specified stream. @@ -197,97 +219,69 @@ public static T deserialize(final InputStream inputStream) { } /** - *

      - * Deserializes a single {@code Object} from an array of bytes. - *

      + * Performs a serialization roundtrip. Serializes and deserializes the given object, great for testing objects that + * implement {@link Serializable}. * - *

      - * If the call site incorrectly types the return value, a {@link ClassCastException} is thrown from the call site. - * Without Generics in this declaration, the call site must type cast and can cause the same ClassCastException. - * Note that in both cases, the ClassCastException is in the call site, not in this method. - *

      + * @param + * the type of the object involved + * @param msg + * the object to roundtrip + * @return the serialized and deserialized object + * @since 3.3 + */ + @SuppressWarnings("unchecked") // OK, because we serialized a type `T` + public static T roundtrip(final T msg) { + return (T) deserialize(serialize(msg)); + } + + /** + *

      Serializes an {@code Object} to a byte array for + * storage/serialization.

      * - * @param the object type to be deserialized - * @param objectData - * the serialized object, must not be null - * @return the deserialized object - * @throws NullPointerException if {@code objectData} is {@code null} + * @param obj the object to serialize to bytes + * @return a byte[] with the converted Serializable * @throws SerializationException (runtime) if the serialization fails */ - public static T deserialize(final byte[] objectData) { - Validate.notNull(objectData, "The byte[] must not be null"); - return deserialize(new ByteArrayInputStream(objectData)); + public static byte[] serialize(final Serializable obj) { + final ByteArrayOutputStream baos = new ByteArrayOutputStream(512); + serialize(obj, baos); + return baos.toByteArray(); } /** - *

      Custom specialization of the standard JDK {@link java.io.ObjectInputStream} - * that uses a custom {@code ClassLoader} to resolve a class. - * If the specified {@code ClassLoader} is not able to resolve the class, - * the context classloader of the current thread will be used. - * This way, the standard deserialization work also in web-application - * containers and application servers, no matter in which of the - * {@code ClassLoader} the particular class that encapsulates - * serialization/deserialization lives.

      + *

      Serializes an {@code Object} to the specified stream.

      * - *

      For more in-depth information about the problem for which this - * class here is a workaround, see the JIRA issue LANG-626.

      + *

      The stream will be closed once the object is written. + * This avoids the need for a finally clause, and maybe also exception + * handling, in the application code.

      + * + *

      The stream passed in is not buffered internally within this method. + * This is the responsibility of your application if desired.

      + * + * @param obj the object to serialize to bytes, may be null + * @param outputStream the stream to write to, must not be null + * @throws NullPointerException if {@code outputStream} is {@code null} + * @throws SerializationException (runtime) if the serialization fails */ - static class ClassLoaderAwareObjectInputStream extends ObjectInputStream { - private static final Map> primitiveTypes = - new HashMap<>(); - - static { - primitiveTypes.put("byte", byte.class); - primitiveTypes.put("short", short.class); - primitiveTypes.put("int", int.class); - primitiveTypes.put("long", long.class); - primitiveTypes.put("float", float.class); - primitiveTypes.put("double", double.class); - primitiveTypes.put("boolean", boolean.class); - primitiveTypes.put("char", char.class); - primitiveTypes.put("void", void.class); - } - - private final ClassLoader classLoader; - - /** - * Constructor. - * @param in The {@code InputStream}. - * @param classLoader classloader to use - * @throws IOException if an I/O error occurs while reading stream header. - * @see java.io.ObjectInputStream - */ - ClassLoaderAwareObjectInputStream(final InputStream in, final ClassLoader classLoader) throws IOException { - super(in); - this.classLoader = classLoader; - } - - /** - * Overridden version that uses the parameterized {@code ClassLoader} or the {@code ClassLoader} - * of the current {@code Thread} to resolve the class. - * @param desc An instance of class {@code ObjectStreamClass}. - * @return A {@code Class} object corresponding to {@code desc}. - * @throws IOException Any of the usual Input/Output exceptions. - * @throws ClassNotFoundException If class of a serialized object cannot be found. - */ - @Override - protected Class resolveClass(final ObjectStreamClass desc) throws IOException, ClassNotFoundException { - final String name = desc.getName(); - try { - return Class.forName(name, false, classLoader); - } catch (final ClassNotFoundException ex) { - try { - return Class.forName(name, false, Thread.currentThread().getContextClassLoader()); - } catch (final ClassNotFoundException cnfe) { - final Class cls = primitiveTypes.get(name); - if (cls != null) { - return cls; - } - throw cnfe; - } - } + public static void serialize(final Serializable obj, final OutputStream outputStream) { + Validate.notNull(outputStream, "The OutputStream must not be null"); + try (ObjectOutputStream out = new ObjectOutputStream(outputStream)) { + out.writeObject(obj); + } catch (final IOException ex) { + throw new SerializationException(ex); } + } + /** + *

      SerializationUtils instances should NOT be constructed in standard programming. + * Instead, the class should be used as {@code SerializationUtils.clone(object)}.

      + * + *

      This constructor is public to permit tools that require a JavaBean instance + * to operate.

      + * @since 2.0 + */ + public SerializationUtils() { + super(); } } From 4d066361c022b5d3339548b1c423a049e83b4252 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sun, 25 Oct 2020 10:31:35 -0400 Subject: [PATCH 0389/3230] Suppress warning and add comment; use a simpler error messgae. --- .../java/org/apache/commons/lang3/SerializationUtils.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/SerializationUtils.java b/src/main/java/org/apache/commons/lang3/SerializationUtils.java index 8e8ead58035..3b316a16f0b 100644 --- a/src/main/java/org/apache/commons/lang3/SerializationUtils.java +++ b/src/main/java/org/apache/commons/lang3/SerializationUtils.java @@ -207,8 +207,9 @@ public static T deserialize(final byte[] objectData) { * @throws NullPointerException if {@code inputStream} is {@code null} * @throws SerializationException (runtime) if the serialization fails */ + @SuppressWarnings("resource") // inputStream is managed by the caller public static T deserialize(final InputStream inputStream) { - Validate.notNull(inputStream, "The InputStream must not be null"); + Validate.notNull(inputStream, "inputStream"); try (ObjectInputStream in = new ObjectInputStream(inputStream)) { @SuppressWarnings("unchecked") final T obj = (T) in.readObject(); @@ -263,8 +264,9 @@ public static byte[] serialize(final Serializable obj) { * @throws NullPointerException if {@code outputStream} is {@code null} * @throws SerializationException (runtime) if the serialization fails */ + @SuppressWarnings("resource") // outputStream is managed by the caller public static void serialize(final Serializable obj, final OutputStream outputStream) { - Validate.notNull(outputStream, "The OutputStream must not be null"); + Validate.notNull(outputStream, "outputStream"); try (ObjectOutputStream out = new ObjectOutputStream(outputStream)) { out.writeObject(obj); } catch (final IOException ex) { From 54afd64c79064d76037b31e88cc68d5895d9b85c Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sun, 25 Oct 2020 10:36:34 -0400 Subject: [PATCH 0390/3230] Fix param name. --- .../java/org/apache/commons/lang3/SerializationUtils.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/SerializationUtils.java b/src/main/java/org/apache/commons/lang3/SerializationUtils.java index 3b316a16f0b..a8269abfbd6 100644 --- a/src/main/java/org/apache/commons/lang3/SerializationUtils.java +++ b/src/main/java/org/apache/commons/lang3/SerializationUtils.java @@ -225,14 +225,14 @@ public static T deserialize(final InputStream inputStream) { * * @param * the type of the object involved - * @param msg + * @param obj * the object to roundtrip * @return the serialized and deserialized object * @since 3.3 */ @SuppressWarnings("unchecked") // OK, because we serialized a type `T` - public static T roundtrip(final T msg) { - return (T) deserialize(serialize(msg)); + public static T roundtrip(final T obj) { + return (T) deserialize(serialize(obj)); } /** From 13eab3b25e6031f0e36ad55e7d6ba56cfafc04ad Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sun, 25 Oct 2020 10:43:33 -0400 Subject: [PATCH 0391/3230] Use own API for ser/deser roundtrip since the point of the test is not proper usage of JRE API but whether our classes are properly implemented. --- .../commons/lang3/tuple/ImmutablePairTest.java | 11 ++--------- .../commons/lang3/tuple/ImmutableTripleTest.java | 11 ++--------- .../apache/commons/lang3/tuple/MutablePairTest.java | 11 ++--------- .../commons/lang3/tuple/MutableTripleTest.java | 12 ++---------- 4 files changed, 8 insertions(+), 37 deletions(-) diff --git a/src/test/java/org/apache/commons/lang3/tuple/ImmutablePairTest.java b/src/test/java/org/apache/commons/lang3/tuple/ImmutablePairTest.java index d518fba523a..4dc1f42d2a3 100644 --- a/src/test/java/org/apache/commons/lang3/tuple/ImmutablePairTest.java +++ b/src/test/java/org/apache/commons/lang3/tuple/ImmutablePairTest.java @@ -23,16 +23,13 @@ import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Map.Entry; import java.util.TreeMap; +import org.apache.commons.lang3.SerializationUtils; import org.junit.jupiter.api.Test; /** @@ -164,11 +161,7 @@ public void testPairOfObjects() { @SuppressWarnings("unchecked") public void testSerialization() throws Exception { final ImmutablePair origPair = ImmutablePair.of(0, "foo"); - final ByteArrayOutputStream baos = new ByteArrayOutputStream(); - final ObjectOutputStream out = new ObjectOutputStream(baos); - out.writeObject(origPair); - final ImmutablePair deserializedPair = (ImmutablePair) new ObjectInputStream( - new ByteArrayInputStream(baos.toByteArray())).readObject(); + final ImmutablePair deserializedPair = SerializationUtils.roundtrip(origPair); assertEquals(origPair, deserializedPair); assertEquals(origPair.hashCode(), deserializedPair.hashCode()); } diff --git a/src/test/java/org/apache/commons/lang3/tuple/ImmutableTripleTest.java b/src/test/java/org/apache/commons/lang3/tuple/ImmutableTripleTest.java index 2be49421448..0af0535b06c 100644 --- a/src/test/java/org/apache/commons/lang3/tuple/ImmutableTripleTest.java +++ b/src/test/java/org/apache/commons/lang3/tuple/ImmutableTripleTest.java @@ -22,16 +22,13 @@ import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Map.Entry; import java.util.TreeMap; +import org.apache.commons.lang3.SerializationUtils; import org.junit.jupiter.api.Test; /** @@ -123,11 +120,7 @@ public void testNullTripleTyped() { @SuppressWarnings("unchecked") public void testSerialization() throws Exception { final ImmutableTriple origTriple = ImmutableTriple.of(0, "foo", Boolean.TRUE); - final ByteArrayOutputStream baos = new ByteArrayOutputStream(); - final ObjectOutputStream out = new ObjectOutputStream(baos); - out.writeObject(origTriple); - final ImmutableTriple deserializedTriple = (ImmutableTriple) new ObjectInputStream( - new ByteArrayInputStream(baos.toByteArray())).readObject(); + final ImmutableTriple deserializedTriple = SerializationUtils.roundtrip(origTriple); assertEquals(origTriple, deserializedTriple); assertEquals(origTriple.hashCode(), deserializedTriple.hashCode()); } diff --git a/src/test/java/org/apache/commons/lang3/tuple/MutablePairTest.java b/src/test/java/org/apache/commons/lang3/tuple/MutablePairTest.java index 57a6d490d95..74eb25389eb 100644 --- a/src/test/java/org/apache/commons/lang3/tuple/MutablePairTest.java +++ b/src/test/java/org/apache/commons/lang3/tuple/MutablePairTest.java @@ -20,13 +20,10 @@ import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNull; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; import java.util.HashMap; import java.util.Map.Entry; +import org.apache.commons.lang3.SerializationUtils; import org.junit.jupiter.api.Test; /** @@ -132,11 +129,7 @@ public void testPairOfObjects() { @SuppressWarnings("unchecked") public void testSerialization() throws Exception { final MutablePair origPair = MutablePair.of(0, "foo"); - final ByteArrayOutputStream baos = new ByteArrayOutputStream(); - final ObjectOutputStream out = new ObjectOutputStream(baos); - out.writeObject(origPair); - final MutablePair deserializedPair = (MutablePair) new ObjectInputStream( - new ByteArrayInputStream(baos.toByteArray())).readObject(); + final MutablePair deserializedPair = SerializationUtils.roundtrip(origPair); assertEquals(origPair, deserializedPair); assertEquals(origPair.hashCode(), deserializedPair.hashCode()); } diff --git a/src/test/java/org/apache/commons/lang3/tuple/MutableTripleTest.java b/src/test/java/org/apache/commons/lang3/tuple/MutableTripleTest.java index 70a3a798164..830e0627dfb 100644 --- a/src/test/java/org/apache/commons/lang3/tuple/MutableTripleTest.java +++ b/src/test/java/org/apache/commons/lang3/tuple/MutableTripleTest.java @@ -20,11 +20,7 @@ import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNull; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; - +import org.apache.commons.lang3.SerializationUtils; import org.junit.jupiter.api.Test; /** @@ -97,11 +93,7 @@ public void testMutate() { @SuppressWarnings("unchecked") public void testSerialization() throws Exception { final MutableTriple origTriple = MutableTriple.of(0, "foo", Boolean.TRUE); - final ByteArrayOutputStream baos = new ByteArrayOutputStream(); - final ObjectOutputStream out = new ObjectOutputStream(baos); - out.writeObject(origTriple); - final MutableTriple deserializedTriple = (MutableTriple) new ObjectInputStream( - new ByteArrayInputStream(baos.toByteArray())).readObject(); + final MutableTriple deserializedTriple = SerializationUtils.roundtrip(origTriple); assertEquals(origTriple, deserializedTriple); assertEquals(origTriple.hashCode(), deserializedTriple.hashCode()); } From 38c3d59a895ec18495fccb98550c3cfb005bd8fb Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sun, 25 Oct 2020 10:45:34 -0400 Subject: [PATCH 0392/3230] Bump spotbugs-maven-plugin from 4.1.3 to 4.1.4 (#632) Bumps [spotbugs-maven-plugin](https://github.com/spotbugs/spotbugs-maven-plugin) from 4.1.3 to 4.1.4. - [Release notes](https://github.com/spotbugs/spotbugs-maven-plugin/releases) - [Commits](https://github.com/spotbugs/spotbugs-maven-plugin/compare/spotbugs-maven-plugin-4.1.3...spotbugs-maven-plugin-4.1.4) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 83f70ad46f7..a2d886bab25 100644 --- a/pom.xml +++ b/pom.xml @@ -617,7 +617,7 @@ 8.36.2 src/site/resources/checkstyle - 4.1.3 + 4.1.4 4.1.4 false true From 05cb6139b9888dbe1784128aa7c07a31c6ca71fd Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sun, 25 Oct 2020 10:47:11 -0400 Subject: [PATCH 0393/3230] Bump spotbugs-maven-plugin from 4.1.3 to 4.1.4 #632. --- src/changes/changes.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index a38e9d84d49..572760894cd 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -64,7 +64,7 @@ The type attribute can be add,update,fix,remove. Improve StringUtils.stripAccents conversion of remaining accents. ArrayUtils.toPrimitive(Object) does not support boolean and other types #607. Enable Dependabot #587. - Update spotbugs-maven-plugin from 4.0.0 to 4.1.3, #593, #596, #609, #623. + Update spotbugs-maven-plugin from 4.0.0 to 4.1.4, #593, #596, #609, #623, #632. Update biz.aQute.bndlib from 5.1.1 to 5.2.0 #592, #628. Update junit-pioneer from 0.6.0 to 1.0.0, #589, #597, #600, #624, #625. Update checkstyle from 8.34 to 8.36 #594, #614. From 34a3096eb4570179414b92d238138596f3cc807e Mon Sep 17 00:00:00 2001 From: Edgar Asatryan <17509127+nstdio@users.noreply.github.com> Date: Sun, 25 Oct 2020 18:52:16 +0400 Subject: [PATCH 0394/3230] More coverage for CharSequenceUtils. (#631) --- .../commons/lang3/CharSequenceUtilsTest.java | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/src/test/java/org/apache/commons/lang3/CharSequenceUtilsTest.java b/src/test/java/org/apache/commons/lang3/CharSequenceUtilsTest.java index 7e2f4d16451..3353f7a7995 100644 --- a/src/test/java/org/apache/commons/lang3/CharSequenceUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/CharSequenceUtilsTest.java @@ -23,13 +23,18 @@ import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.params.provider.Arguments.arguments; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.util.Random; import java.util.stream.IntStream; +import java.util.stream.Stream; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; /** * Tests CharSequenceUtils @@ -261,6 +266,25 @@ public void testNewLastIndexOf() { } } + @ParameterizedTest + @MethodSource("lastIndexWithStandardCharSequence") + public void testLastIndexOfWithDifferentCharSequences(CharSequence cs, CharSequence search, int start, + int expected) { + assertEquals(expected, CharSequenceUtils.lastIndexOf(cs, search, start)); + } + + static Stream lastIndexWithStandardCharSequence() { + return Stream.of( + arguments("abc", "b", 2, 1), + arguments(new StringBuilder("abc"), "b", 2, 1), + arguments(new StringBuffer("abc"), "b", 2, 1), + arguments("abc", new StringBuilder("b"), 2, 1), + arguments(new StringBuilder("abc"), new StringBuilder("b"), 2, 1), + arguments(new StringBuffer("abc"), new StringBuffer("b"), 2, 1), + arguments(new StringBuilder("abc"), new StringBuffer("b"), 2, 1) + ); + } + private void testNewLastIndexOfSingle(final CharSequence a, final CharSequence b) { final int maxa = Math.max(a.length(), b.length()); for (int i = -maxa - 10; i <= maxa + 10; i++) { From 20ae8f6888705cdc74166cb2f8bfc519ff274291 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sun, 25 Oct 2020 10:53:14 -0400 Subject: [PATCH 0395/3230] More test coverage for CharSequenceUtils. #631. --- src/changes/changes.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 572760894cd..96fb91821cf 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -55,6 +55,7 @@ The type attribute can be add,update,fix,remove. Add BooleanUtils.booleanValues(). Add BooleanUtils.primitiveValues(). + More test coverage for CharSequenceUtils. #631. Bump junit-jupiter from 5.6.2 to 5.7.0. Bump spotbugs from 4.1.2 to 4.1.4, #627. From d9f5b615675d525bccc2c04ad8f261a783386c4c Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sun, 25 Oct 2020 14:39:14 -0400 Subject: [PATCH 0396/3230] Add SECURITY.MD. --- SECURITY.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 SECURITY.md diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 00000000000..de29bb8df54 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,17 @@ + +Apache Commons security page is [https://commons.apache.org/security.html](https://commons.apache.org/security.html). From 4b1a602e4903167be5e8e90f2a1578630a56ce5b Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Fri, 30 Oct 2020 09:36:32 -0400 Subject: [PATCH 0397/3230] Typo. --- SECURITY.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SECURITY.md b/SECURITY.md index de29bb8df54..51943ba7b48 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -14,4 +14,4 @@ See the License for the specific language governing permissions and limitations under the License. --> -Apache Commons security page is [https://commons.apache.org/security.html](https://commons.apache.org/security.html). +The Apache Commons security page is [https://commons.apache.org/security.html](https://commons.apache.org/security.html). From 553e192aac6903b811b5d7cce0abb488e99b6e5d Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2020 09:42:09 -0500 Subject: [PATCH 0398/3230] Bump actions/checkout from v2.3.3 to v2.3.4 (#639) Bumps [actions/checkout](https://github.com/actions/checkout) from v2.3.3 to v2.3.4. - [Release notes](https://github.com/actions/checkout/releases) - [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md) - [Commits](https://github.com/actions/checkout/compare/v2.3.3...5a4ac9002d0be2fb38bd78e4b4dbde5606d7042f) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/maven.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml index 153553bba81..3de60824cb5 100644 --- a/.github/workflows/maven.yml +++ b/.github/workflows/maven.yml @@ -31,7 +31,7 @@ jobs: experimental: true steps: - - uses: actions/checkout@v2.3.3 + - uses: actions/checkout@v2.3.4 - uses: actions/cache@v2 with: path: ~/.m2/repository From 146ddf23634997c8f3d076afa92a9b543a2a624e Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Fri, 6 Nov 2020 09:44:21 -0500 Subject: [PATCH 0399/3230] Bump actions/checkout from v2.3.3 to v2.3.4 #639. --- src/changes/changes.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 96fb91821cf..eaecb51d595 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -69,7 +69,7 @@ The type attribute can be add,update,fix,remove. Update biz.aQute.bndlib from 5.1.1 to 5.2.0 #592, #628. Update junit-pioneer from 0.6.0 to 1.0.0, #589, #597, #600, #624, #625. Update checkstyle from 8.34 to 8.36 #594, #614. - Update actions/checkout from v2.3.1 to v2.3.2 #601. + Update actions/checkout from v2.3.1 to v2.3.4 #601, #639. Update actions/setup-java from v1.4.0 to v1.4.2 #612. Update commons.jacoco.version 0.8.5 to 0.8.6 (Fixes Java 15 builds).
      From fdd73e696aefaa038c64471d5906879c848cb7fb Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2020 09:45:07 -0500 Subject: [PATCH 0400/3230] Bump checkstyle from 8.36.2 to 8.37 (#637) Bumps [checkstyle](https://github.com/checkstyle/checkstyle) from 8.36.2 to 8.37. - [Release notes](https://github.com/checkstyle/checkstyle/releases) - [Commits](https://github.com/checkstyle/checkstyle/compare/checkstyle-8.36.2...checkstyle-8.37) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index a2d886bab25..622abeeef25 100644 --- a/pom.xml +++ b/pom.xml @@ -614,7 +614,7 @@ utf-8 3.1.1 - 8.36.2 + 8.37 src/site/resources/checkstyle 4.1.4 From 6b3f258ed7f8737740a22599458c0c468864b837 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Fri, 6 Nov 2020 09:46:31 -0500 Subject: [PATCH 0401/3230] Bump checkstyle from 8.36.2 to 8.37 #637. --- src/changes/changes.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index eaecb51d595..61e6a37262a 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -59,7 +59,7 @@ The type attribute can be add,update,fix,remove. Bump junit-jupiter from 5.6.2 to 5.7.0. Bump spotbugs from 4.1.2 to 4.1.4, #627. - Bump checkstyle from 8.36 to 8.36.2 + Bump checkstyle from 8.36 to 8.37, #637. StringUtils.countMatches - clarify Javadoc. Remove redundant argument from substring call. Improve StringUtils.stripAccents conversion of remaining accents. From 6f51b9b7cb362655ad9b6587120b63d56e44264d Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Fri, 13 Nov 2020 10:01:10 -0500 Subject: [PATCH 0402/3230] Sort members. --- .../lang3/StringUtilsContainsTest.java | 42 +++++++++---------- 1 file changed, 21 insertions(+), 21 deletions(-) diff --git a/src/test/java/org/apache/commons/lang3/StringUtilsContainsTest.java b/src/test/java/org/apache/commons/lang3/StringUtilsContainsTest.java index 4a0a4ccf535..f384ebbb720 100644 --- a/src/test/java/org/apache/commons/lang3/StringUtilsContainsTest.java +++ b/src/test/java/org/apache/commons/lang3/StringUtilsContainsTest.java @@ -175,6 +175,27 @@ public void testContainsAny_StringString() { assertFalse(StringUtils.containsAny("ab", "z")); } + @Test + public void testContainsAny_StringStringArray() { + assertFalse(StringUtils.containsAny(null, (String[]) null)); + assertFalse(StringUtils.containsAny(null, new String[0])); + assertFalse(StringUtils.containsAny(null, new String[] { "hello" })); + assertFalse(StringUtils.containsAny("", (String[]) null)); + assertFalse(StringUtils.containsAny("", new String[0])); + assertFalse(StringUtils.containsAny("", new String[] { "hello" })); + assertFalse(StringUtils.containsAny("hello, goodbye", (String[]) null)); + assertFalse(StringUtils.containsAny("hello, goodbye", new String[0])); + assertTrue(StringUtils.containsAny("hello, goodbye", new String[]{"hello", "goodbye"})); + assertTrue(StringUtils.containsAny("hello, goodbye", new String[]{"hello", "Goodbye"})); + assertFalse(StringUtils.containsAny("hello, goodbye", new String[]{"Hello", "Goodbye"})); + assertFalse(StringUtils.containsAny("hello, goodbye", new String[]{"Hello", null})); + assertFalse(StringUtils.containsAny("hello, null", new String[] { "Hello", null })); + // Javadoc examples: + assertTrue(StringUtils.containsAny("abcd", "ab", null)); + assertTrue(StringUtils.containsAny("abcd", "ab", "cd")); + assertTrue(StringUtils.containsAny("abc", "d", "abc")); + } + /** * See http://www.oracle.com/technetwork/articles/javase/supplementary-142654.html */ @@ -206,27 +227,6 @@ public void testContainsAny_StringWithSupplementaryChars() { assertFalse(StringUtils.containsAny(CharU20001, CharU20000)); } - @Test - public void testContainsAny_StringStringArray() { - assertFalse(StringUtils.containsAny(null, (String[]) null)); - assertFalse(StringUtils.containsAny(null, new String[0])); - assertFalse(StringUtils.containsAny(null, new String[] { "hello" })); - assertFalse(StringUtils.containsAny("", (String[]) null)); - assertFalse(StringUtils.containsAny("", new String[0])); - assertFalse(StringUtils.containsAny("", new String[] { "hello" })); - assertFalse(StringUtils.containsAny("hello, goodbye", (String[]) null)); - assertFalse(StringUtils.containsAny("hello, goodbye", new String[0])); - assertTrue(StringUtils.containsAny("hello, goodbye", new String[]{"hello", "goodbye"})); - assertTrue(StringUtils.containsAny("hello, goodbye", new String[]{"hello", "Goodbye"})); - assertFalse(StringUtils.containsAny("hello, goodbye", new String[]{"Hello", "Goodbye"})); - assertFalse(StringUtils.containsAny("hello, goodbye", new String[]{"Hello", null})); - assertFalse(StringUtils.containsAny("hello, null", new String[] { "Hello", null })); - // Javadoc examples: - assertTrue(StringUtils.containsAny("abcd", "ab", null)); - assertTrue(StringUtils.containsAny("abcd", "ab", "cd")); - assertTrue(StringUtils.containsAny("abc", "d", "abc")); - } - @DefaultLocale(language = "de", country = "DE") @Test public void testContainsIgnoreCase_LocaleIndependence() { From 6a991d841301c30214255984535a1fe7f78248c7 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Fri, 13 Nov 2020 10:10:27 -0500 Subject: [PATCH 0403/3230] Close HTML tag. --- src/main/java/org/apache/commons/lang3/function/TriFunction.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/org/apache/commons/lang3/function/TriFunction.java b/src/main/java/org/apache/commons/lang3/function/TriFunction.java index 653013ada74..6e5af2dc705 100644 --- a/src/main/java/org/apache/commons/lang3/function/TriFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/TriFunction.java @@ -26,6 +26,7 @@ *

      * This is a functional interface whose functional method is * {@link #apply(Object, Object, Object)}. + *

      * * @param the type of the first argument to the function * @param the type of the second argument to the function From 93d520a3e1781d99f99711df7016f474b36fbf82 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Fri, 13 Nov 2020 10:30:08 -0500 Subject: [PATCH 0404/3230] Add StringUtils.containsAnyIgnoreCase(CharSequence, CharSequence...). --- src/changes/changes.xml | 1 + .../org/apache/commons/lang3/StringUtils.java | 159 +++++++----------- .../lang3/function/ToBooleanBiFunction.java | 43 +++++ .../lang3/StringUtilsContainsTest.java | 21 +++ 4 files changed, 129 insertions(+), 95 deletions(-) create mode 100644 src/main/java/org/apache/commons/lang3/function/ToBooleanBiFunction.java diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 61e6a37262a..316f3558898 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -55,6 +55,7 @@ The type attribute can be add,update,fix,remove. Add BooleanUtils.booleanValues(). Add BooleanUtils.primitiveValues(). + Add StringUtils.containsAnyIgnoreCase(CharSequence, CharSequence...). More test coverage for CharSequenceUtils. #631. Bump junit-jupiter from 5.6.2 to 5.7.0. diff --git a/src/main/java/org/apache/commons/lang3/StringUtils.java b/src/main/java/org/apache/commons/lang3/StringUtils.java index 3089082778e..588bf0be295 100644 --- a/src/main/java/org/apache/commons/lang3/StringUtils.java +++ b/src/main/java/org/apache/commons/lang3/StringUtils.java @@ -30,6 +30,8 @@ import java.util.function.Supplier; import java.util.regex.Pattern; +import org.apache.commons.lang3.function.ToBooleanBiFunction; + /** *

      Operations on {@link java.lang.String} that are * {@code null} safe.

      @@ -184,8 +186,6 @@ public class StringUtils { */ private static final Pattern STRIP_ACCENTS_PATTERN = Pattern.compile("\\p{InCombiningDiacriticalMarks}+"); //$NON-NLS-1$ - // Abbreviating - //----------------------------------------------------------------------- /** *

      Abbreviates a String using ellipses. This will turn * "Now is the time for all good men" into "Now is the time for..."

      @@ -559,8 +559,6 @@ public static String capitalize(final String str) { return new String(newCodePoints, 0, outOffset); } - // Centering - //----------------------------------------------------------------------- /** *

      Centers a String in a larger String of size {@code size} * using the space character (' ').

      @@ -669,8 +667,6 @@ public static String center(String str, final int size, String padStr) { return str; } - // Chomping - //----------------------------------------------------------------------- /** *

      Removes one newline from end of a String if it's there, * otherwise leave it alone. A newline is "{@code \n}", @@ -754,8 +750,6 @@ public static String chomp(final String str, final String separator) { return removeEnd(str, separator); } - // Chopping - //----------------------------------------------------------------------- /** *

      Remove the last character from a String.

      * @@ -796,8 +790,6 @@ public static String chop(final String str) { return ret; } - // Compare - //----------------------------------------------------------------------- /** *

      Compare two Strings lexicographically, as per {@link String#compareTo(String)}, returning :

      *