Modified: pivot/trunk/core/src/org/apache/pivot/util/Utils.java URL: http://svn.apache.org/viewvc/pivot/trunk/core/src/org/apache/pivot/util/Utils.java?rev=1913470&r1=1913469&r2=1913470&view=diff ============================================================================== --- pivot/trunk/core/src/org/apache/pivot/util/Utils.java (original) +++ pivot/trunk/core/src/org/apache/pivot/util/Utils.java Tue Oct 31 19:15:47 2023 @@ -1,454 +1,454 @@ -/* - * 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.pivot.util; - -/** - * Utility methods for other parts of the code. - */ -public final class Utils { - /** - * Non-public constructor for a utility class. - */ - private Utils() { - } - - /** - * Decide if two strings are the same content (not just the same reference). - * <p> Works properly for either string being {@code null}. - * @param s1 First string to compare (can be {@code null}). - * @param s2 Second string to compare (can also be {@code null}). - * @return {@code true} if both strings are {@code null} or if - * <code>s1.equals(s2)</code>. - */ - public static boolean stringsAreEqual(final String s1, final String s2) { - if (s1 == null && s2 == null) { - return true; - } - if ((s1 != null && s2 == null) || (s1 == null && s2 != null)) { - return false; - } - return s1.equals(s2); - } - - /** - * Does an "equals" check, taking care that null object references are handled - * appropriately. - * - * @param obj1 The first object to compare (could be {@code null}). - * @param obj2 The second object to compare (could be {@code null}). - * @return {@code true} if the two objects are non-null and equal (according - * to their {@code Object#equals} method), or are both {@code null}. - */ - public static boolean equals(final Object obj1, final Object obj2) { - if (obj1 != null && obj2 != null) { - return obj1.equals(obj2); - } else if (obj1 == null && obj2 == null) { - return true; - } - return false; - } - - /** - * Check if the input argument is {@code null} and throw an - * {@link IllegalArgumentException} if so, with an optional - * message derived from the given string. - * - * @param value The argument value to check for {@code null}. - * @param description A description for the value used to - * construct a message like {@code "xxx must not be null."}. Can be - * {@code null} or an empty string, in which case a plain - * {@link IllegalArgumentException} is thrown without any detail message. - * @throws IllegalArgumentException if the value is {@code null}. - */ - public static void checkNull(final Object value, final String description) { - if (value == null) { - if (isNullOrEmpty(description)) { - throw new IllegalArgumentException(); - } else { - throw new IllegalArgumentException(description + " must not be null."); - } - } - } - - /** - * Check if the input argument is {@code null} and throw an - * {@link IllegalArgumentException} with an empty message if so. - * - * @param value The argument value to check for {@code null}. - * @throws IllegalArgumentException if the value is {@code null}. - */ - public static void checkNull(final Object value) { - checkNull(value, null); - } - - /** - * Check if the input string is {@code null} or empty (or all whitespace). - * - * @param value The string to check. - * @return {@code true} if the input is {@code null} or empty, {@code false} - * otherwise. - */ - public static boolean isNullOrEmpty(final String value) { - if (value == null) { - return true; - } - return value.trim().isEmpty(); - } - - /** - * Check if the input value is {@code null} or if it is a string and is empty - * (or all whitespace). - * - * @param value The object to check. - * @return {@code true} if the input is {@code null} or an empty string, - * {@code false} otherwise (which would include a non-null object other - * than a string). - */ - public static boolean isNullOrEmpty(final Object value) { - if (value == null) { - return true; - } - return (value instanceof String) && ((String) value).trim().isEmpty(); - } - - /** - * Check if the input argument is {@code null} and if it is a string - * if it is empty, and throw an {@link IllegalArgumentException} if so, - * with an optional message derived from the given string. - * - * @param value The argument value to check for {@code null} or empty. - * @param description A description for the argument, used to - * construct a message like {@code "xxx must not be null or empty."}. - * Can be {@code null} or an empty string, in which case a plain - * {@link IllegalArgumentException} is thrown without any detail message. - * @throws IllegalArgumentException if the value is {@code null}. - */ - public static void checkNullOrEmpty(final Object value, final String description) { - if (value == null || (value instanceof String && isNullOrEmpty((String) value))) { - if (isNullOrEmpty(description)) { - throw new IllegalArgumentException(); - } else { - throw new IllegalArgumentException(description + " must not be null or empty."); - } - } - } - - /** - * Check if the input argument is {@code null} and if it is a string - * if it is empty, and throw an {@link IllegalArgumentException} if so. - * - * @param value The string to check. - * @throws IllegalArgumentException if the value is {@code null}. - */ - public static void checkNullOrEmpty(final Object value) { - checkNullOrEmpty(value, null); - } - - /** - * If the first argument given is {@code null} then substitute the second argument - * for it, else just return the given argument. - * - * @param <T> Type of value being tested and returned. - * @param value The argument to check for "null-ness". - * @param substituteForNull The value to use instead of the {@code null} value. - * @return Either the value or the substituted one (which could be null, but then - * why would you call this method?). - */ - public static <T> T ifNull(final T value, final T substituteForNull) { - return (value == null) ? substituteForNull : value; - } - - /** - * Check if the input argument is negative (less than zero), and throw an - * {@link IllegalArgumentException} if so, with or without a descriptive message, - * depending on the {@code description} supplied. - * - * @param value The value to check. - * @param description A description for the argument, used to - * construct a message like {@code "xxx must not be negative."}. - * Can be {@code null} or an empty string, in which case a plain - * {@link IllegalArgumentException} is thrown without any detail message. - * @throws IllegalArgumentException if the value is negative. - */ - public static void checkNonNegative(final int value, final String description) { - if (value < 0) { - if (isNullOrEmpty(description)) { - throw new IllegalArgumentException(); - } else { - throw new IllegalArgumentException(description + " must not be negative."); - } - } - } - - /** - * Check if the input argument is negative (less than zero), and throw an - * {@link IllegalArgumentException} if so. - * - * @param value The value to check. - * @throws IllegalArgumentException if the value is negative. - */ - public static void checkNonNegative(final int value) { - checkNonNegative(value, null); - } - - /** - * Check if the input argument is negative (less than zero), and throw an - * {@link IllegalArgumentException} if so, with or without a descriptive message, - * depending on the {@code description} supplied. - * - * @param value The value to check. - * @param description A description for the argument, used to - * construct a message like {@code "xxx must not be negative."}. - * Can be {@code null} or an empty string, in which case a plain - * {@link IllegalArgumentException} is thrown without any detail message. - * @throws IllegalArgumentException if the value is negative. - */ - public static void checkNonNegative(final float value, final String description) { - if (value < 0.0f) { - if (isNullOrEmpty(description)) { - throw new IllegalArgumentException(); - } else { - throw new IllegalArgumentException(description + " must not be negative."); - } - } - } - - /** - * Check if the input argument is negative (less than zero), and throw an - * {@link IllegalArgumentException} if so. - * - * @param value The value to check. - * @throws IllegalArgumentException if the value is negative. - */ - public static void checkNonNegative(final float value) { - checkNonNegative(value, null); - } - - /** - * Check if the input argument is positive (greater than zero), and throw an - * {@link IllegalArgumentException} if not, with or without a descriptive message, - * depending on the {@code description} supplied. - * - * @param value The value to check. - * @param description A description for the argument, used to - * construct a message like {@code "xxx must be positive."}. - * Can be {@code null} or an empty string, in which case a plain - * {@link IllegalArgumentException} is thrown without any detail message. - * @throws IllegalArgumentException if the value is negative or zero. - */ - public static void checkPositive(final int value, final String description) { - if (value <= 0) { - if (isNullOrEmpty(description)) { - throw new IllegalArgumentException(); - } else { - throw new IllegalArgumentException(description + " must be positive."); - } - } - } - - /** - * Check if the input argument is positive (greater than zero), and throw an - * {@link IllegalArgumentException} if not. - * - * @param value The value to check. - * @throws IllegalArgumentException if the value is negative or zero. - */ - public static void checkPositive(final int value) { - checkPositive(value, null); - } - - /** - * Check if the input argument is positive (greater than zero), and throw an - * {@link IllegalArgumentException} if not, with or without a descriptive message, - * depending on the {@code description} supplied. - * - * @param value The value to check. - * @param description A description for the argument, used to - * construct a message like {@code "xxx must be positive."}. - * Can be {@code null} or an empty string, in which case a plain - * {@link IllegalArgumentException} is thrown without any detail message. - * @throws IllegalArgumentException if the value is negative. - */ - public static void checkPositive(final float value, final String description) { - if (value <= 0.0f) { - if (isNullOrEmpty(description)) { - throw new IllegalArgumentException(); - } else { - throw new IllegalArgumentException(description + " must be positive."); - } - } - } - - /** - * Check if the input argument is positive (greater than zero), and throw an - * {@link IllegalArgumentException} if not. - * - * @param value The value to check. - * @throws IllegalArgumentException if the value is negative or zero. - */ - public static void checkPositive(final float value) { - checkPositive(value, null); - } - - /** - * Check that the given value falls within the range of a non-negative "short" value, that is - * between 0 and {@link Short#MAX_VALUE} (inclusive). - * - * @param value The value to check. - * @param description The optional argument used to describe the value in case it is out of range - * (used in the thrown exception). - * @throws IllegalArgumentException if the value is out of range. - */ - public static void checkInRangeOfShort(final int value, final String description) { - if (value < 0 || value > (int) Short.MAX_VALUE) { - String valueMsg = ifNull(description, "value"); - throw new IllegalArgumentException(valueMsg + " must be less than or equal " - + Short.MAX_VALUE + "."); - } - } - - /** - * Check that the given value falls within the range of a non-negative "short" value, that is - * between 0 and {@link Short#MAX_VALUE} (inclusive). - * - * @param value The value to check. - * @throws IllegalArgumentException if the value is out of range. - */ - public static void checkInRangeOfShort(final int value) { - checkInRangeOfShort(value, null); - } - - /** - * Check that the given {@code index} is between the values of {@code start} and {@code end}. - * - * @param index The candidate index into the range. - * @param start The start of the acceptable range (inclusive). - * @param end The end of the acceptable range (inclusive). - * - * @throws IllegalArgumentException if {@code end < start}. - * @throws IndexOutOfBoundsException if {@code index < start} or {@code index > end}. - */ - public static void checkIndexBounds(final int index, final int start, final int end) { - if (end < start) { - throw new IllegalArgumentException("end (" + end + ") < " + "start (" + start + ")"); - } - if (index < start || index > end) { - throw new IndexOutOfBoundsException("Index " + index + " out of bounds [" + start + "," - + end + "]."); - } - } - - /** - * Special case of {@link #checkIndexBounds(int, int, int)} for the case that start is zero and therefore - * the end case is usually size - 1. - * - * @param index The candidate index into the zero-based range. - * @param size The size of the array/list/etc. (so the proper range is {@code 0 .. size - 1}). - * @throws IndexOutOfBoundsException if the {@code index < 0} or {@code index >= size}. - */ - public static void checkZeroBasedIndex(final int index, final int size) { - if (index < 0 || index >= size) { - throw new IndexOutOfBoundsException("Index " + index + " out of bounds [0," + (size - 1) + "]."); - } - } - - /** - * Check that the given {@code index} plus {@code count} are between the values of - * {@code start} and {@code end}. - * - * @param index The candidate index into the range. - * @param count The number of elements in the indexed selection. - * @param start The start of the acceptable range (inclusive). - * @param end The end of the acceptable range (inclusive). - * - * @throws IllegalArgumentException if {@code end < start}, or - * if {@code count} or {@code start} are {@code < zero}. - * @throws IndexOutOfBoundsException if {@code index < start} or - * if {@code index + count > end}. - */ - public static void checkIndexBounds(final int index, final int count, final int start, final int end) { - if (end < start) { - throw new IllegalArgumentException("end (" + end + ") < " + "start (" + start + ")"); - } - if (count < 0 || start < 0) { - throw new IllegalArgumentException("count (" + count + ") < 0 or start (" + start - + ") < 0"); - } - if (index < start) { - throw new IndexOutOfBoundsException("Index " + index + " out of bounds [" + start + "," - + end + "]."); - } - if (index + count > end) { - throw new IndexOutOfBoundsException("Index + count (" + index + " + " + count - + ") out of bounds [" + start + "," + end + "]."); - } - } - - /** - * Check that the given {@code startIndex} and {@code endIndex} are between - * the values of {@code start} and {@code end}. - * - * @param startIndex The beginning index to check. - * @param endIndex The ending index (inclusive) to check. - * @param start The start of the acceptable range (inclusive). - * @param end The end of the acceptable range (inclusive). - * - * @throws IllegalArgumentException if {@code startIndex > endIndex}. - * @throws IndexOutOfBoundsException if {@code startIndex < start} or - * {@code endIndex > end}. - */ - public static void checkTwoIndexBounds(final int startIndex, final int endIndex, final int start, final int end) { - if (startIndex > endIndex) { - throw new IllegalArgumentException("endIndex (" + endIndex + ") < " + "startIndex (" + startIndex + ")"); - } - - if (startIndex < start || endIndex > end) { - throw new IndexOutOfBoundsException("startIndex " + startIndex + " or endIndex " + endIndex - + " out of bounds [" + start + "," + end + "]."); - } - } - - /** - * Check the count of new or additional characters exceeding the specified maximum. - * - * @param currentCount For a "new" text operation (from {@code setText} this should be < zero - * (that is, a different message is thrown), otherwise the current count for an {@code insertText} - * operation. - * @param newCount If {@code currentCount} is negative, this is the complete count of text that - * will be set, otherwise this is the incremental new amount of text to add to the current. - * @param maximum The current maximum length. - * @throws IllegalArgumentException if the count exceeds the maximum. - */ - public static void checkTextMaximumLength(final int currentCount, final int newCount, final int maximum) { - if (currentCount < 0) { - if (newCount > maximum) { - throw new IllegalArgumentException(String.format( - "New text length of %1$,d exceeds the maximum length of %2$,d.", - newCount, maximum)); - } - } else { - if (currentCount + newCount > maximum) { - throw new IllegalArgumentException(String.format( - "Insertion of %1$,d characters to existing length of %2$,d would " - + "exceed the maximum length of %3$,d.", - newCount, currentCount, maximum)); - } - } - } - - -} +/* + * 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.pivot.util; + +/** + * Utility methods for other parts of the code. + */ +public final class Utils { + /** + * Non-public constructor for a utility class. + */ + private Utils() { + } + + /** + * Decide if two strings are the same content (not just the same reference). + * <p> Works properly for either string being {@code null}. + * @param s1 First string to compare (can be {@code null}). + * @param s2 Second string to compare (can also be {@code null}). + * @return {@code true} if both strings are {@code null} or if + * <code>s1.equals(s2)</code>. + */ + public static boolean stringsAreEqual(final String s1, final String s2) { + if (s1 == null && s2 == null) { + return true; + } + if ((s1 != null && s2 == null) || (s1 == null && s2 != null)) { + return false; + } + return s1.equals(s2); + } + + /** + * Does an "equals" check, taking care that null object references are handled + * appropriately. + * + * @param obj1 The first object to compare (could be {@code null}). + * @param obj2 The second object to compare (could be {@code null}). + * @return {@code true} if the two objects are non-null and equal (according + * to their {@code Object#equals} method), or are both {@code null}. + */ + public static boolean equals(final Object obj1, final Object obj2) { + if (obj1 != null && obj2 != null) { + return obj1.equals(obj2); + } else if (obj1 == null && obj2 == null) { + return true; + } + return false; + } + + /** + * Check if the input argument is {@code null} and throw an + * {@link IllegalArgumentException} if so, with an optional + * message derived from the given string. + * + * @param value The argument value to check for {@code null}. + * @param description A description for the value used to + * construct a message like {@code "xxx must not be null."}. Can be + * {@code null} or an empty string, in which case a plain + * {@link IllegalArgumentException} is thrown without any detail message. + * @throws IllegalArgumentException if the value is {@code null}. + */ + public static void checkNull(final Object value, final String description) { + if (value == null) { + if (isNullOrEmpty(description)) { + throw new IllegalArgumentException(); + } else { + throw new IllegalArgumentException(description + " must not be null."); + } + } + } + + /** + * Check if the input argument is {@code null} and throw an + * {@link IllegalArgumentException} with an empty message if so. + * + * @param value The argument value to check for {@code null}. + * @throws IllegalArgumentException if the value is {@code null}. + */ + public static void checkNull(final Object value) { + checkNull(value, null); + } + + /** + * Check if the input string is {@code null} or empty (or all whitespace). + * + * @param value The string to check. + * @return {@code true} if the input is {@code null} or empty, {@code false} + * otherwise. + */ + public static boolean isNullOrEmpty(final String value) { + if (value == null) { + return true; + } + return value.trim().isEmpty(); + } + + /** + * Check if the input value is {@code null} or if it is a string and is empty + * (or all whitespace). + * + * @param value The object to check. + * @return {@code true} if the input is {@code null} or an empty string, + * {@code false} otherwise (which would include a non-null object other + * than a string). + */ + public static boolean isNullOrEmpty(final Object value) { + if (value == null) { + return true; + } + return (value instanceof String) && ((String) value).trim().isEmpty(); + } + + /** + * Check if the input argument is {@code null} and if it is a string + * if it is empty, and throw an {@link IllegalArgumentException} if so, + * with an optional message derived from the given string. + * + * @param value The argument value to check for {@code null} or empty. + * @param description A description for the argument, used to + * construct a message like {@code "xxx must not be null or empty."}. + * Can be {@code null} or an empty string, in which case a plain + * {@link IllegalArgumentException} is thrown without any detail message. + * @throws IllegalArgumentException if the value is {@code null}. + */ + public static void checkNullOrEmpty(final Object value, final String description) { + if (value == null || (value instanceof String && isNullOrEmpty((String) value))) { + if (isNullOrEmpty(description)) { + throw new IllegalArgumentException(); + } else { + throw new IllegalArgumentException(description + " must not be null or empty."); + } + } + } + + /** + * Check if the input argument is {@code null} and if it is a string + * if it is empty, and throw an {@link IllegalArgumentException} if so. + * + * @param value The string to check. + * @throws IllegalArgumentException if the value is {@code null}. + */ + public static void checkNullOrEmpty(final Object value) { + checkNullOrEmpty(value, null); + } + + /** + * If the first argument given is {@code null} then substitute the second argument + * for it, else just return the given argument. + * + * @param <T> Type of value being tested and returned. + * @param value The argument to check for "null-ness". + * @param substituteForNull The value to use instead of the {@code null} value. + * @return Either the value or the substituted one (which could be null, but then + * why would you call this method?). + */ + public static <T> T ifNull(final T value, final T substituteForNull) { + return (value == null) ? substituteForNull : value; + } + + /** + * Check if the input argument is negative (less than zero), and throw an + * {@link IllegalArgumentException} if so, with or without a descriptive message, + * depending on the {@code description} supplied. + * + * @param value The value to check. + * @param description A description for the argument, used to + * construct a message like {@code "xxx must not be negative."}. + * Can be {@code null} or an empty string, in which case a plain + * {@link IllegalArgumentException} is thrown without any detail message. + * @throws IllegalArgumentException if the value is negative. + */ + public static void checkNonNegative(final int value, final String description) { + if (value < 0) { + if (isNullOrEmpty(description)) { + throw new IllegalArgumentException(); + } else { + throw new IllegalArgumentException(description + " must not be negative."); + } + } + } + + /** + * Check if the input argument is negative (less than zero), and throw an + * {@link IllegalArgumentException} if so. + * + * @param value The value to check. + * @throws IllegalArgumentException if the value is negative. + */ + public static void checkNonNegative(final int value) { + checkNonNegative(value, null); + } + + /** + * Check if the input argument is negative (less than zero), and throw an + * {@link IllegalArgumentException} if so, with or without a descriptive message, + * depending on the {@code description} supplied. + * + * @param value The value to check. + * @param description A description for the argument, used to + * construct a message like {@code "xxx must not be negative."}. + * Can be {@code null} or an empty string, in which case a plain + * {@link IllegalArgumentException} is thrown without any detail message. + * @throws IllegalArgumentException if the value is negative. + */ + public static void checkNonNegative(final float value, final String description) { + if (value < 0.0f) { + if (isNullOrEmpty(description)) { + throw new IllegalArgumentException(); + } else { + throw new IllegalArgumentException(description + " must not be negative."); + } + } + } + + /** + * Check if the input argument is negative (less than zero), and throw an + * {@link IllegalArgumentException} if so. + * + * @param value The value to check. + * @throws IllegalArgumentException if the value is negative. + */ + public static void checkNonNegative(final float value) { + checkNonNegative(value, null); + } + + /** + * Check if the input argument is positive (greater than zero), and throw an + * {@link IllegalArgumentException} if not, with or without a descriptive message, + * depending on the {@code description} supplied. + * + * @param value The value to check. + * @param description A description for the argument, used to + * construct a message like {@code "xxx must be positive."}. + * Can be {@code null} or an empty string, in which case a plain + * {@link IllegalArgumentException} is thrown without any detail message. + * @throws IllegalArgumentException if the value is negative or zero. + */ + public static void checkPositive(final int value, final String description) { + if (value <= 0) { + if (isNullOrEmpty(description)) { + throw new IllegalArgumentException(); + } else { + throw new IllegalArgumentException(description + " must be positive."); + } + } + } + + /** + * Check if the input argument is positive (greater than zero), and throw an + * {@link IllegalArgumentException} if not. + * + * @param value The value to check. + * @throws IllegalArgumentException if the value is negative or zero. + */ + public static void checkPositive(final int value) { + checkPositive(value, null); + } + + /** + * Check if the input argument is positive (greater than zero), and throw an + * {@link IllegalArgumentException} if not, with or without a descriptive message, + * depending on the {@code description} supplied. + * + * @param value The value to check. + * @param description A description for the argument, used to + * construct a message like {@code "xxx must be positive."}. + * Can be {@code null} or an empty string, in which case a plain + * {@link IllegalArgumentException} is thrown without any detail message. + * @throws IllegalArgumentException if the value is negative. + */ + public static void checkPositive(final float value, final String description) { + if (value <= 0.0f) { + if (isNullOrEmpty(description)) { + throw new IllegalArgumentException(); + } else { + throw new IllegalArgumentException(description + " must be positive."); + } + } + } + + /** + * Check if the input argument is positive (greater than zero), and throw an + * {@link IllegalArgumentException} if not. + * + * @param value The value to check. + * @throws IllegalArgumentException if the value is negative or zero. + */ + public static void checkPositive(final float value) { + checkPositive(value, null); + } + + /** + * Check that the given value falls within the range of a non-negative "short" value, that is + * between 0 and {@link Short#MAX_VALUE} (inclusive). + * + * @param value The value to check. + * @param description The optional argument used to describe the value in case it is out of range + * (used in the thrown exception). + * @throws IllegalArgumentException if the value is out of range. + */ + public static void checkInRangeOfShort(final int value, final String description) { + if (value < 0 || value > (int) Short.MAX_VALUE) { + String valueMsg = ifNull(description, "value"); + throw new IllegalArgumentException(valueMsg + " must be less than or equal " + + Short.MAX_VALUE + "."); + } + } + + /** + * Check that the given value falls within the range of a non-negative "short" value, that is + * between 0 and {@link Short#MAX_VALUE} (inclusive). + * + * @param value The value to check. + * @throws IllegalArgumentException if the value is out of range. + */ + public static void checkInRangeOfShort(final int value) { + checkInRangeOfShort(value, null); + } + + /** + * Check that the given {@code index} is between the values of {@code start} and {@code end}. + * + * @param index The candidate index into the range. + * @param start The start of the acceptable range (inclusive). + * @param end The end of the acceptable range (inclusive). + * + * @throws IllegalArgumentException if {@code end < start}. + * @throws IndexOutOfBoundsException if {@code index < start} or {@code index > end}. + */ + public static void checkIndexBounds(final int index, final int start, final int end) { + if (end < start) { + throw new IllegalArgumentException("end (" + end + ") < " + "start (" + start + ")"); + } + if (index < start || index > end) { + throw new IndexOutOfBoundsException("Index " + index + " out of bounds [" + start + "," + + end + "]."); + } + } + + /** + * Special case of {@link #checkIndexBounds(int, int, int)} for the case that start is zero and therefore + * the end case is usually size - 1. + * + * @param index The candidate index into the zero-based range. + * @param size The size of the array/list/etc. (so the proper range is {@code 0 .. size - 1}). + * @throws IndexOutOfBoundsException if the {@code index < 0} or {@code index >= size}. + */ + public static void checkZeroBasedIndex(final int index, final int size) { + if (index < 0 || index >= size) { + throw new IndexOutOfBoundsException("Index " + index + " out of bounds [0," + (size - 1) + "]."); + } + } + + /** + * Check that the given {@code index} plus {@code count} are between the values of + * {@code start} and {@code end}. + * + * @param index The candidate index into the range. + * @param count The number of elements in the indexed selection. + * @param start The start of the acceptable range (inclusive). + * @param end The end of the acceptable range (inclusive). + * + * @throws IllegalArgumentException if {@code end < start}, or + * if {@code count} or {@code start} are {@code < zero}. + * @throws IndexOutOfBoundsException if {@code index < start} or + * if {@code index + count > end}. + */ + public static void checkIndexBounds(final int index, final int count, final int start, final int end) { + if (end < start) { + throw new IllegalArgumentException("end (" + end + ") < " + "start (" + start + ")"); + } + if (count < 0 || start < 0) { + throw new IllegalArgumentException("count (" + count + ") < 0 or start (" + start + + ") < 0"); + } + if (index < start) { + throw new IndexOutOfBoundsException("Index " + index + " out of bounds [" + start + "," + + end + "]."); + } + if (index + count > end) { + throw new IndexOutOfBoundsException("Index + count (" + index + " + " + count + + ") out of bounds [" + start + "," + end + "]."); + } + } + + /** + * Check that the given {@code startIndex} and {@code endIndex} are between + * the values of {@code start} and {@code end}. + * + * @param startIndex The beginning index to check. + * @param endIndex The ending index (inclusive) to check. + * @param start The start of the acceptable range (inclusive). + * @param end The end of the acceptable range (inclusive). + * + * @throws IllegalArgumentException if {@code startIndex > endIndex}. + * @throws IndexOutOfBoundsException if {@code startIndex < start} or + * {@code endIndex > end}. + */ + public static void checkTwoIndexBounds(final int startIndex, final int endIndex, final int start, final int end) { + if (startIndex > endIndex) { + throw new IllegalArgumentException("endIndex (" + endIndex + ") < " + "startIndex (" + startIndex + ")"); + } + + if (startIndex < start || endIndex > end) { + throw new IndexOutOfBoundsException("startIndex " + startIndex + " or endIndex " + endIndex + + " out of bounds [" + start + "," + end + "]."); + } + } + + /** + * Check the count of new or additional characters exceeding the specified maximum. + * + * @param currentCount For a "new" text operation (from {@code setText} this should be < zero + * (that is, a different message is thrown), otherwise the current count for an {@code insertText} + * operation. + * @param newCount If {@code currentCount} is negative, this is the complete count of text that + * will be set, otherwise this is the incremental new amount of text to add to the current. + * @param maximum The current maximum length. + * @throws IllegalArgumentException if the count exceeds the maximum. + */ + public static void checkTextMaximumLength(final int currentCount, final int newCount, final int maximum) { + if (currentCount < 0) { + if (newCount > maximum) { + throw new IllegalArgumentException(String.format( + "New text length of %1$,d exceeds the maximum length of %2$,d.", + newCount, maximum)); + } + } else { + if (currentCount + newCount > maximum) { + throw new IllegalArgumentException(String.format( + "Insertion of %1$,d characters to existing length of %2$,d would " + + "exceed the maximum length of %3$,d.", + newCount, currentCount, maximum)); + } + } + } + + +}
Propchange: pivot/trunk/core/src/org/apache/pivot/util/Utils.java ------------------------------------------------------------------------------ svn:eol-style = native Modified: pivot/trunk/core/src/org/apache/pivot/util/VoteResult.java URL: http://svn.apache.org/viewvc/pivot/trunk/core/src/org/apache/pivot/util/VoteResult.java?rev=1913470&r1=1913469&r2=1913470&view=diff ============================================================================== --- pivot/trunk/core/src/org/apache/pivot/util/VoteResult.java (original) +++ pivot/trunk/core/src/org/apache/pivot/util/VoteResult.java Tue Oct 31 19:15:47 2023 @@ -1,65 +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.pivot.util; - -/** - * An object holding the result of a {@link Vote#tally} that can be - * used with a {@code forEach} or lambda expression, where the value - * used during the iteration must be final or effectively final. - */ -public class VoteResult { - /** The latest running vote tally. */ - private Vote result; - - /** - * Construct one of these and set the initial vote value to - * {@link Vote#APPROVE} (which is the usual starting point). - */ - public VoteResult() { - this(Vote.APPROVE); - } - - /** - * Construct one of these and set the initial vote to the given value. - * - * @param initialVote The initial vote value. - */ - public VoteResult(final Vote initialVote) { - result = initialVote; - } - - /** - * Tally the internal vote with the next vote in line. - * <p> The internal {@code Vote} is updated with the - * result of the vote tally. - * - * @param vote The next vote to tally against all the - * previous ones. - * @see Vote#tally - */ - public void tally(final Vote vote) { - result = result.tally(vote); - } - - /** - * @return The final tallied {@code Vote} value. - */ - public Vote get() { - return result; - } - -} +/* + * 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.pivot.util; + +/** + * An object holding the result of a {@link Vote#tally} that can be + * used with a {@code forEach} or lambda expression, where the value + * used during the iteration must be final or effectively final. + */ +public class VoteResult { + /** The latest running vote tally. */ + private Vote result; + + /** + * Construct one of these and set the initial vote value to + * {@link Vote#APPROVE} (which is the usual starting point). + */ + public VoteResult() { + this(Vote.APPROVE); + } + + /** + * Construct one of these and set the initial vote to the given value. + * + * @param initialVote The initial vote value. + */ + public VoteResult(final Vote initialVote) { + result = initialVote; + } + + /** + * Tally the internal vote with the next vote in line. + * <p> The internal {@code Vote} is updated with the + * result of the vote tally. + * + * @param vote The next vote to tally against all the + * previous ones. + * @see Vote#tally + */ + public void tally(final Vote vote) { + result = result.tally(vote); + } + + /** + * @return The final tallied {@code Vote} value. + */ + public Vote get() { + return result; + } + +} Propchange: pivot/trunk/core/src/org/apache/pivot/util/VoteResult.java ------------------------------------------------------------------------------ svn:eol-style = native Modified: pivot/trunk/core/src/org/apache/pivot/util/concurrent/SimpleExecutorService.java URL: http://svn.apache.org/viewvc/pivot/trunk/core/src/org/apache/pivot/util/concurrent/SimpleExecutorService.java?rev=1913470&r1=1913469&r2=1913470&view=diff ============================================================================== --- pivot/trunk/core/src/org/apache/pivot/util/concurrent/SimpleExecutorService.java (original) +++ pivot/trunk/core/src/org/apache/pivot/util/concurrent/SimpleExecutorService.java Tue Oct 31 19:15:47 2023 @@ -1,66 +1,66 @@ -/* - * 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.pivot.util.concurrent; - -import java.util.concurrent.AbstractExecutorService; -import java.util.concurrent.TimeUnit; - -/** - * An executor service that simply spawns a new thread on every call to {@link #execute}. - * <p> Note: this has been moved out of {@link Task} where it used to be used as the default - * executor service as a workaround for problems seen some time ago with - * {@link java.util.concurrent.Executors#newCachedThreadPool} when running as an applet. - * <p> The default for {@link Task}, {@link TaskSequence} and {@link TaskGroup} is now to - * use the system service, but this class may be used still as a workaround if problems - * are still seen (unlikely). - */ -public class SimpleExecutorService extends AbstractExecutorService { - private boolean shutdown = false; - - @Override - public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { - return true; - } - - @Override - public void shutdown() { - shutdownNow(); - } - - @Override - public java.util.List<Runnable> shutdownNow() { - shutdown = true; - return new java.util.ArrayList<>(); - } - - @Override - public boolean isShutdown() { - return shutdown; - } - - @Override - public boolean isTerminated() { - return isShutdown(); - } - - @Override - public void execute(Runnable command) { - Thread thread = new Thread(command); - thread.start(); - } -} - +/* + * 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.pivot.util.concurrent; + +import java.util.concurrent.AbstractExecutorService; +import java.util.concurrent.TimeUnit; + +/** + * An executor service that simply spawns a new thread on every call to {@link #execute}. + * <p> Note: this has been moved out of {@link Task} where it used to be used as the default + * executor service as a workaround for problems seen some time ago with + * {@link java.util.concurrent.Executors#newCachedThreadPool} when running as an applet. + * <p> The default for {@link Task}, {@link TaskSequence} and {@link TaskGroup} is now to + * use the system service, but this class may be used still as a workaround if problems + * are still seen (unlikely). + */ +public class SimpleExecutorService extends AbstractExecutorService { + private boolean shutdown = false; + + @Override + public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { + return true; + } + + @Override + public void shutdown() { + shutdownNow(); + } + + @Override + public java.util.List<Runnable> shutdownNow() { + shutdown = true; + return new java.util.ArrayList<>(); + } + + @Override + public boolean isShutdown() { + return shutdown; + } + + @Override + public boolean isTerminated() { + return isShutdown(); + } + + @Override + public void execute(Runnable command) { + Thread thread = new Thread(command); + thread.start(); + } +} + Propchange: pivot/trunk/core/src/org/apache/pivot/util/concurrent/SimpleExecutorService.java ------------------------------------------------------------------------------ svn:eol-style = native Modified: pivot/trunk/core/test/org/apache/pivot/collections/test/DictionaryTest.java URL: http://svn.apache.org/viewvc/pivot/trunk/core/test/org/apache/pivot/collections/test/DictionaryTest.java?rev=1913470&r1=1913469&r2=1913470&view=diff ============================================================================== --- pivot/trunk/core/test/org/apache/pivot/collections/test/DictionaryTest.java (original) +++ pivot/trunk/core/test/org/apache/pivot/collections/test/DictionaryTest.java Tue Oct 31 19:15:47 2023 @@ -1,71 +1,71 @@ -/* - * 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.pivot.collections.test; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; - -import java.awt.Color; -import org.apache.pivot.collections.HashMap; - - -public class DictionaryTest { - @Test - public void test() { - HashMap<String, Integer> map = new HashMap<>(); - map.put("one", 1); - map.put("two", 2); - map.put("three", 300); - assertEquals(map.getInt("one"), 1); - assertEquals(map.getInt("two"), 2); - assertEquals(map.getInt("three"), 300); - } - - @Test - public void boolTest() { - HashMap<String, Boolean> map = new HashMap<>(); - map.put("true", false); - map.put("false", true); - map.put("other", true); - assertEquals(map.getBoolean("true"), false); - assertEquals(map.getBoolean("false"), true); - assertEquals(map.getBoolean("other"), true); - } - - @Test - public void colorTest() { - HashMap<String, Color> map = new HashMap<>(); - map.put("black", Color.BLACK); - assertEquals(map.getColor("black"), Color.BLACK); - } - - @Test - public void anyTest() { - HashMap<String, Integer> map = new HashMap<>(); - map.put("one", 1); - map.put("two", 2); - map.put("three", 300); - - assertEquals(map.containsAny("a", "b", "one"), true); - Integer first = map.getFirst("c", "d", "two"); - assertEquals(first.intValue(), 2); - - assertEquals(map.containsAny("a", "b", "c", "d"), false); - assertEquals(map.getFirst("e", "f"), null); - } -} +/* + * 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.pivot.collections.test; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +import java.awt.Color; +import org.apache.pivot.collections.HashMap; + + +public class DictionaryTest { + @Test + public void test() { + HashMap<String, Integer> map = new HashMap<>(); + map.put("one", 1); + map.put("two", 2); + map.put("three", 300); + assertEquals(map.getInt("one"), 1); + assertEquals(map.getInt("two"), 2); + assertEquals(map.getInt("three"), 300); + } + + @Test + public void boolTest() { + HashMap<String, Boolean> map = new HashMap<>(); + map.put("true", false); + map.put("false", true); + map.put("other", true); + assertEquals(map.getBoolean("true"), false); + assertEquals(map.getBoolean("false"), true); + assertEquals(map.getBoolean("other"), true); + } + + @Test + public void colorTest() { + HashMap<String, Color> map = new HashMap<>(); + map.put("black", Color.BLACK); + assertEquals(map.getColor("black"), Color.BLACK); + } + + @Test + public void anyTest() { + HashMap<String, Integer> map = new HashMap<>(); + map.put("one", 1); + map.put("two", 2); + map.put("three", 300); + + assertEquals(map.containsAny("a", "b", "one"), true); + Integer first = map.getFirst("c", "d", "two"); + assertEquals(first.intValue(), 2); + + assertEquals(map.containsAny("a", "b", "c", "d"), false); + assertEquals(map.getFirst("e", "f"), null); + } +} Propchange: pivot/trunk/core/test/org/apache/pivot/collections/test/DictionaryTest.java ------------------------------------------------------------------------------ svn:eol-style = native Modified: pivot/trunk/core/test/org/apache/pivot/functional/monad/test/OptionTest.java URL: http://svn.apache.org/viewvc/pivot/trunk/core/test/org/apache/pivot/functional/monad/test/OptionTest.java?rev=1913470&r1=1913469&r2=1913470&view=diff ============================================================================== --- pivot/trunk/core/test/org/apache/pivot/functional/monad/test/OptionTest.java (original) +++ pivot/trunk/core/test/org/apache/pivot/functional/monad/test/OptionTest.java Tue Oct 31 19:15:47 2023 @@ -1,296 +1,296 @@ -/* - * 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.pivot.functional.monad.test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.util.Iterator; -import java.util.NoSuchElementException; -import java.util.Random; - -import org.apache.pivot.functional.monad.None; -import org.apache.pivot.functional.monad.Option; -import org.apache.pivot.functional.monad.OptionCompanion; -import org.apache.pivot.functional.monad.Some; -import org.junit.Test; - -public class OptionTest { - @Test - public void companionTest() { - OptionCompanion<Object> o = OptionCompanion.getInstance(); - assertNotNull(o); - } - - @Test(expected = NoSuchElementException.class) - public void companionNoneTest() { - OptionCompanion<Object> o = OptionCompanion.getInstance(); - assertNotNull(o); - - Option<Object> on = o.fromValue(null); - assertNotNull(on); - assertTrue(on instanceof None); - assertFalse(on.hasValue()); - System.out.println("companionNoneTest(), has value is " + on.hasValue()); - Object onValue = on.getValue(); // throw Exception here - assertTrue(onValue instanceof None); // never called - } - - @Test - public void companionObjectTest() { - OptionCompanion<Object> o = OptionCompanion.getInstance(); - assertNotNull(o); - - Option<Object> oo = o.fromValue(new StringBuilder("Hello")); - assertNotNull(oo); - assertTrue(oo instanceof Some); - assertTrue(oo.hasValue()); - Object ooValue = oo.getValue(); - assertTrue(ooValue instanceof StringBuilder); - System.out.println("companionObjectTest(), value stored is " + ooValue); - } - - @Test - public void companionStringTest() { - OptionCompanion<String> o = OptionCompanion.getInstance(); - assertNotNull(o); - - Option<String> os = o.fromValue("Hello"); - assertNotNull(os); - assertTrue(os instanceof Some); - assertTrue(os.hasValue()); - Object osValue = os.getValue(); - assertTrue(osValue instanceof String); - System.out.println("companionStringTest(), value stored is " + osValue); - } - - @Test - public void companionNumberTest() { - OptionCompanion<Number> o = OptionCompanion.getInstance(); - assertNotNull(o); - - Option<Number> on = o.fromValue(Double.valueOf(Math.PI)); - assertNotNull(on); - assertTrue(on instanceof Some); - assertTrue(on.hasValue()); - Object onValue = on.getValue(); - assertTrue(onValue instanceof Number); - assertTrue(onValue instanceof Double); - System.out.println("companionNumberTest(), value stored is " + onValue); - } - - @Test - public void companionRealUsageRandomTest() { - OptionCompanion<String> o = OptionCompanion.getInstance(); - assertNotNull(o); - - Option<String> os = null; - String value; - - // randomizing this test - Random randomGenerator = new Random(); - int randomInt = randomGenerator.nextInt(100); - - // store the value in the Option instance (Some if not null, otherwise None) - // note that try/catch block here are unnecessary, but probably near to a real-world usage - try { - // randomizing this test: - // for even numbers a value will be generated, - // but for odd numbers the value will be null so a call on it will throw a RuntimeException - if (randomInt % 2 == 0) { - value = String.valueOf(randomInt); - } else { - value = null; - } - - os = o.fromValue(value); - } catch (RuntimeException e) { - System.err.println("companionRealUsageRandomTest(), got RuntimeException " + e); - os = o.fromValue(null); - } - - // verify the value stored - System.out.println("companionRealUsageRandomTest(), stored element has a value " + os.hasValue()); - try { - String tsValue; // = os.getValue(); // this will throw a RuntimeException if os is a None - // System.out.println("companionRealUsageRandomTest(), value stored is " + tsValue); - - if (randomInt % 2 == 0) { - assertTrue(os instanceof Some); - assertTrue(os.hasValue()); - tsValue = os.getValue(); - System.out.println("companionRealUsageRandomTest(), value stored is " + tsValue); - assertTrue(tsValue != null); - } else { - assertTrue(os instanceof None); - assertFalse(os.hasValue()); - tsValue = os.getValue(); // will throw a RuntimeException when called in the case - assertTrue(tsValue == null); // never called - } - - } catch (RuntimeException e) { - System.err.println("companionRealUsageRandomTest(), got RuntimeException " + e); - assertFalse(os.hasValue()); - } - } - - @Test - public void optionSomeTest() { - // sample by direct instancing of Some/None classes, but discouraged - Option<String> os = null; - String osValue = null; - - // store the value in the Option instance (Some if not null, otherwise None) - os = new Some<>("Optional value"); - System.out.println("optionSomeTest(), instance variable is " + os); - assertTrue(os != null); - - // verify the value stored - System.out.println("optionSomeTest(), stored element has a value " + os.hasValue()); - assertTrue(os instanceof Some); - assertTrue(os.hasValue()); - osValue = os.getValue(); - System.out.println("optionSomeTest(), value stored is " + osValue); - assertTrue(osValue != null); - // test with alternative value - osValue = os.getValueOrElse("Alternative value"); - assertEquals("Optional value", osValue); - osValue = os.getValueOrNull(); - assertEquals("Optional value", osValue); - } - - @Test - public void optionNoneTest() { - // sample by direct instancing of Some/None classes, but discouraged - Option<String> os = null; - String tsValue = null; - - // store the value in the Option instance (Some if not null, otherwise None) - // os = new None<>(); // discouraged - os = None.getInstance(); // better - System.out.println("optionNoneTest(), instance variable is " + os); - assertTrue(os != null); - - // verify the value stored - System.out.println("optionNoneTest(), stored element has a value " + os.hasValue()); - assertTrue(os instanceof None); - assertFalse(os.hasValue()); - try { - tsValue = os.getValue(); // will throw a RuntimeException when called in the case - assertTrue(tsValue == null); // never called - } catch (RuntimeException e) { - System.err.println("optionNoneTest(), got RuntimeException " + e); - assertFalse(os.hasValue()); - } - // test with alternative value - tsValue = os.getValueOrElse("Alternative value"); - assertEquals("Alternative value", tsValue); - tsValue = os.getValueOrNull(); - assertEquals(null, tsValue); - } - - @Test - public void optionSomeEqualsTest() { - // sample by direct instancing of Some/None classes, but discouraged - Option<String> os1 = new Some<>("Optional value 1"); - System.out.println("optionSomeEqualsTest(), instance variable 1 is " + os1); - Option<String> os2 = new Some<>("Optional value 2"); - System.out.println("optionSomeEqualsTest(), instance variable 2 is " + os2); - - // verify the value stored - System.out.println("optionSomeEqualsTest(), two instances are not the same object " + (os1 != os2)); - assertTrue(os1 != os2); - } - - @Test - public void optionNoneEqualsTest() { - // sample by direct instancing of Some/None classes, but discouraged - None<String> on1 = None.getInstance(); - System.out.println("optionNoneEqualsTest(), instance variable 1 is " + on1); - None<String> on2 = None.getInstance(); - System.out.println("optionNoneEqualsTest(), instance variable 2 is " + on2); - - // verify the value stored - System.out.println("optionNoneEqualsTest(), two instances are the same object " + (on1 == on2)); - assertTrue(on1 == on2); - } - - @Test - public void optionSomeIteratorTest() { - // sample by direct instancing of Some/None classes, but discouraged - Option<String> os = new Some<>("Optional value"); - System.out.println("optionSomeIteratorTest(), instance variable is " + os); - - // iterate and verify on the value stored - Iterator<String> it = os.iterator(); - assertNotNull(it); - int i = 0; - while (it.hasNext()) { - String value = it.next(); - System.out.println("optionSomeIteratorTest(), value " + i + " from iterator is " + value); - assertNotNull(value); - assertEquals("Optional value", value); - i++; - } - assertEquals(i, 1); - - // another test - i = 0; - System.out.println("optionSomeIteratorTest(), another test"); - for (String value : os) { - System.out.println("optionSomeIteratorTest(), value " + i + " from iterator is " + value); - assertNotNull(value); - assertEquals("Optional value", value); - i++; - } - assertEquals(i, 1); - } - - @Test - public void optionNoneIteratorTest() { - // sample by direct instancing of Some/None classes, but discouraged - None<String> on = None.getInstance(); - System.out.println("optionNoneIteratorTest(), instance variable is " + on); - - // iterate and verify on the value stored - Iterator<String> it = on.iterator(); - assertNotNull(it); - int i = 0; - while (it.hasNext()) { - // never executed in this case - String value = it.next(); - System.out.println("optionNoneIteratorTest(), value " + i + " from iterator is " + value); - assertEquals(null, value); - i++; - } - assertEquals(i, 0); - - // another test - i = 0; - System.out.println("optionNoneIteratorTest(), another test"); - for (String value : on) { - // never executed in this case - System.out.println("optionNoneIteratorTest(), value " + i + " from iterator is " + value); - assertEquals(null, value); - i++; - } - assertEquals(i, 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.pivot.functional.monad.test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.util.Iterator; +import java.util.NoSuchElementException; +import java.util.Random; + +import org.apache.pivot.functional.monad.None; +import org.apache.pivot.functional.monad.Option; +import org.apache.pivot.functional.monad.OptionCompanion; +import org.apache.pivot.functional.monad.Some; +import org.junit.Test; + +public class OptionTest { + @Test + public void companionTest() { + OptionCompanion<Object> o = OptionCompanion.getInstance(); + assertNotNull(o); + } + + @Test(expected = NoSuchElementException.class) + public void companionNoneTest() { + OptionCompanion<Object> o = OptionCompanion.getInstance(); + assertNotNull(o); + + Option<Object> on = o.fromValue(null); + assertNotNull(on); + assertTrue(on instanceof None); + assertFalse(on.hasValue()); + System.out.println("companionNoneTest(), has value is " + on.hasValue()); + Object onValue = on.getValue(); // throw Exception here + assertTrue(onValue instanceof None); // never called + } + + @Test + public void companionObjectTest() { + OptionCompanion<Object> o = OptionCompanion.getInstance(); + assertNotNull(o); + + Option<Object> oo = o.fromValue(new StringBuilder("Hello")); + assertNotNull(oo); + assertTrue(oo instanceof Some); + assertTrue(oo.hasValue()); + Object ooValue = oo.getValue(); + assertTrue(ooValue instanceof StringBuilder); + System.out.println("companionObjectTest(), value stored is " + ooValue); + } + + @Test + public void companionStringTest() { + OptionCompanion<String> o = OptionCompanion.getInstance(); + assertNotNull(o); + + Option<String> os = o.fromValue("Hello"); + assertNotNull(os); + assertTrue(os instanceof Some); + assertTrue(os.hasValue()); + Object osValue = os.getValue(); + assertTrue(osValue instanceof String); + System.out.println("companionStringTest(), value stored is " + osValue); + } + + @Test + public void companionNumberTest() { + OptionCompanion<Number> o = OptionCompanion.getInstance(); + assertNotNull(o); + + Option<Number> on = o.fromValue(Double.valueOf(Math.PI)); + assertNotNull(on); + assertTrue(on instanceof Some); + assertTrue(on.hasValue()); + Object onValue = on.getValue(); + assertTrue(onValue instanceof Number); + assertTrue(onValue instanceof Double); + System.out.println("companionNumberTest(), value stored is " + onValue); + } + + @Test + public void companionRealUsageRandomTest() { + OptionCompanion<String> o = OptionCompanion.getInstance(); + assertNotNull(o); + + Option<String> os = null; + String value; + + // randomizing this test + Random randomGenerator = new Random(); + int randomInt = randomGenerator.nextInt(100); + + // store the value in the Option instance (Some if not null, otherwise None) + // note that try/catch block here are unnecessary, but probably near to a real-world usage + try { + // randomizing this test: + // for even numbers a value will be generated, + // but for odd numbers the value will be null so a call on it will throw a RuntimeException + if (randomInt % 2 == 0) { + value = String.valueOf(randomInt); + } else { + value = null; + } + + os = o.fromValue(value); + } catch (RuntimeException e) { + System.err.println("companionRealUsageRandomTest(), got RuntimeException " + e); + os = o.fromValue(null); + } + + // verify the value stored + System.out.println("companionRealUsageRandomTest(), stored element has a value " + os.hasValue()); + try { + String tsValue; // = os.getValue(); // this will throw a RuntimeException if os is a None + // System.out.println("companionRealUsageRandomTest(), value stored is " + tsValue); + + if (randomInt % 2 == 0) { + assertTrue(os instanceof Some); + assertTrue(os.hasValue()); + tsValue = os.getValue(); + System.out.println("companionRealUsageRandomTest(), value stored is " + tsValue); + assertTrue(tsValue != null); + } else { + assertTrue(os instanceof None); + assertFalse(os.hasValue()); + tsValue = os.getValue(); // will throw a RuntimeException when called in the case + assertTrue(tsValue == null); // never called + } + + } catch (RuntimeException e) { + System.err.println("companionRealUsageRandomTest(), got RuntimeException " + e); + assertFalse(os.hasValue()); + } + } + + @Test + public void optionSomeTest() { + // sample by direct instancing of Some/None classes, but discouraged + Option<String> os = null; + String osValue = null; + + // store the value in the Option instance (Some if not null, otherwise None) + os = new Some<>("Optional value"); + System.out.println("optionSomeTest(), instance variable is " + os); + assertTrue(os != null); + + // verify the value stored + System.out.println("optionSomeTest(), stored element has a value " + os.hasValue()); + assertTrue(os instanceof Some); + assertTrue(os.hasValue()); + osValue = os.getValue(); + System.out.println("optionSomeTest(), value stored is " + osValue); + assertTrue(osValue != null); + // test with alternative value + osValue = os.getValueOrElse("Alternative value"); + assertEquals("Optional value", osValue); + osValue = os.getValueOrNull(); + assertEquals("Optional value", osValue); + } + + @Test + public void optionNoneTest() { + // sample by direct instancing of Some/None classes, but discouraged + Option<String> os = null; + String tsValue = null; + + // store the value in the Option instance (Some if not null, otherwise None) + // os = new None<>(); // discouraged + os = None.getInstance(); // better + System.out.println("optionNoneTest(), instance variable is " + os); + assertTrue(os != null); + + // verify the value stored + System.out.println("optionNoneTest(), stored element has a value " + os.hasValue()); + assertTrue(os instanceof None); + assertFalse(os.hasValue()); + try { + tsValue = os.getValue(); // will throw a RuntimeException when called in the case + assertTrue(tsValue == null); // never called + } catch (RuntimeException e) { + System.err.println("optionNoneTest(), got RuntimeException " + e); + assertFalse(os.hasValue()); + } + // test with alternative value + tsValue = os.getValueOrElse("Alternative value"); + assertEquals("Alternative value", tsValue); + tsValue = os.getValueOrNull(); + assertEquals(null, tsValue); + } + + @Test + public void optionSomeEqualsTest() { + // sample by direct instancing of Some/None classes, but discouraged + Option<String> os1 = new Some<>("Optional value 1"); + System.out.println("optionSomeEqualsTest(), instance variable 1 is " + os1); + Option<String> os2 = new Some<>("Optional value 2"); + System.out.println("optionSomeEqualsTest(), instance variable 2 is " + os2); + + // verify the value stored + System.out.println("optionSomeEqualsTest(), two instances are not the same object " + (os1 != os2)); + assertTrue(os1 != os2); + } + + @Test + public void optionNoneEqualsTest() { + // sample by direct instancing of Some/None classes, but discouraged + None<String> on1 = None.getInstance(); + System.out.println("optionNoneEqualsTest(), instance variable 1 is " + on1); + None<String> on2 = None.getInstance(); + System.out.println("optionNoneEqualsTest(), instance variable 2 is " + on2); + + // verify the value stored + System.out.println("optionNoneEqualsTest(), two instances are the same object " + (on1 == on2)); + assertTrue(on1 == on2); + } + + @Test + public void optionSomeIteratorTest() { + // sample by direct instancing of Some/None classes, but discouraged + Option<String> os = new Some<>("Optional value"); + System.out.println("optionSomeIteratorTest(), instance variable is " + os); + + // iterate and verify on the value stored + Iterator<String> it = os.iterator(); + assertNotNull(it); + int i = 0; + while (it.hasNext()) { + String value = it.next(); + System.out.println("optionSomeIteratorTest(), value " + i + " from iterator is " + value); + assertNotNull(value); + assertEquals("Optional value", value); + i++; + } + assertEquals(i, 1); + + // another test + i = 0; + System.out.println("optionSomeIteratorTest(), another test"); + for (String value : os) { + System.out.println("optionSomeIteratorTest(), value " + i + " from iterator is " + value); + assertNotNull(value); + assertEquals("Optional value", value); + i++; + } + assertEquals(i, 1); + } + + @Test + public void optionNoneIteratorTest() { + // sample by direct instancing of Some/None classes, but discouraged + None<String> on = None.getInstance(); + System.out.println("optionNoneIteratorTest(), instance variable is " + on); + + // iterate and verify on the value stored + Iterator<String> it = on.iterator(); + assertNotNull(it); + int i = 0; + while (it.hasNext()) { + // never executed in this case + String value = it.next(); + System.out.println("optionNoneIteratorTest(), value " + i + " from iterator is " + value); + assertEquals(null, value); + i++; + } + assertEquals(i, 0); + + // another test + i = 0; + System.out.println("optionNoneIteratorTest(), another test"); + for (String value : on) { + // never executed in this case + System.out.println("optionNoneIteratorTest(), value " + i + " from iterator is " + value); + assertEquals(null, value); + i++; + } + assertEquals(i, 0); + } + +} Propchange: pivot/trunk/core/test/org/apache/pivot/functional/monad/test/OptionTest.java ------------------------------------------------------------------------------ svn:eol-style = native