Index: 3rdParty_sources/versions.txt
===================================================================
RCS file: /usr/local/cvsroot/3rdParty_sources/versions.txt,v
diff -u -r1.7 -r1.8
--- 3rdParty_sources/versions.txt 19 Dec 2012 16:50:01 -0000 1.7
+++ 3rdParty_sources/versions.txt 15 Mar 2013 09:55:56 -0000 1.8
@@ -11,7 +11,7 @@
Commons HttpClient 3.0
-Commons Lang 2.0
+Commons Lang 2.6
Commons IO 2.1
Index: 3rdParty_sources/commons-lang/org/apache/commons/lang/ArrayUtils.java
===================================================================
RCS file: /usr/local/cvsroot/3rdParty_sources/commons-lang/org/apache/commons/lang/ArrayUtils.java,v
diff -u -r1.1 -r1.2
--- 3rdParty_sources/commons-lang/org/apache/commons/lang/ArrayUtils.java 30 Aug 2012 16:24:42 -0000 1.1
+++ 3rdParty_sources/commons-lang/org/apache/commons/lang/ArrayUtils.java 15 Mar 2013 09:52:49 -0000 1.2
@@ -1,58 +1,22 @@
-/* ====================================================================
- * The Apache Software License, Version 1.1
+/*
+ * 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
*
- * Copyright (c) 2002-2003 The Apache Software Foundation. All rights
- * reserved.
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in
- * the documentation and/or other materials provided with the
- * distribution.
- *
- * 3. The end-user documentation included with the redistribution, if
- * any, must include the following acknowledgement:
- * "This product includes software developed by the
- * Apache Software Foundation (http://www.apache.org/)."
- * Alternately, this acknowledgement may appear in the software itself,
- * if and wherever such third-party acknowledgements normally appear.
- *
- * 4. The names "The Jakarta Project", "Commons", and "Apache Software
- * Foundation" must not be used to endorse or promote products derived
- * from this software without prior written permission. For written
- * permission, please contact apache@apache.org.
- *
- * 5. Products derived from this software may not be called "Apache"
- * nor may "Apache" appear in their names without prior written
- * permission of the Apache Software Foundation.
- *
- * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
- * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
- * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
- * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- * ====================================================================
- *
- * This software consists of voluntary contributions made by many
- * individuals on behalf of the Apache Software Foundation. For more
- * information on the Apache Software Foundation, please see
- *
Operations on arrays, primitive arrays (like int[]
) and primitive wrapper arrays
- * (like Integer[]
).
Operations on arrays, primitive arrays (like int[]
) and
+ * primitive wrapper arrays (like Integer[]
).
This class tries to handle null
input gracefully.
* An exception will not be thrown for a null
* array input. However, an Object array that contains a null
* element may throw an exception. Each method documents its behaviour.
#ThreadSafe#
+ * @author Apache Software Foundation * @author Moritz Petersen * @author Fredrik Westermarck * @author Nikolay Metchev * @author Matthew Hawthorne * @author Tim O'Brien * @author Pete Gieser * @author Gary Gregory + * @author Ashwin S + * @author Maarten Coene * @since 2.0 * @version $Id$ */ @@ -161,15 +128,23 @@ public static final Character[] EMPTY_CHARACTER_OBJECT_ARRAY = new Character[0]; /** + * The index value when an element is not found in a list or array:-1
.
+ * This value is returned by methods in this class and can also be used in comparisons with values returned by
+ * various method from {@link java.util.List}.
+ */
+ public static final int INDEX_NOT_FOUND = -1;
+
+ /**
* ArrayUtils instances should NOT be constructed in standard programming.
* Instead, the class should be used as ArrayUtils.clone(new int[] {2})
.
This constructor is public to permit tools that require a JavaBean instance * to operate.
*/ public ArrayUtils() { + super(); } - + // Basic methods handling multi-dimensional arrays //----------------------------------------------------------------------- /** @@ -179,11 +154,11 @@ * multi-dimensional primitive arrays. * *The format is that of Java source code, for example {a,b}
.
null
* @return a String representation of the array, '{}' if null array input
*/
- public static String toString(final Object array) {
+ public static String toString(Object array) {
return toString(array, "{}");
}
@@ -194,12 +169,12 @@
* multi-dimensional primitive arrays.
*
* The format is that of Java source code, for example {a,b}
.
null
* @param stringIfNull the String to return if the array is null
* @return a String representation of the array
- */
- public static String toString(final Object array, final String stringIfNull) {
+ */
+ public static String toString(Object array, String stringIfNull) {
if (array == null) {
return stringIfNull;
}
@@ -208,27 +183,27 @@
/**
* Get a hashCode for an array handling multi-dimensional arrays correctly.
- * + * *Multi-dimensional primitive arrays are also handled correctly by this method.
- * + * * @param array the array to get a hashCode for, may benull
* @return a hashCode for the array, zero if null array input
*/
- public static int hashCode(final Object array) {
+ public static int hashCode(Object array) {
return new HashCodeBuilder().append(array).toHashCode();
}
/**
* Compares two arrays, using equals(), handling multi-dimensional arrays * correctly.
- * + * *Multi-dimensional primitive arrays are also handled correctly by this method.
- * - * @param array1 the array to get a hashCode for, may benull
- * @param array2 the array to get a hashCode for, may be null
+ *
+ * @param array1 the left hand array to compare, may be null
+ * @param array2 the right hand array to compare, may be null
* @return true
if the arrays are equal
*/
- public static boolean isEquals(final Object array1, final Object array2) {
+ public static boolean isEquals(Object array1, Object array2) {
return new EqualsBuilder().append(array1, array2).isEquals();
}
@@ -248,18 +223,18 @@
* {"GREEN", "#00FF00"},
* {"BLUE", "#0000FF"}});
*
- *
- * This method returns null
if null
array input.
This method returns null
for a null
input array.
null
* @return a Map
that was created from the array
* @throws IllegalArgumentException if one element of this Array is
* itself an Array containing less then two elements
* @throws IllegalArgumentException if the array contains elements other
* than {@link java.util.Map.Entry} and an Array
*/
- public static Map toMap(final Object[] array) {
+ public static Map toMap(Object[] array) {
if (array == null) {
return null;
}
@@ -272,13 +247,13 @@
} else if (object instanceof Object[]) {
Object[] entry = (Object[]) object;
if (entry.length < 2) {
- throw new IllegalArgumentException("Array element " + i + ", '"
+ throw new IllegalArgumentException("Array element " + i + ", '"
+ object
+ "', has a length less than 2");
}
map.put(entry[0], entry[1]);
} else {
- throw new IllegalArgumentException("Array element " + i + ", '"
+ throw new IllegalArgumentException("Array element " + i + ", '"
+ object
+ "', is neither of type Map.Entry nor an Array");
}
@@ -292,15 +267,15 @@
* Shallow clones an array returning a typecast result and handling
* null
.
The objecs in the array are not cloned, thus there is no special + *
The objects in the array are not cloned, thus there is no special * handling for multi-dimensional arrays.
- * - *This method returns null
if null
array input.
This method returns null
for a null
input array.
null
* @return the cloned array, null
if null
input
*/
- public static Object[] clone(final Object[] array) {
+ public static Object[] clone(Object[] array) {
if (array == null) {
return null;
}
@@ -311,12 +286,12 @@
* Clones an array returning a typecast result and handling
* null
.
This method returns null
if null
array input.
This method returns null
for a null
input array.
null
* @return the cloned array, null
if null
input
*/
- public static long[] clone(final long[] array) {
+ public static long[] clone(long[] array) {
if (array == null) {
return null;
}
@@ -327,8 +302,8 @@
* Clones an array returning a typecast result and handling
* null
.
This method returns null
if null
array input.
This method returns null
for a null
input array.
null
* @return the cloned array, null
if null
input
*/
@@ -343,12 +318,12 @@
* Clones an array returning a typecast result and handling
* null
.
This method returns null
if null
array input.
This method returns null
for a null
input array.
null
* @return the cloned array, null
if null
input
*/
- public static short[] clone(final short[] array) {
+ public static short[] clone(short[] array) {
if (array == null) {
return null;
}
@@ -359,12 +334,12 @@
* Clones an array returning a typecast result and handling
* null
.
This method returns null
if null
array input.
This method returns null
for a null
input array.
null
* @return the cloned array, null
if null
input
*/
- public static char[] clone(final char[] array) {
+ public static char[] clone(char[] array) {
if (array == null) {
return null;
}
@@ -375,12 +350,12 @@
* Clones an array returning a typecast result and handling
* null
.
This method returns null
if null
array input.
This method returns null
for a null
input array.
null
* @return the cloned array, null
if null
input
*/
- public static byte[] clone(final byte[] array) {
+ public static byte[] clone(byte[] array) {
if (array == null) {
return null;
}
@@ -391,12 +366,12 @@
* Clones an array returning a typecast result and handling
* null
.
This method returns null
if null
array input.
This method returns null
for a null
input array.
null
* @return the cloned array, null
if null
input
*/
- public static double[] clone(final double[] array) {
+ public static double[] clone(double[] array) {
if (array == null) {
return null;
}
@@ -407,12 +382,12 @@
* Clones an array returning a typecast result and handling
* null
.
This method returns null
if null
array input.
This method returns null
for a null
input array.
null
* @return the cloned array, null
if null
input
*/
- public static float[] clone(final float[] array) {
+ public static float[] clone(float[] array) {
if (array == null) {
return null;
}
@@ -423,32 +398,755 @@
* Clones an array returning a typecast result and handling
* null
.
This method returns null
if null
array input.
This method returns null
for a null
input array.
null
* @return the cloned array, null
if null
input
*/
- public static boolean[] clone(final boolean[] array) {
+ public static boolean[] clone(boolean[] array) {
if (array == null) {
return null;
}
return (boolean[]) array.clone();
}
+ // nullToEmpty
+ //-----------------------------------------------------------------------
+ /**
+ * Defensive programming technique to change a null
+ * reference to an empty one.
This method returns an empty array for a null
input array.
As a memory optimizing technique an empty array passed in will be overridden with
+ * the empty public static
references in this class.
null
or empty
+ * @return the same array, public static
empty array if null
or empty input
+ * @since 2.5
+ */
+ public static Object[] nullToEmpty(Object[] array) {
+ if (array == null || array.length == 0) {
+ return EMPTY_OBJECT_ARRAY;
+ }
+ return array;
+ }
+
+ /**
+ * Defensive programming technique to change a null
+ * reference to an empty one.
This method returns an empty array for a null
input array.
As a memory optimizing technique an empty array passed in will be overridden with
+ * the empty public static
references in this class.
null
or empty
+ * @return the same array, public static
empty array if null
or empty input
+ * @since 2.5
+ */
+ public static String[] nullToEmpty(String[] array) {
+ if (array == null || array.length == 0) {
+ return EMPTY_STRING_ARRAY;
+ }
+ return array;
+ }
+
+ /**
+ * Defensive programming technique to change a null
+ * reference to an empty one.
This method returns an empty array for a null
input array.
As a memory optimizing technique an empty array passed in will be overridden with
+ * the empty public static
references in this class.
null
or empty
+ * @return the same array, public static
empty array if null
or empty input
+ * @since 2.5
+ */
+ public static long[] nullToEmpty(long[] array) {
+ if (array == null || array.length == 0) {
+ return EMPTY_LONG_ARRAY;
+ }
+ return array;
+ }
+
+ /**
+ * Defensive programming technique to change a null
+ * reference to an empty one.
This method returns an empty array for a null
input array.
As a memory optimizing technique an empty array passed in will be overridden with
+ * the empty public static
references in this class.
null
or empty
+ * @return the same array, public static
empty array if null
or empty input
+ * @since 2.5
+ */
+ public static int[] nullToEmpty(int[] array) {
+ if (array == null || array.length == 0) {
+ return EMPTY_INT_ARRAY;
+ }
+ return array;
+ }
+
+ /**
+ * Defensive programming technique to change a null
+ * reference to an empty one.
This method returns an empty array for a null
input array.
As a memory optimizing technique an empty array passed in will be overridden with
+ * the empty public static
references in this class.
null
or empty
+ * @return the same array, public static
empty array if null
or empty input
+ * @since 2.5
+ */
+ public static short[] nullToEmpty(short[] array) {
+ if (array == null || array.length == 0) {
+ return EMPTY_SHORT_ARRAY;
+ }
+ return array;
+ }
+
+ /**
+ * Defensive programming technique to change a null
+ * reference to an empty one.
This method returns an empty array for a null
input array.
As a memory optimizing technique an empty array passed in will be overridden with
+ * the empty public static
references in this class.
null
or empty
+ * @return the same array, public static
empty array if null
or empty input
+ * @since 2.5
+ */
+ public static char[] nullToEmpty(char[] array) {
+ if (array == null || array.length == 0) {
+ return EMPTY_CHAR_ARRAY;
+ }
+ return array;
+ }
+
+ /**
+ * Defensive programming technique to change a null
+ * reference to an empty one.
This method returns an empty array for a null
input array.
As a memory optimizing technique an empty array passed in will be overridden with
+ * the empty public static
references in this class.
null
or empty
+ * @return the same array, public static
empty array if null
or empty input
+ * @since 2.5
+ */
+ public static byte[] nullToEmpty(byte[] array) {
+ if (array == null || array.length == 0) {
+ return EMPTY_BYTE_ARRAY;
+ }
+ return array;
+ }
+
+ /**
+ * Defensive programming technique to change a null
+ * reference to an empty one.
This method returns an empty array for a null
input array.
As a memory optimizing technique an empty array passed in will be overridden with
+ * the empty public static
references in this class.
null
or empty
+ * @return the same array, public static
empty array if null
or empty input
+ * @since 2.5
+ */
+ public static double[] nullToEmpty(double[] array) {
+ if (array == null || array.length == 0) {
+ return EMPTY_DOUBLE_ARRAY;
+ }
+ return array;
+ }
+
+ /**
+ * Defensive programming technique to change a null
+ * reference to an empty one.
This method returns an empty array for a null
input array.
As a memory optimizing technique an empty array passed in will be overridden with
+ * the empty public static
references in this class.
null
or empty
+ * @return the same array, public static
empty array if null
or empty input
+ * @since 2.5
+ */
+ public static float[] nullToEmpty(float[] array) {
+ if (array == null || array.length == 0) {
+ return EMPTY_FLOAT_ARRAY;
+ }
+ return array;
+ }
+
+ /**
+ * Defensive programming technique to change a null
+ * reference to an empty one.
This method returns an empty array for a null
input array.
As a memory optimizing technique an empty array passed in will be overridden with
+ * the empty public static
references in this class.
null
or empty
+ * @return the same array, public static
empty array if null
or empty input
+ * @since 2.5
+ */
+ public static boolean[] nullToEmpty(boolean[] array) {
+ if (array == null || array.length == 0) {
+ return EMPTY_BOOLEAN_ARRAY;
+ }
+ return array;
+ }
+
+ /**
+ * Defensive programming technique to change a null
+ * reference to an empty one.
This method returns an empty array for a null
input array.
As a memory optimizing technique an empty array passed in will be overridden with
+ * the empty public static
references in this class.
null
or empty
+ * @return the same array, public static
empty array if null
or empty input
+ * @since 2.5
+ */
+ public static Long[] nullToEmpty(Long[] array) {
+ if (array == null || array.length == 0) {
+ return EMPTY_LONG_OBJECT_ARRAY;
+ }
+ return array;
+ }
+
+ /**
+ * Defensive programming technique to change a null
+ * reference to an empty one.
This method returns an empty array for a null
input array.
As a memory optimizing technique an empty array passed in will be overridden with
+ * the empty public static
references in this class.
null
or empty
+ * @return the same array, public static
empty array if null
or empty input
+ * @since 2.5
+ */
+ public static Integer[] nullToEmpty(Integer[] array) {
+ if (array == null || array.length == 0) {
+ return EMPTY_INTEGER_OBJECT_ARRAY;
+ }
+ return array;
+ }
+
+ /**
+ * Defensive programming technique to change a null
+ * reference to an empty one.
This method returns an empty array for a null
input array.
As a memory optimizing technique an empty array passed in will be overridden with
+ * the empty public static
references in this class.
null
or empty
+ * @return the same array, public static
empty array if null
or empty input
+ * @since 2.5
+ */
+ public static Short[] nullToEmpty(Short[] array) {
+ if (array == null || array.length == 0) {
+ return EMPTY_SHORT_OBJECT_ARRAY;
+ }
+ return array;
+ }
+
+ /**
+ * Defensive programming technique to change a null
+ * reference to an empty one.
This method returns an empty array for a null
input array.
As a memory optimizing technique an empty array passed in will be overridden with
+ * the empty public static
references in this class.
null
or empty
+ * @return the same array, public static
empty array if null
or empty input
+ * @since 2.5
+ */
+ public static Character[] nullToEmpty(Character[] array) {
+ if (array == null || array.length == 0) {
+ return EMPTY_CHARACTER_OBJECT_ARRAY;
+ }
+ return array;
+ }
+
+ /**
+ * Defensive programming technique to change a null
+ * reference to an empty one.
This method returns an empty array for a null
input array.
As a memory optimizing technique an empty array passed in will be overridden with
+ * the empty public static
references in this class.
null
or empty
+ * @return the same array, public static
empty array if null
or empty input
+ * @since 2.5
+ */
+ public static Byte[] nullToEmpty(Byte[] array) {
+ if (array == null || array.length == 0) {
+ return EMPTY_BYTE_OBJECT_ARRAY;
+ }
+ return array;
+ }
+
+ /**
+ * Defensive programming technique to change a null
+ * reference to an empty one.
This method returns an empty array for a null
input array.
As a memory optimizing technique an empty array passed in will be overridden with
+ * the empty public static
references in this class.
null
or empty
+ * @return the same array, public static
empty array if null
or empty input
+ * @since 2.5
+ */
+ public static Double[] nullToEmpty(Double[] array) {
+ if (array == null || array.length == 0) {
+ return EMPTY_DOUBLE_OBJECT_ARRAY;
+ }
+ return array;
+ }
+
+ /**
+ * Defensive programming technique to change a null
+ * reference to an empty one.
This method returns an empty array for a null
input array.
As a memory optimizing technique an empty array passed in will be overridden with
+ * the empty public static
references in this class.
null
or empty
+ * @return the same array, public static
empty array if null
or empty input
+ * @since 2.5
+ */
+ public static Float[] nullToEmpty(Float[] array) {
+ if (array == null || array.length == 0) {
+ return EMPTY_FLOAT_OBJECT_ARRAY;
+ }
+ return array;
+ }
+
+ /**
+ * Defensive programming technique to change a null
+ * reference to an empty one.
This method returns an empty array for a null
input array.
As a memory optimizing technique an empty array passed in will be overridden with
+ * the empty public static
references in this class.
null
or empty
+ * @return the same array, public static
empty array if null
or empty input
+ * @since 2.5
+ */
+ public static Boolean[] nullToEmpty(Boolean[] array) {
+ if (array == null || array.length == 0) {
+ return EMPTY_BOOLEAN_OBJECT_ARRAY;
+ }
+ return array;
+ }
+
+ // Subarrays
+ //-----------------------------------------------------------------------
+ /**
+ * Produces a new array containing the elements between + * the start and end indices.
+ * + *The start index is inclusive, the end index exclusive. + * Null array input produces null output.
+ * + *The component type of the subarray is always the same as
+ * that of the input array. Thus, if the input is an array of type
+ * Date
, the following usage is envisaged:
+ * Date[] someDates = (Date[])ArrayUtils.subarray(allDates, 2, 5); + *+ * + * @param array the array + * @param startIndexInclusive the starting index. Undervalue (<0) + * is promoted to 0, overvalue (>array.length) results + * in an empty array. + * @param endIndexExclusive elements up to endIndex-1 are present in the + * returned subarray. Undervalue (< startIndex) produces + * empty array, overvalue (>array.length) is demoted to + * array length. + * @return a new array containing the elements between + * the start and end indices. + * @since 2.1 + */ + public static Object[] subarray(Object[] array, int startIndexInclusive, int endIndexExclusive) { + if (array == null) { + return null; + } + if (startIndexInclusive < 0) { + startIndexInclusive = 0; + } + if (endIndexExclusive > array.length) { + endIndexExclusive = array.length; + } + int newSize = endIndexExclusive - startIndexInclusive; + Class type = array.getClass().getComponentType(); + if (newSize <= 0) { + return (Object[]) Array.newInstance(type, 0); + } + Object[] subarray = (Object[]) Array.newInstance(type, newSize); + System.arraycopy(array, startIndexInclusive, subarray, 0, newSize); + return subarray; + } + + /** + *
Produces a new long
array containing the elements
+ * between the start and end indices.
The start index is inclusive, the end index exclusive. + * Null array input produces null output.
+ * + * @param array the array + * @param startIndexInclusive the starting index. Undervalue (<0) + * is promoted to 0, overvalue (>array.length) results + * in an empty array. + * @param endIndexExclusive elements up to endIndex-1 are present in the + * returned subarray. Undervalue (< startIndex) produces + * empty array, overvalue (>array.length) is demoted to + * array length. + * @return a new array containing the elements between + * the start and end indices. + * @since 2.1 + */ + public static long[] subarray(long[] array, int startIndexInclusive, int endIndexExclusive) { + if (array == null) { + return null; + } + if (startIndexInclusive < 0) { + startIndexInclusive = 0; + } + if (endIndexExclusive > array.length) { + endIndexExclusive = array.length; + } + int newSize = endIndexExclusive - startIndexInclusive; + if (newSize <= 0) { + return EMPTY_LONG_ARRAY; + } + + long[] subarray = new long[newSize]; + System.arraycopy(array, startIndexInclusive, subarray, 0, newSize); + return subarray; + } + + /** + *Produces a new int
array containing the elements
+ * between the start and end indices.
The start index is inclusive, the end index exclusive. + * Null array input produces null output.
+ * + * @param array the array + * @param startIndexInclusive the starting index. Undervalue (<0) + * is promoted to 0, overvalue (>array.length) results + * in an empty array. + * @param endIndexExclusive elements up to endIndex-1 are present in the + * returned subarray. Undervalue (< startIndex) produces + * empty array, overvalue (>array.length) is demoted to + * array length. + * @return a new array containing the elements between + * the start and end indices. + * @since 2.1 + */ + public static int[] subarray(int[] array, int startIndexInclusive, int endIndexExclusive) { + if (array == null) { + return null; + } + if (startIndexInclusive < 0) { + startIndexInclusive = 0; + } + if (endIndexExclusive > array.length) { + endIndexExclusive = array.length; + } + int newSize = endIndexExclusive - startIndexInclusive; + if (newSize <= 0) { + return EMPTY_INT_ARRAY; + } + + int[] subarray = new int[newSize]; + System.arraycopy(array, startIndexInclusive, subarray, 0, newSize); + return subarray; + } + + /** + *Produces a new short
array containing the elements
+ * between the start and end indices.
The start index is inclusive, the end index exclusive. + * Null array input produces null output.
+ * + * @param array the array + * @param startIndexInclusive the starting index. Undervalue (<0) + * is promoted to 0, overvalue (>array.length) results + * in an empty array. + * @param endIndexExclusive elements up to endIndex-1 are present in the + * returned subarray. Undervalue (< startIndex) produces + * empty array, overvalue (>array.length) is demoted to + * array length. + * @return a new array containing the elements between + * the start and end indices. + * @since 2.1 + */ + public static short[] subarray(short[] array, int startIndexInclusive, int endIndexExclusive) { + if (array == null) { + return null; + } + if (startIndexInclusive < 0) { + startIndexInclusive = 0; + } + if (endIndexExclusive > array.length) { + endIndexExclusive = array.length; + } + int newSize = endIndexExclusive - startIndexInclusive; + if (newSize <= 0) { + return EMPTY_SHORT_ARRAY; + } + + short[] subarray = new short[newSize]; + System.arraycopy(array, startIndexInclusive, subarray, 0, newSize); + return subarray; + } + + /** + *Produces a new char
array containing the elements
+ * between the start and end indices.
The start index is inclusive, the end index exclusive. + * Null array input produces null output.
+ * + * @param array the array + * @param startIndexInclusive the starting index. Undervalue (<0) + * is promoted to 0, overvalue (>array.length) results + * in an empty array. + * @param endIndexExclusive elements up to endIndex-1 are present in the + * returned subarray. Undervalue (< startIndex) produces + * empty array, overvalue (>array.length) is demoted to + * array length. + * @return a new array containing the elements between + * the start and end indices. + * @since 2.1 + */ + public static char[] subarray(char[] array, int startIndexInclusive, int endIndexExclusive) { + if (array == null) { + return null; + } + if (startIndexInclusive < 0) { + startIndexInclusive = 0; + } + if (endIndexExclusive > array.length) { + endIndexExclusive = array.length; + } + int newSize = endIndexExclusive - startIndexInclusive; + if (newSize <= 0) { + return EMPTY_CHAR_ARRAY; + } + + char[] subarray = new char[newSize]; + System.arraycopy(array, startIndexInclusive, subarray, 0, newSize); + return subarray; + } + + /** + *Produces a new byte
array containing the elements
+ * between the start and end indices.
The start index is inclusive, the end index exclusive. + * Null array input produces null output.
+ * + * @param array the array + * @param startIndexInclusive the starting index. Undervalue (<0) + * is promoted to 0, overvalue (>array.length) results + * in an empty array. + * @param endIndexExclusive elements up to endIndex-1 are present in the + * returned subarray. Undervalue (< startIndex) produces + * empty array, overvalue (>array.length) is demoted to + * array length. + * @return a new array containing the elements between + * the start and end indices. + * @since 2.1 + */ + public static byte[] subarray(byte[] array, int startIndexInclusive, int endIndexExclusive) { + if (array == null) { + return null; + } + if (startIndexInclusive < 0) { + startIndexInclusive = 0; + } + if (endIndexExclusive > array.length) { + endIndexExclusive = array.length; + } + int newSize = endIndexExclusive - startIndexInclusive; + if (newSize <= 0) { + return EMPTY_BYTE_ARRAY; + } + + byte[] subarray = new byte[newSize]; + System.arraycopy(array, startIndexInclusive, subarray, 0, newSize); + return subarray; + } + + /** + *Produces a new double
array containing the elements
+ * between the start and end indices.
The start index is inclusive, the end index exclusive. + * Null array input produces null output.
+ * + * @param array the array + * @param startIndexInclusive the starting index. Undervalue (<0) + * is promoted to 0, overvalue (>array.length) results + * in an empty array. + * @param endIndexExclusive elements up to endIndex-1 are present in the + * returned subarray. Undervalue (< startIndex) produces + * empty array, overvalue (>array.length) is demoted to + * array length. + * @return a new array containing the elements between + * the start and end indices. + * @since 2.1 + */ + public static double[] subarray(double[] array, int startIndexInclusive, int endIndexExclusive) { + if (array == null) { + return null; + } + if (startIndexInclusive < 0) { + startIndexInclusive = 0; + } + if (endIndexExclusive > array.length) { + endIndexExclusive = array.length; + } + int newSize = endIndexExclusive - startIndexInclusive; + if (newSize <= 0) { + return EMPTY_DOUBLE_ARRAY; + } + + double[] subarray = new double[newSize]; + System.arraycopy(array, startIndexInclusive, subarray, 0, newSize); + return subarray; + } + + /** + *Produces a new float
array containing the elements
+ * between the start and end indices.
The start index is inclusive, the end index exclusive. + * Null array input produces null output.
+ * + * @param array the array + * @param startIndexInclusive the starting index. Undervalue (<0) + * is promoted to 0, overvalue (>array.length) results + * in an empty array. + * @param endIndexExclusive elements up to endIndex-1 are present in the + * returned subarray. Undervalue (< startIndex) produces + * empty array, overvalue (>array.length) is demoted to + * array length. + * @return a new array containing the elements between + * the start and end indices. + * @since 2.1 + */ + public static float[] subarray(float[] array, int startIndexInclusive, int endIndexExclusive) { + if (array == null) { + return null; + } + if (startIndexInclusive < 0) { + startIndexInclusive = 0; + } + if (endIndexExclusive > array.length) { + endIndexExclusive = array.length; + } + int newSize = endIndexExclusive - startIndexInclusive; + if (newSize <= 0) { + return EMPTY_FLOAT_ARRAY; + } + + float[] subarray = new float[newSize]; + System.arraycopy(array, startIndexInclusive, subarray, 0, newSize); + return subarray; + } + + /** + *Produces a new boolean
array containing the elements
+ * between the start and end indices.
The start index is inclusive, the end index exclusive. + * Null array input produces null output.
+ * + * @param array the array + * @param startIndexInclusive the starting index. Undervalue (<0) + * is promoted to 0, overvalue (>array.length) results + * in an empty array. + * @param endIndexExclusive elements up to endIndex-1 are present in the + * returned subarray. Undervalue (< startIndex) produces + * empty array, overvalue (>array.length) is demoted to + * array length. + * @return a new array containing the elements between + * the start and end indices. + * @since 2.1 + */ + public static boolean[] subarray(boolean[] array, int startIndexInclusive, int endIndexExclusive) { + if (array == null) { + return null; + } + if (startIndexInclusive < 0) { + startIndexInclusive = 0; + } + if (endIndexExclusive > array.length) { + endIndexExclusive = array.length; + } + int newSize = endIndexExclusive - startIndexInclusive; + if (newSize <= 0) { + return EMPTY_BOOLEAN_ARRAY; + } + + boolean[] subarray = new boolean[newSize]; + System.arraycopy(array, startIndexInclusive, subarray, 0, newSize); + return subarray; + } + // Is same length //----------------------------------------------------------------------- /** *Checks whether two arrays are the same length, treating
* null
arrays as length 0
.
*
*
Any multi-dimensional aspects of the arrays are ignored.
- * + * * @param array1 the first array, may benull
* @param array2 the second array, may be null
* @return true
if length of arrays matches, treating
* null
as an empty array
- */
- public static boolean isSameLength(final Object[] array1, final Object[] array2) {
+ */
+ public static boolean isSameLength(Object[] array1, Object[] array2) {
if ((array1 == null && array2 != null && array2.length > 0) ||
(array2 == null && array1 != null && array1.length > 0) ||
(array1 != null && array2 != null && array1.length != array2.length)) {
@@ -460,13 +1158,13 @@
/**
* Checks whether two arrays are the same length, treating
* null
arrays as length 0
.
null
* @param array2 the second array, may be null
* @return true
if length of arrays matches, treating
* null
as an empty array
*/
- public static boolean isSameLength(final long[] array1, final long[] array2) {
+ public static boolean isSameLength(long[] array1, long[] array2) {
if ((array1 == null && array2 != null && array2.length > 0) ||
(array2 == null && array1 != null && array1.length > 0) ||
(array1 != null && array2 != null && array1.length != array2.length)) {
@@ -478,13 +1176,13 @@
/**
* Checks whether two arrays are the same length, treating
* null
arrays as length 0
.
null
* @param array2 the second array, may be null
* @return true
if length of arrays matches, treating
* null
as an empty array
*/
- public static boolean isSameLength(final int[] array1, final int[] array2) {
+ public static boolean isSameLength(int[] array1, int[] array2) {
if ((array1 == null && array2 != null && array2.length > 0) ||
(array2 == null && array1 != null && array1.length > 0) ||
(array1 != null && array2 != null && array1.length != array2.length)) {
@@ -496,13 +1194,13 @@
/**
* Checks whether two arrays are the same length, treating
* null
arrays as length 0
.
null
* @param array2 the second array, may be null
* @return true
if length of arrays matches, treating
* null
as an empty array
*/
- public static boolean isSameLength(final short[] array1, final short[] array2) {
+ public static boolean isSameLength(short[] array1, short[] array2) {
if ((array1 == null && array2 != null && array2.length > 0) ||
(array2 == null && array1 != null && array1.length > 0) ||
(array1 != null && array2 != null && array1.length != array2.length)) {
@@ -514,13 +1212,13 @@
/**
* Checks whether two arrays are the same length, treating
* null
arrays as length 0
.
null
* @param array2 the second array, may be null
* @return true
if length of arrays matches, treating
* null
as an empty array
*/
- public static boolean isSameLength(final char[] array1, final char[] array2) {
+ public static boolean isSameLength(char[] array1, char[] array2) {
if ((array1 == null && array2 != null && array2.length > 0) ||
(array2 == null && array1 != null && array1.length > 0) ||
(array1 != null && array2 != null && array1.length != array2.length)) {
@@ -532,13 +1230,13 @@
/**
* Checks whether two arrays are the same length, treating
* null
arrays as length 0
.
null
* @param array2 the second array, may be null
* @return true
if length of arrays matches, treating
* null
as an empty array
*/
- public static boolean isSameLength(final byte[] array1, final byte[] array2) {
+ public static boolean isSameLength(byte[] array1, byte[] array2) {
if ((array1 == null && array2 != null && array2.length > 0) ||
(array2 == null && array1 != null && array1.length > 0) ||
(array1 != null && array2 != null && array1.length != array2.length)) {
@@ -550,13 +1248,13 @@
/**
* Checks whether two arrays are the same length, treating
* null
arrays as length 0
.
null
* @param array2 the second array, may be null
* @return true
if length of arrays matches, treating
* null
as an empty array
*/
- public static boolean isSameLength(final double[] array1, final double[] array2) {
+ public static boolean isSameLength(double[] array1, double[] array2) {
if ((array1 == null && array2 != null && array2.length > 0) ||
(array2 == null && array1 != null && array1.length > 0) ||
(array1 != null && array2 != null && array1.length != array2.length)) {
@@ -568,13 +1266,13 @@
/**
* Checks whether two arrays are the same length, treating
* null
arrays as length 0
.
null
* @param array2 the second array, may be null
* @return true
if length of arrays matches, treating
* null
as an empty array
*/
- public static boolean isSameLength(final float[] array1, final float[] array2) {
+ public static boolean isSameLength(float[] array1, float[] array2) {
if ((array1 == null && array2 != null && array2.length > 0) ||
(array2 == null && array1 != null && array1.length > 0) ||
(array1 != null && array2 != null && array1.length != array2.length)) {
@@ -586,13 +1284,13 @@
/**
* Checks whether two arrays are the same length, treating
* null
arrays as length 0
.
null
* @param array2 the second array, may be null
* @return true
if length of arrays matches, treating
* null
as an empty array
*/
- public static boolean isSameLength(final boolean[] array1, final boolean[] array2) {
+ public static boolean isSameLength(boolean[] array1, boolean[] array2) {
if ((array1 == null && array2 != null && array2.length > 0) ||
(array2 == null && array1 != null && array1.length > 0) ||
(array1 != null && array2 != null && array1.length != array2.length)) {
@@ -601,16 +1299,44 @@
return true;
}
+ //-----------------------------------------------------------------------
/**
+ * Returns the length of the specified array.
+ * This method can deal with Object
arrays and with primitive arrays.
If the input array is null
, 0
is returned.
+ * ArrayUtils.getLength(null) = 0 + * ArrayUtils.getLength([]) = 0 + * ArrayUtils.getLength([null]) = 1 + * ArrayUtils.getLength([true, false]) = 2 + * ArrayUtils.getLength([1, 2, 3]) = 3 + * ArrayUtils.getLength(["a", "b", "c"]) = 3 + *+ * + * @param array the array to retrieve the length from, may be null + * @return The length of the array, or
0
if the array is null
+ * @throws IllegalArgumentException if the object arguement is not an array.
+ * @since 2.1
+ */
+ public static int getLength(Object array) {
+ if (array == null) {
+ return 0;
+ }
+ return Array.getLength(array);
+ }
+
+ /**
* Checks whether two arrays are the same type taking into account * multi-dimensional arrays.
- * + * * @param array1 the first array, must not benull
* @param array2 the second array, must not be null
* @return true
if type of arrays matches
* @throws IllegalArgumentException if either array is null
- */
- public static boolean isSameType(final Object array1, final Object array2) {
+ */
+ public static boolean isSameType(Object array1, Object array2) {
if (array1 == null || array2 == null) {
throw new IllegalArgumentException("The Array must not be null");
}
@@ -619,16 +1345,16 @@
// Reverse
//-----------------------------------------------------------------------
- /**
+ /**
* Reverses the order of the given array.
* *There is no special handling for multi-dimensional arrays.
* - *This method does nothing if null
array input.
This method does nothing for a null
input array.
null
*/
- public static void reverse(final Object[] array) {
+ public static void reverse(Object[] array) {
if (array == null) {
return;
}
@@ -646,12 +1372,12 @@
/**
* Reverses the order of the given array.
- * - *This method does nothing if null
array input.
This method does nothing for a null
input array.
null
*/
- public static void reverse(final long[] array) {
+ public static void reverse(long[] array) {
if (array == null) {
return;
}
@@ -669,12 +1395,12 @@
/**
* Reverses the order of the given array.
- * - *This method does nothing if null
array input.
This method does nothing for a null
input array.
null
*/
- public static void reverse(final int[] array) {
+ public static void reverse(int[] array) {
if (array == null) {
return;
}
@@ -692,12 +1418,12 @@
/**
* Reverses the order of the given array.
- * - *This method does nothing if null
array input.
This method does nothing for a null
input array.
null
*/
- public static void reverse(final short[] array) {
+ public static void reverse(short[] array) {
if (array == null) {
return;
}
@@ -715,12 +1441,12 @@
/**
* Reverses the order of the given array.
- * - *This method does nothing if null
array input.
This method does nothing for a null
input array.
null
*/
- public static void reverse(final char[] array) {
+ public static void reverse(char[] array) {
if (array == null) {
return;
}
@@ -738,12 +1464,12 @@
/**
* Reverses the order of the given array.
- * - *This method does nothing if null
array input.
This method does nothing for a null
input array.
null
*/
- public static void reverse(final byte[] array) {
+ public static void reverse(byte[] array) {
if (array == null) {
return;
}
@@ -761,12 +1487,12 @@
/**
* Reverses the order of the given array.
- * - *This method does nothing if null
array input.
This method does nothing for a null
input array.
null
*/
- public static void reverse(final double[] array) {
+ public static void reverse(double[] array) {
if (array == null) {
return;
}
@@ -784,12 +1510,12 @@
/**
* Reverses the order of the given array.
- * - *This method does nothing if null
array input.
This method does nothing for a null
input array.
null
*/
- public static void reverse(final float[] array) {
+ public static void reverse(float[] array) {
if (array == null) {
return;
}
@@ -807,12 +1533,12 @@
/**
* Reverses the order of the given array.
- * - *This method does nothing if null
array input.
This method does nothing for a null
input array.
null
*/
- public static void reverse(final boolean[] array) {
+ public static void reverse(boolean[] array) {
if (array == null) {
return;
}
@@ -830,40 +1556,40 @@
// IndexOf search
// ----------------------------------------------------------------------
-
+
// Object IndexOf
//-----------------------------------------------------------------------
/**
- * Find the index of the given object in the array.
+ *Finds the index of the given object in the array.
* - *This method returns -1
if null
array input.
This method returns {@link #INDEX_NOT_FOUND} (-1
) for a null
input array.
null
* @param objectToFind the object to find, may be null
- * @return the index of the object within the array,
- * -1
if not found or null
array input
+ * @return the index of the object within the array,
+ * {@link #INDEX_NOT_FOUND} (-1
) if not found or null
array input
*/
- public static int indexOf(final Object[] array, final Object objectToFind) {
+ public static int indexOf(Object[] array, Object objectToFind) {
return indexOf(array, objectToFind, 0);
}
/**
- * Find the index of the given object in the array starting at the given index.
+ *Finds the index of the given object in the array starting at the given index.
* - *This method returns -1
if null
array input.
This method returns {@link #INDEX_NOT_FOUND} (-1
) for a null
input array.
A negative startIndex is treated as zero. A startIndex larger than the array
- * length will return -1
.
-1
).
+ *
* @param array the array to search through for the object, may be null
* @param objectToFind the object to find, may be null
* @param startIndex the index to start searching at
* @return the index of the object within the array starting at the index,
- * -1
if not found or null
array input
+ * {@link #INDEX_NOT_FOUND} (-1
) if not found or null
array input
*/
- public static int indexOf(final Object[] array, final Object objectToFind, int startIndex) {
+ public static int indexOf(Object[] array, Object objectToFind, int startIndex) {
if (array == null) {
- return -1;
+ return INDEX_NOT_FOUND;
}
if (startIndex < 0) {
startIndex = 0;
@@ -874,50 +1600,50 @@
return i;
}
}
- } else {
+ } else if (array.getClass().getComponentType().isInstance(objectToFind)) {
for (int i = startIndex; i < array.length; i++) {
if (objectToFind.equals(array[i])) {
return i;
}
}
}
- return -1;
+ return INDEX_NOT_FOUND;
}
/**
- * Find the last index of the given object within the array.
+ *Finds the last index of the given object within the array.
* - *This method returns -1
if null
array input.
This method returns {@link #INDEX_NOT_FOUND} (-1
) for a null
input array.
null
* @param objectToFind the object to find, may be null
* @return the last index of the object within the array,
- * -1
if not found or null
array input
+ * {@link #INDEX_NOT_FOUND} (-1
) if not found or null
array input
*/
- public static int lastIndexOf(final Object[] array, final Object objectToFind) {
+ public static int lastIndexOf(Object[] array, Object objectToFind) {
return lastIndexOf(array, objectToFind, Integer.MAX_VALUE);
}
/**
- * Find the last index of the given object in the array starting at the given index.
+ *Finds the last index of the given object in the array starting at the given index.
* - *This method returns -1
if null
array input.
This method returns {@link #INDEX_NOT_FOUND} (-1
) for a null
input array.
A negative startIndex will return -1
. A startIndex larger than
+ *
A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1
). A startIndex larger than
* the array length will search from the end of the array.
null
* @param objectToFind the object to find, may be null
* @param startIndex the start index to travers backwards from
* @return the last index of the object within the array,
- * -1
if not found or null
array input
+ * {@link #INDEX_NOT_FOUND} (-1
) if not found or null
array input
*/
- public static int lastIndexOf(final Object[] array, final Object objectToFind, int startIndex) {
+ public static int lastIndexOf(Object[] array, Object objectToFind, int startIndex) {
if (array == null) {
- return -1;
+ return INDEX_NOT_FOUND;
}
if (startIndex < 0) {
- return -1;
+ return INDEX_NOT_FOUND;
} else if (startIndex >= array.length) {
startIndex = array.length - 1;
}
@@ -927,62 +1653,62 @@
return i;
}
}
- } else {
+ } else if (array.getClass().getComponentType().isInstance(objectToFind)) {
for (int i = startIndex; i >= 0; i--) {
if (objectToFind.equals(array[i])) {
return i;
}
}
}
- return -1;
+ return INDEX_NOT_FOUND;
}
/**
* Checks if the object is in the given array.
* *The method returns false
if a null
array is passed in.
true
if the array contains the object
*/
- public static boolean contains(final Object[] array, final Object objectToFind) {
- return (indexOf(array, objectToFind) != -1);
+ public static boolean contains(Object[] array, Object objectToFind) {
+ return indexOf(array, objectToFind) != INDEX_NOT_FOUND;
}
// long IndexOf
//-----------------------------------------------------------------------
/**
- * Find the index of the given value in the array.
+ *Finds the index of the given value in the array.
* - *This method returns -1
if null
array input.
This method returns {@link #INDEX_NOT_FOUND} (-1
) for a null
input array.
null
* @param valueToFind the value to find
* @return the index of the value within the array,
- * -1
if not found or null
array input
+ * {@link #INDEX_NOT_FOUND} (-1
) if not found or null
array input
*/
- public static int indexOf(final long[] array, final long valueToFind) {
+ public static int indexOf(long[] array, long valueToFind) {
return indexOf(array, valueToFind, 0);
}
/**
- * Find the index of the given value in the array starting at the given index.
+ *Finds the index of the given value in the array starting at the given index.
* - *This method returns -1
if null
array input.
This method returns {@link #INDEX_NOT_FOUND} (-1
) for a null
input array.
A negative startIndex is treated as zero. A startIndex larger than the array - * length will return -1.
- * + * length will return {@link #INDEX_NOT_FOUND} (-1
).
+ *
* @param array the array to search through for the object, may be null
* @param valueToFind the value to find
* @param startIndex the index to start searching at
* @return the index of the value within the array,
- * -1
if not found or null
array input
+ * {@link #INDEX_NOT_FOUND} (-1
) if not found or null
array input
*/
- public static int indexOf(final long[] array, final long valueToFind, int startIndex) {
+ public static int indexOf(long[] array, long valueToFind, int startIndex) {
if (array == null) {
- return -1;
+ return INDEX_NOT_FOUND;
}
if (startIndex < 0) {
startIndex = 0;
@@ -992,43 +1718,43 @@
return i;
}
}
- return -1;
+ return INDEX_NOT_FOUND;
}
/**
- * Find the last index of the given value within the array.
+ *Finds the last index of the given value within the array.
* - *This method returns -1
if null
array input.
This method returns {@link #INDEX_NOT_FOUND} (-1
) for a null
input array.
null
* @param valueToFind the object to find
* @return the last index of the value within the array,
- * -1
if not found or null
array input
+ * {@link #INDEX_NOT_FOUND} (-1
) if not found or null
array input
*/
- public static int lastIndexOf(final long[] array, final long valueToFind) {
+ public static int lastIndexOf(long[] array, long valueToFind) {
return lastIndexOf(array, valueToFind, Integer.MAX_VALUE);
}
/**
- * Find the last index of the given value in the array starting at the given index.
+ *Finds the last index of the given value in the array starting at the given index.
* - *This method returns -1
if null
array input.
This method returns {@link #INDEX_NOT_FOUND} (-1
) for a null
input array.
A negative startIndex will return -1. A startIndex larger than the array - * length will search from the end of the array.
- * + *A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1
). A startIndex larger than the
+ * array length will search from the end of the array.
null
* @param valueToFind the value to find
* @param startIndex the start index to travers backwards from
* @return the last index of the value within the array,
- * -1
if not found or null
array input
+ * {@link #INDEX_NOT_FOUND} (-1
) if not found or null
array input
*/
- public static int lastIndexOf(final long[] array, final long valueToFind, int startIndex) {
+ public static int lastIndexOf(long[] array, long valueToFind, int startIndex) {
if (array == null) {
- return -1;
+ return INDEX_NOT_FOUND;
}
if (startIndex < 0) {
- return -1;
+ return INDEX_NOT_FOUND;
} else if (startIndex >= array.length) {
startIndex = array.length - 1;
}
@@ -1037,55 +1763,55 @@
return i;
}
}
- return -1;
+ return INDEX_NOT_FOUND;
}
/**
* Checks if the value is in the given array.
* *The method returns false
if a null
array is passed in.
true
if the array contains the object
*/
- public static boolean contains(final long[] array, final long valueToFind) {
- return (indexOf(array, valueToFind) != -1);
+ public static boolean contains(long[] array, long valueToFind) {
+ return indexOf(array, valueToFind) != INDEX_NOT_FOUND;
}
// int IndexOf
//-----------------------------------------------------------------------
/**
- * Find the index of the given value in the array.
+ *Finds the index of the given value in the array.
* - *This method returns -1
if null
array input.
This method returns {@link #INDEX_NOT_FOUND} (-1
) for a null
input array.
null
* @param valueToFind the value to find
* @return the index of the value within the array,
- * -1
if not found or null
array input
+ * {@link #INDEX_NOT_FOUND} (-1
) if not found or null
array input
*/
- public static int indexOf(final int[] array, final int valueToFind) {
+ public static int indexOf(int[] array, int valueToFind) {
return indexOf(array, valueToFind, 0);
}
/**
- * Find the index of the given value in the array starting at the given index.
+ *Finds the index of the given value in the array starting at the given index.
* - *This method returns -1
if null
array input.
This method returns {@link #INDEX_NOT_FOUND} (-1
) for a null
input array.
A negative startIndex is treated as zero. A startIndex larger than the array - * length will return -1.
- * + * length will return {@link #INDEX_NOT_FOUND} (-1
).
+ *
* @param array the array to search through for the object, may be null
* @param valueToFind the value to find
* @param startIndex the index to start searching at
* @return the index of the value within the array,
- * -1
if not found or null
array input
+ * {@link #INDEX_NOT_FOUND} (-1
) if not found or null
array input
*/
- public static int indexOf(final int[] array, final int valueToFind, int startIndex) {
+ public static int indexOf(int[] array, int valueToFind, int startIndex) {
if (array == null) {
- return -1;
+ return INDEX_NOT_FOUND;
}
if (startIndex < 0) {
startIndex = 0;
@@ -1095,43 +1821,43 @@
return i;
}
}
- return -1;
+ return INDEX_NOT_FOUND;
}
/**
- * Find the last index of the given value within the array.
+ *Finds the last index of the given value within the array.
* - *This method returns -1
if null
array input.
This method returns {@link #INDEX_NOT_FOUND} (-1
) for a null
input array.
null
* @param valueToFind the object to find
* @return the last index of the value within the array,
- * -1
if not found or null
array input
+ * {@link #INDEX_NOT_FOUND} (-1
) if not found or null
array input
*/
- public static int lastIndexOf(final int[] array, final int valueToFind) {
+ public static int lastIndexOf(int[] array, int valueToFind) {
return lastIndexOf(array, valueToFind, Integer.MAX_VALUE);
}
/**
- * Find the last index of the given value in the array starting at the given index.
+ *Finds the last index of the given value in the array starting at the given index.
* - *This method returns -1
if null
array input.
This method returns {@link #INDEX_NOT_FOUND} (-1
) for a null
input array.
A negative startIndex will return -1. A startIndex larger than the array - * length will search from the end of the array.
- * + *A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1
). A startIndex larger than the
+ * array length will search from the end of the array.
null
* @param valueToFind the value to find
* @param startIndex the start index to travers backwards from
* @return the last index of the value within the array,
- * -1
if not found or null
array input
+ * {@link #INDEX_NOT_FOUND} (-1
) if not found or null
array input
*/
- public static int lastIndexOf(final int[] array, final int valueToFind, int startIndex) {
+ public static int lastIndexOf(int[] array, int valueToFind, int startIndex) {
if (array == null) {
- return -1;
+ return INDEX_NOT_FOUND;
}
if (startIndex < 0) {
- return -1;
+ return INDEX_NOT_FOUND;
} else if (startIndex >= array.length) {
startIndex = array.length - 1;
}
@@ -1140,55 +1866,55 @@
return i;
}
}
- return -1;
+ return INDEX_NOT_FOUND;
}
/**
* Checks if the value is in the given array.
* *The method returns false
if a null
array is passed in.
true
if the array contains the object
*/
- public static boolean contains(final int[] array, final int valueToFind) {
- return (indexOf(array, valueToFind) != -1);
+ public static boolean contains(int[] array, int valueToFind) {
+ return indexOf(array, valueToFind) != INDEX_NOT_FOUND;
}
// short IndexOf
//-----------------------------------------------------------------------
/**
- * Find the index of the given value in the array.
+ *Finds the index of the given value in the array.
* - *This method returns -1
if null
array input.
This method returns {@link #INDEX_NOT_FOUND} (-1
) for a null
input array.
null
* @param valueToFind the value to find
* @return the index of the value within the array,
- * -1
if not found or null
array input
+ * {@link #INDEX_NOT_FOUND} (-1
) if not found or null
array input
*/
- public static int indexOf(final short[] array, final short valueToFind) {
+ public static int indexOf(short[] array, short valueToFind) {
return indexOf(array, valueToFind, 0);
}
/**
- * Find the index of the given value in the array starting at the given index.
+ *Finds the index of the given value in the array starting at the given index.
* - *This method returns -1
if null
array input.
This method returns {@link #INDEX_NOT_FOUND} (-1
) for a null
input array.
A negative startIndex is treated as zero. A startIndex larger than the array - * length will return -1.
- * + * length will return {@link #INDEX_NOT_FOUND} (-1
).
+ *
* @param array the array to search through for the object, may be null
* @param valueToFind the value to find
* @param startIndex the index to start searching at
* @return the index of the value within the array,
- * -1
if not found or null
array input
+ * {@link #INDEX_NOT_FOUND} (-1
) if not found or null
array input
*/
- public static int indexOf(final short[] array, final short valueToFind, int startIndex) {
+ public static int indexOf(short[] array, short valueToFind, int startIndex) {
if (array == null) {
- return -1;
+ return INDEX_NOT_FOUND;
}
if (startIndex < 0) {
startIndex = 0;
@@ -1198,43 +1924,43 @@
return i;
}
}
- return -1;
+ return INDEX_NOT_FOUND;
}
/**
- * Find the last index of the given value within the array.
+ *Finds the last index of the given value within the array.
* - *This method returns -1
if null
array input.
This method returns {@link #INDEX_NOT_FOUND} (-1
) for a null
input array.
null
* @param valueToFind the object to find
* @return the last index of the value within the array,
- * -1
if not found or null
array input
+ * {@link #INDEX_NOT_FOUND} (-1
) if not found or null
array input
*/
- public static int lastIndexOf(final short[] array, final short valueToFind) {
+ public static int lastIndexOf(short[] array, short valueToFind) {
return lastIndexOf(array, valueToFind, Integer.MAX_VALUE);
}
/**
- * Find the last index of the given value in the array starting at the given index.
+ *Finds the last index of the given value in the array starting at the given index.
* - *This method returns -1
if null
array input.
This method returns {@link #INDEX_NOT_FOUND} (-1
) for a null
input array.
A negative startIndex will return -1. A startIndex larger than the array - * length will search from the end of the array.
- * + *A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1
). A startIndex larger than the
+ * array length will search from the end of the array.
null
* @param valueToFind the value to find
* @param startIndex the start index to travers backwards from
* @return the last index of the value within the array,
- * -1
if not found or null
array input
+ * {@link #INDEX_NOT_FOUND} (-1
) if not found or null
array input
*/
- public static int lastIndexOf(final short[] array, final short valueToFind, int startIndex) {
+ public static int lastIndexOf(short[] array, short valueToFind, int startIndex) {
if (array == null) {
- return -1;
+ return INDEX_NOT_FOUND;
}
if (startIndex < 0) {
- return -1;
+ return INDEX_NOT_FOUND;
} else if (startIndex >= array.length) {
startIndex = array.length - 1;
}
@@ -1243,55 +1969,163 @@
return i;
}
}
- return -1;
+ return INDEX_NOT_FOUND;
}
/**
* Checks if the value is in the given array.
* *The method returns false
if a null
array is passed in.
true
if the array contains the object
*/
- public static boolean contains(final short[] array, final short valueToFind) {
- return (indexOf(array, valueToFind) != -1);
+ public static boolean contains(short[] array, short valueToFind) {
+ return indexOf(array, valueToFind) != INDEX_NOT_FOUND;
}
+ // char IndexOf
+ //-----------------------------------------------------------------------
+ /**
+ * Finds the index of the given value in the array.
+ * + *This method returns {@link #INDEX_NOT_FOUND} (-1
) for a null
input array.
null
+ * @param valueToFind the value to find
+ * @return the index of the value within the array,
+ * {@link #INDEX_NOT_FOUND} (-1
) if not found or null
array input
+ * @since 2.1
+ */
+ public static int indexOf(char[] array, char valueToFind) {
+ return indexOf(array, valueToFind, 0);
+ }
+
+ /**
+ * Finds the index of the given value in the array starting at the given index.
+ * + *This method returns {@link #INDEX_NOT_FOUND} (-1
) for a null
input array.
A negative startIndex is treated as zero. A startIndex larger than the array
+ * length will return {@link #INDEX_NOT_FOUND} (-1
).
null
+ * @param valueToFind the value to find
+ * @param startIndex the index to start searching at
+ * @return the index of the value within the array,
+ * {@link #INDEX_NOT_FOUND} (-1
) if not found or null
array input
+ * @since 2.1
+ */
+ public static int indexOf(char[] array, char valueToFind, int startIndex) {
+ if (array == null) {
+ return INDEX_NOT_FOUND;
+ }
+ if (startIndex < 0) {
+ startIndex = 0;
+ }
+ for (int i = startIndex; i < array.length; i++) {
+ if (valueToFind == array[i]) {
+ return i;
+ }
+ }
+ return INDEX_NOT_FOUND;
+ }
+
+ /**
+ * Finds the last index of the given value within the array.
+ * + *This method returns {@link #INDEX_NOT_FOUND} (-1
) for a null
input array.
null
+ * @param valueToFind the object to find
+ * @return the last index of the value within the array,
+ * {@link #INDEX_NOT_FOUND} (-1
) if not found or null
array input
+ * @since 2.1
+ */
+ public static int lastIndexOf(char[] array, char valueToFind) {
+ return lastIndexOf(array, valueToFind, Integer.MAX_VALUE);
+ }
+
+ /**
+ * Finds the last index of the given value in the array starting at the given index.
+ * + *This method returns {@link #INDEX_NOT_FOUND} (-1
) for a null
input array.
A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1
). A startIndex larger than the
+ * array length will search from the end of the array.
null
+ * @param valueToFind the value to find
+ * @param startIndex the start index to travers backwards from
+ * @return the last index of the value within the array,
+ * {@link #INDEX_NOT_FOUND} (-1
) if not found or null
array input
+ * @since 2.1
+ */
+ public static int lastIndexOf(char[] array, char valueToFind, int startIndex) {
+ if (array == null) {
+ return INDEX_NOT_FOUND;
+ }
+ if (startIndex < 0) {
+ return INDEX_NOT_FOUND;
+ } else if (startIndex >= array.length) {
+ startIndex = array.length - 1;
+ }
+ for (int i = startIndex; i >= 0; i--) {
+ if (valueToFind == array[i]) {
+ return i;
+ }
+ }
+ return INDEX_NOT_FOUND;
+ }
+
+ /**
+ * Checks if the value is in the given array.
+ * + *The method returns false
if a null
array is passed in.
true
if the array contains the object
+ * @since 2.1
+ */
+ public static boolean contains(char[] array, char valueToFind) {
+ return indexOf(array, valueToFind) != INDEX_NOT_FOUND;
+ }
+
// byte IndexOf
//-----------------------------------------------------------------------
/**
- * Find the index of the given value in the array.
+ *Finds the index of the given value in the array.
* - *This method returns -1
if null
array input.
This method returns {@link #INDEX_NOT_FOUND} (-1
) for a null
input array.
null
* @param valueToFind the value to find
* @return the index of the value within the array,
- * -1
if not found or null
array input
+ * {@link #INDEX_NOT_FOUND} (-1
) if not found or null
array input
*/
- public static int indexOf(final byte[] array, final byte valueToFind) {
+ public static int indexOf(byte[] array, byte valueToFind) {
return indexOf(array, valueToFind, 0);
}
/**
- * Find the index of the given value in the array starting at the given index.
+ *Finds the index of the given value in the array starting at the given index.
* - *This method returns -1
if null
array input.
This method returns {@link #INDEX_NOT_FOUND} (-1
) for a null
input array.
A negative startIndex is treated as zero. A startIndex larger than the array - * length will return -1.
- * + * length will return {@link #INDEX_NOT_FOUND} (-1
).
+ *
* @param array the array to search through for the object, may be null
* @param valueToFind the value to find
* @param startIndex the index to start searching at
* @return the index of the value within the array,
- * -1
if not found or null
array input
+ * {@link #INDEX_NOT_FOUND} (-1
) if not found or null
array input
*/
- public static int indexOf(final byte[] array, final byte valueToFind, int startIndex) {
+ public static int indexOf(byte[] array, byte valueToFind, int startIndex) {
if (array == null) {
- return -1;
+ return INDEX_NOT_FOUND;
}
if (startIndex < 0) {
startIndex = 0;
@@ -1301,43 +2135,43 @@
return i;
}
}
- return -1;
+ return INDEX_NOT_FOUND;
}
/**
- * Find the last index of the given value within the array.
+ *Finds the last index of the given value within the array.
* - *This method returns -1
if null
array input.
This method returns {@link #INDEX_NOT_FOUND} (-1
) for a null
input array.
null
* @param valueToFind the object to find
* @return the last index of the value within the array,
- * -1
if not found or null
array input
+ * {@link #INDEX_NOT_FOUND} (-1
) if not found or null
array input
*/
- public static int lastIndexOf(final byte[] array, final byte valueToFind) {
+ public static int lastIndexOf(byte[] array, byte valueToFind) {
return lastIndexOf(array, valueToFind, Integer.MAX_VALUE);
}
/**
- * Find the last index of the given value in the array starting at the given index.
+ *Finds the last index of the given value in the array starting at the given index.
* - *This method returns -1
if null
array input.
This method returns {@link #INDEX_NOT_FOUND} (-1
) for a null
input array.
A negative startIndex will return -1. A startIndex larger than the array - * length will search from the end of the array.
- * + *A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1
). A startIndex larger than the
+ * array length will search from the end of the array.
null
* @param valueToFind the value to find
* @param startIndex the start index to travers backwards from
* @return the last index of the value within the array,
- * -1
if not found or null
array input
+ * {@link #INDEX_NOT_FOUND} (-1
) if not found or null
array input
*/
- public static int lastIndexOf(final byte[] array, final byte valueToFind, int startIndex) {
+ public static int lastIndexOf(byte[] array, byte valueToFind, int startIndex) {
if (array == null) {
- return -1;
+ return INDEX_NOT_FOUND;
}
if (startIndex < 0) {
- return -1;
+ return INDEX_NOT_FOUND;
} else if (startIndex >= array.length) {
startIndex = array.length - 1;
}
@@ -1346,72 +2180,72 @@
return i;
}
}
- return -1;
+ return INDEX_NOT_FOUND;
}
/**
* Checks if the value is in the given array.
* *The method returns false
if a null
array is passed in.
true
if the array contains the object
*/
- public static boolean contains(final byte[] array, final byte valueToFind) {
- return (indexOf(array, valueToFind) != -1);
+ public static boolean contains(byte[] array, byte valueToFind) {
+ return indexOf(array, valueToFind) != INDEX_NOT_FOUND;
}
// double IndexOf
//-----------------------------------------------------------------------
/**
- * Find the index of the given value in the array.
+ *Finds the index of the given value in the array.
* - *This method returns -1
if null
array input.
This method returns {@link #INDEX_NOT_FOUND} (-1
) for a null
input array.
null
* @param valueToFind the value to find
* @return the index of the value within the array,
- * -1
if not found or null
array input
+ * {@link #INDEX_NOT_FOUND} (-1
) if not found or null
array input
*/
- public static int indexOf(final double[] array, final double valueToFind) {
+ public static int indexOf(double[] array, double valueToFind) {
return indexOf(array, valueToFind, 0);
}
/**
- * Find the index of the given value within a given tolerance in the array. + *
Finds the index of the given value within a given tolerance in the array. * This method will return the index of the first value which falls between the region * defined by valueToFind - tolerance and valueToFind + tolerance.
* - *This method returns -1
if null
array input.
This method returns {@link #INDEX_NOT_FOUND} (-1
) for a null
input array.
null
* @param valueToFind the value to find
* @param tolerance tolerance of the search
* @return the index of the value within the array,
- * -1
if not found or null
array input
+ * {@link #INDEX_NOT_FOUND} (-1
) if not found or null
array input
*/
- public static int indexOf(final double[] array, final double valueToFind, final double tolerance) {
+ public static int indexOf(double[] array, double valueToFind, double tolerance) {
return indexOf(array, valueToFind, 0, tolerance);
}
/**
- * Find the index of the given value in the array starting at the given index.
+ *Finds the index of the given value in the array starting at the given index.
* - *This method returns -1
if null
array input.
This method returns {@link #INDEX_NOT_FOUND} (-1
) for a null
input array.
A negative startIndex is treated as zero. A startIndex larger than the array - * length will return -1.
- * + * length will return {@link #INDEX_NOT_FOUND} (-1
).
+ *
* @param array the array to search through for the object, may be null
* @param valueToFind the value to find
* @param startIndex the index to start searching at
* @return the index of the value within the array,
- * -1
if not found or null
array input
+ * {@link #INDEX_NOT_FOUND} (-1
) if not found or null
array input
*/
- public static int indexOf(final double[] array, final double valueToFind, int startIndex) {
- if (array == null || array.length == 0) {
- return -1;
+ public static int indexOf(double[] array, double valueToFind, int startIndex) {
+ if (ArrayUtils.isEmpty(array)) {
+ return INDEX_NOT_FOUND;
}
if (startIndex < 0) {
startIndex = 0;
@@ -1421,29 +2255,29 @@
return i;
}
}
- return -1;
+ return INDEX_NOT_FOUND;
}
/**
- * Find the index of the given value in the array starting at the given index. + *
Finds the index of the given value in the array starting at the given index. * This method will return the index of the first value which falls between the region * defined by valueToFind - tolerance and valueToFind + tolerance.
* - *This method returns -1
if null
array input.
This method returns {@link #INDEX_NOT_FOUND} (-1
) for a null
input array.
A negative startIndex is treated as zero. A startIndex larger than the array - * length will return -1.
- * + * length will return {@link #INDEX_NOT_FOUND} (-1
).
+ *
* @param array the array to search through for the object, may be null
* @param valueToFind the value to find
* @param startIndex the index to start searching at
* @param tolerance tolerance of the search
* @return the index of the value within the array,
- * -1
if not found or null
array input
+ * {@link #INDEX_NOT_FOUND} (-1
) if not found or null
array input
*/
- public static int indexOf(final double[] array, final double valueToFind, int startIndex, double tolerance) {
- if (array == null || array.length == 0) {
- return -1;
+ public static int indexOf(double[] array, double valueToFind, int startIndex, double tolerance) {
+ if (ArrayUtils.isEmpty(array)) {
+ return INDEX_NOT_FOUND;
}
if (startIndex < 0) {
startIndex = 0;
@@ -1455,60 +2289,60 @@
return i;
}
}
- return -1;
+ return INDEX_NOT_FOUND;
}
/**
- * Find the last index of the given value within the array.
+ *Finds the last index of the given value within the array.
* - *This method returns -1
if null
array input.
This method returns {@link #INDEX_NOT_FOUND} (-1
) for a null
input array.
null
* @param valueToFind the object to find
* @return the last index of the value within the array,
- * -1
if not found or null
array input
+ * {@link #INDEX_NOT_FOUND} (-1
) if not found or null
array input
*/
- public static int lastIndexOf(final double[] array, final double valueToFind) {
+ public static int lastIndexOf(double[] array, double valueToFind) {
return lastIndexOf(array, valueToFind, Integer.MAX_VALUE);
}
/**
- * Find the last index of the given value within a given tolerance in the array. + *
Finds the last index of the given value within a given tolerance in the array. * This method will return the index of the last value which falls between the region * defined by valueToFind - tolerance and valueToFind + tolerance.
* - *This method returns -1
if null
array input.
This method returns {@link #INDEX_NOT_FOUND} (-1
) for a null
input array.
null
* @param valueToFind the value to find
* @param tolerance tolerance of the search
* @return the index of the value within the array,
- * -1
if not found or null
array input
+ * {@link #INDEX_NOT_FOUND} (-1
) if not found or null
array input
*/
- public static int lastIndexOf(final double[] array, final double valueToFind, final double tolerance) {
+ public static int lastIndexOf(double[] array, double valueToFind, double tolerance) {
return lastIndexOf(array, valueToFind, Integer.MAX_VALUE, tolerance);
}
/**
- * Find the last index of the given value in the array starting at the given index.
+ *Finds the last index of the given value in the array starting at the given index.
* - *This method returns -1
if null
array input.
This method returns {@link #INDEX_NOT_FOUND} (-1
) for a null
input array.
A negative startIndex will return -1. A startIndex larger than the array - * length will search from the end of the array.
- * + *A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1
). A startIndex larger than the
+ * array length will search from the end of the array.
null
* @param valueToFind the value to find
* @param startIndex the start index to travers backwards from
* @return the last index of the value within the array,
- * -1
if not found or null
array input
+ * {@link #INDEX_NOT_FOUND} (-1
) if not found or null
array input
*/
- public static int lastIndexOf(final double[] array, final double valueToFind, int startIndex) {
- if (array == null || array.length == 0) {
- return -1;
+ public static int lastIndexOf(double[] array, double valueToFind, int startIndex) {
+ if (ArrayUtils.isEmpty(array)) {
+ return INDEX_NOT_FOUND;
}
if (startIndex < 0) {
- return -1;
+ return INDEX_NOT_FOUND;
} else if (startIndex >= array.length) {
startIndex = array.length - 1;
}
@@ -1517,32 +2351,32 @@
return i;
}
}
- return -1;
+ return INDEX_NOT_FOUND;
}
/**
- * Find the last index of the given value in the array starting at the given index. + *
Finds the last index of the given value in the array starting at the given index. * This method will return the index of the last value which falls between the region * defined by valueToFind - tolerance and valueToFind + tolerance.
* - *This method returns -1
if null
array input.
This method returns {@link #INDEX_NOT_FOUND} (-1
) for a null
input array.
A negative startIndex will return -1. A startIndex larger than the array - * length will search from the end of the array.
- * + *A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1
). A startIndex larger than the
+ * array length will search from the end of the array.
null
* @param valueToFind the value to find
* @param startIndex the start index to travers backwards from
* @param tolerance search for value within plus/minus this amount
* @return the last index of the value within the array,
- * -1
if not found or null
array input
+ * {@link #INDEX_NOT_FOUND} (-1
) if not found or null
array input
*/
- public static int lastIndexOf(final double[] array, final double valueToFind, int startIndex, double tolerance) {
- if (array == null || array.length == 0) {
- return -1;
+ public static int lastIndexOf(double[] array, double valueToFind, int startIndex, double tolerance) {
+ if (ArrayUtils.isEmpty(array)) {
+ return INDEX_NOT_FOUND;
}
if (startIndex < 0) {
- return -1;
+ return INDEX_NOT_FOUND;
} else if (startIndex >= array.length) {
startIndex = array.length - 1;
}
@@ -1553,25 +2387,25 @@
return i;
}
}
- return -1;
+ return INDEX_NOT_FOUND;
}
/**
* Checks if the value is in the given array.
* *The method returns false
if a null
array is passed in.
true
if the array contains the object
*/
- public static boolean contains(final double[] array, final double valueToFind) {
- return (indexOf(array, valueToFind) != -1);
+ public static boolean contains(double[] array, double valueToFind) {
+ return indexOf(array, valueToFind) != INDEX_NOT_FOUND;
}
/**
* Checks if a value falling within the given tolerance is in the - * given array. If the array contains a value within the inclusive range + * given array. If the array contains a value within the inclusive range * defined by (value - tolerance) to (value + tolerance).
* *The method returns false
if a null
array
@@ -1582,43 +2416,43 @@
* @param tolerance the array contains the tolerance of the search
* @return true if value falling within tolerance is in array
*/
- public static boolean contains(final double[] array, final double valueToFind, final double tolerance) {
- return (indexOf(array, valueToFind, 0, tolerance) != -1);
+ public static boolean contains(double[] array, double valueToFind, double tolerance) {
+ return indexOf(array, valueToFind, 0, tolerance) != INDEX_NOT_FOUND;
}
// float IndexOf
//-----------------------------------------------------------------------
/**
- *
Find the index of the given value in the array.
+ *Finds the index of the given value in the array.
* - *This method returns -1
if null
array input.
This method returns {@link #INDEX_NOT_FOUND} (-1
) for a null
input array.
null
* @param valueToFind the value to find
* @return the index of the value within the array,
- * -1
if not found or null
array input
+ * {@link #INDEX_NOT_FOUND} (-1
) if not found or null
array input
*/
- public static int indexOf(final float[] array, final float valueToFind) {
+ public static int indexOf(float[] array, float valueToFind) {
return indexOf(array, valueToFind, 0);
}
/**
- * Find the index of the given value in the array starting at the given index.
+ *Finds the index of the given value in the array starting at the given index.
* - *This method returns -1
if null
array input.
This method returns {@link #INDEX_NOT_FOUND} (-1
) for a null
input array.
A negative startIndex is treated as zero. A startIndex larger than the array - * length will return -1.
- * + * length will return {@link #INDEX_NOT_FOUND} (-1
).
+ *
* @param array the array to search through for the object, may be null
* @param valueToFind the value to find
* @param startIndex the index to start searching at
* @return the index of the value within the array,
- * -1
if not found or null
array input
+ * {@link #INDEX_NOT_FOUND} (-1
) if not found or null
array input
*/
- public static int indexOf(final float[] array, final float valueToFind, int startIndex) {
- if (array == null || array.length == 0) {
- return -1;
+ public static int indexOf(float[] array, float valueToFind, int startIndex) {
+ if (ArrayUtils.isEmpty(array)) {
+ return INDEX_NOT_FOUND;
}
if (startIndex < 0) {
startIndex = 0;
@@ -1628,43 +2462,43 @@
return i;
}
}
- return -1;
+ return INDEX_NOT_FOUND;
}
/**
- * Find the last index of the given value within the array.
+ *Finds the last index of the given value within the array.
* - *This method returns -1
if null
array input.
This method returns {@link #INDEX_NOT_FOUND} (-1
) for a null
input array.
null
* @param valueToFind the object to find
* @return the last index of the value within the array,
- * -1
if not found or null
array input
+ * {@link #INDEX_NOT_FOUND} (-1
) if not found or null
array input
*/
- public static int lastIndexOf(final float[] array, final float valueToFind) {
+ public static int lastIndexOf(float[] array, float valueToFind) {
return lastIndexOf(array, valueToFind, Integer.MAX_VALUE);
}
/**
- * Find the last index of the given value in the array starting at the given index.
+ *Finds the last index of the given value in the array starting at the given index.
* - *This method returns -1
if null
array input.
This method returns {@link #INDEX_NOT_FOUND} (-1
) for a null
input array.
A negative startIndex will return -1. A startIndex larger than the array - * length will search from the end of the array.
- * + *A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1
). A startIndex larger than the
+ * array length will search from the end of the array.
null
* @param valueToFind the value to find
* @param startIndex the start index to travers backwards from
* @return the last index of the value within the array,
- * -1
if not found or null
array input
+ * {@link #INDEX_NOT_FOUND} (-1
) if not found or null
array input
*/
- public static int lastIndexOf(final float[] array, final float valueToFind, int startIndex) {
- if (array == null || array.length == 0) {
- return -1;
+ public static int lastIndexOf(float[] array, float valueToFind, int startIndex) {
+ if (ArrayUtils.isEmpty(array)) {
+ return INDEX_NOT_FOUND;
}
if (startIndex < 0) {
- return -1;
+ return INDEX_NOT_FOUND;
} else if (startIndex >= array.length) {
startIndex = array.length - 1;
}
@@ -1673,55 +2507,56 @@
return i;
}
}
- return -1;
+ return INDEX_NOT_FOUND;
}
/**
* Checks if the value is in the given array.
* *The method returns false
if a null
array is passed in.
true
if the array contains the object
*/
- public static boolean contains(final float[] array, final float valueToFind) {
- return (indexOf(array, valueToFind) != -1);
+ public static boolean contains(float[] array, float valueToFind) {
+ return indexOf(array, valueToFind) != INDEX_NOT_FOUND;
}
// boolean IndexOf
//-----------------------------------------------------------------------
/**
- * Find the index of the given value in the array.
+ *Finds the index of the given value in the array.
* - *This method returns -1
if null
array input.
This method returns {@link #INDEX_NOT_FOUND} (-1
) for a null
input array.
null
* @param valueToFind the value to find
* @return the index of the value within the array,
- * -1
if not found or null
array input
+ * {@link #INDEX_NOT_FOUND} (-1
) if not found or null
array input
*/
- public static int indexOf(final boolean[] array, final boolean valueToFind) {
+ public static int indexOf(boolean[] array, boolean valueToFind) {
return indexOf(array, valueToFind, 0);
}
/**
- * Find the index of the given value in the array starting at the given index.
+ *Finds the index of the given value in the array starting at the given index.
* - *This method returns -1
if null
array input.
This method returns {@link #INDEX_NOT_FOUND} (-1
) for a null
input array.
A negative startIndex is treated as zero. A startIndex larger than the array - * length will return -1.
- * + * length will return {@link #INDEX_NOT_FOUND} (-1
).
+ *
* @param array the array to search through for the object, may be null
* @param valueToFind the value to find
* @param startIndex the index to start searching at
* @return the index of the value within the array,
- * -1
if not found or null
array input
+ * {@link #INDEX_NOT_FOUND} (-1
) if not found or null
+ * array input
*/
- public static int indexOf(final boolean[] array, final boolean valueToFind, int startIndex) {
- if (array == null || array.length == 0) {
- return -1;
+ public static int indexOf(boolean[] array, boolean valueToFind, int startIndex) {
+ if (ArrayUtils.isEmpty(array)) {
+ return INDEX_NOT_FOUND;
}
if (startIndex < 0) {
startIndex = 0;
@@ -1731,43 +2566,44 @@
return i;
}
}
- return -1;
+ return INDEX_NOT_FOUND;
}
/**
- * Find the last index of the given value within the array.
+ *Finds the last index of the given value within the array.
* - *This method returns -1
if null
array input.
This method returns {@link #INDEX_NOT_FOUND} (-1
) if
+ * null
array input.
null
* @param valueToFind the object to find
* @return the last index of the value within the array,
- * -1
if not found or null
array input
+ * {@link #INDEX_NOT_FOUND} (-1
) if not found or null
array input
*/
- public static int lastIndexOf(final boolean[] array, final boolean valueToFind) {
+ public static int lastIndexOf(boolean[] array, boolean valueToFind) {
return lastIndexOf(array, valueToFind, Integer.MAX_VALUE);
}
/**
- * Find the last index of the given value in the array starting at the given index.
+ *Finds the last index of the given value in the array starting at the given index.
* - *This method returns -1
if null
array input.
This method returns {@link #INDEX_NOT_FOUND} (-1
) for a null
input array.
A negative startIndex will return -1. A startIndex larger than the array - * length will search from the end of the array.
- * + *A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1
). A startIndex larger than
+ * the array length will search from the end of the array.
null
* @param valueToFind the value to find
* @param startIndex the start index to travers backwards from
* @return the last index of the value within the array,
- * -1
if not found or null
array input
+ * {@link #INDEX_NOT_FOUND} (-1
) if not found or null
array input
*/
- public static int lastIndexOf(final boolean[] array, final boolean valueToFind, int startIndex) {
- if (array == null || array.length == 0) {
- return -1;
+ public static int lastIndexOf(boolean[] array, boolean valueToFind, int startIndex) {
+ if (ArrayUtils.isEmpty(array)) {
+ return INDEX_NOT_FOUND;
}
if (startIndex < 0) {
- return -1;
+ return INDEX_NOT_FOUND;
} else if (startIndex >= array.length) {
startIndex = array.length - 1;
}
@@ -1776,37 +2612,105 @@
return i;
}
}
- return -1;
+ return INDEX_NOT_FOUND;
}
/**
* Checks if the value is in the given array.
* *The method returns false
if a null
array is passed in.
true
if the array contains the object
*/
- public static boolean contains(final boolean[] array, final boolean valueToFind) {
- return (indexOf(array, valueToFind) != -1);
+ public static boolean contains(boolean[] array, boolean valueToFind) {
+ return indexOf(array, valueToFind) != INDEX_NOT_FOUND;
}
// Primitive/Object array converters
// ----------------------------------------------------------------------
-
+
+ // Character array converters
+ // ----------------------------------------------------------------------
+ /**
+ * Converts an array of object Characters to primitives.
+ * + *This method returns null
for a null
input array.
Character
array, may be null
+ * @return a char
array, null
if null array input
+ * @throws NullPointerException if array content is null
+ */
+ public static char[] toPrimitive(Character[] array) {
+ if (array == null) {
+ return null;
+ } else if (array.length == 0) {
+ return EMPTY_CHAR_ARRAY;
+ }
+ final char[] result = new char[array.length];
+ for (int i = 0; i < array.length; i++) {
+ result[i] = array[i].charValue();
+ }
+ return result;
+ }
+
+ /**
+ * Converts an array of object Character to primitives handling null
.
This method returns null
for a null
input array.
Character
array, may be null
+ * @param valueForNull the value to insert if null
found
+ * @return a char
array, null
if null array input
+ */
+ public static char[] toPrimitive(Character[] array, char valueForNull) {
+ if (array == null) {
+ return null;
+ } else if (array.length == 0) {
+ return EMPTY_CHAR_ARRAY;
+ }
+ final char[] result = new char[array.length];
+ for (int i = 0; i < array.length; i++) {
+ Character b = array[i];
+ result[i] = (b == null ? valueForNull : b.charValue());
+ }
+ return result;
+ }
+
+ /**
+ * Converts an array of primitive chars to objects.
+ * + *This method returns null
for a null
input array.
char
array
+ * @return a Character
array, null
if null array input
+ */
+ public static Character[] toObject(char[] array) {
+ if (array == null) {
+ return null;
+ } else if (array.length == 0) {
+ return EMPTY_CHARACTER_OBJECT_ARRAY;
+ }
+ final Character[] result = new Character[array.length];
+ for (int i = 0; i < array.length; i++) {
+ result[i] = new Character(array[i]);
+ }
+ return result;
+ }
+
// Long array converters
// ----------------------------------------------------------------------
/**
* Converts an array of object Longs to primitives.
* - *This method returns null
if null
array input.
This method returns null
for a null
input array.
Long
array, may be null
* @return a long
array, null
if null array input
* @throws NullPointerException if array content is null
*/
- public static long[] toPrimitive(final Long[] array) {
+ public static long[] toPrimitive(Long[] array) {
if (array == null) {
return null;
} else if (array.length == 0) {
@@ -1818,17 +2722,17 @@
}
return result;
}
-
+
/**
* Converts an array of object Long to primitives handling null
.
This method returns null
if null
array input.
This method returns null
for a null
input array.
Long
array, may be null
* @param valueForNull the value to insert if null
found
* @return a long
array, null
if null array input
*/
- public static long[] toPrimitive(final Long[] array, final long valueForNull) {
+ public static long[] toPrimitive(Long[] array, long valueForNull) {
if (array == null) {
return null;
} else if (array.length == 0) {
@@ -1841,16 +2745,16 @@
}
return result;
}
-
+
/**
* Converts an array of primitive longs to objects.
* - *This method returns null
if null
array input.
This method returns null
for a null
input array.
long
array
* @return a Long
array, null
if null array input
*/
- public static Long[] toObject(final long[] array) {
+ public static Long[] toObject(long[] array) {
if (array == null) {
return null;
} else if (array.length == 0) {
@@ -1868,13 +2772,13 @@
/**
* Converts an array of object Integers to primitives.
* - *This method returns null
if null
array input.
This method returns null
for a null
input array.
Integer
array, may be null
* @return an int
array, null
if null array input
* @throws NullPointerException if array content is null
*/
- public static int[] toPrimitive(final Integer[] array) {
+ public static int[] toPrimitive(Integer[] array) {
if (array == null) {
return null;
} else if (array.length == 0) {
@@ -1889,14 +2793,14 @@
/**
* Converts an array of object Integer to primitives handling null
.
This method returns null
if null
array input.
This method returns null
for a null
input array.
Integer
array, may be null
* @param valueForNull the value to insert if null
found
* @return an int
array, null
if null array input
*/
- public static int[] toPrimitive(final Integer[] array, final int valueForNull) {
+ public static int[] toPrimitive(Integer[] array, int valueForNull) {
if (array == null) {
return null;
} else if (array.length == 0) {
@@ -1913,12 +2817,12 @@
/**
* Converts an array of primitive ints to objects.
* - *This method returns null
if null
array input.
This method returns null
for a null
input array.
int
array
* @return an Integer
array, null
if null array input
*/
- public static Integer[] toObject(final int[] array) {
+ public static Integer[] toObject(int[] array) {
if (array == null) {
return null;
} else if (array.length == 0) {
@@ -1930,19 +2834,19 @@
}
return result;
}
-
+
// Short array converters
// ----------------------------------------------------------------------
/**
* Converts an array of object Shorts to primitives.
* - *This method returns null
if null
array input.
This method returns null
for a null
input array.
Short
array, may be null
* @return a byte
array, null
if null array input
* @throws NullPointerException if array content is null
*/
- public static short[] toPrimitive(final Short[] array) {
+ public static short[] toPrimitive(Short[] array) {
if (array == null) {
return null;
} else if (array.length == 0) {
@@ -1957,14 +2861,14 @@
/**
* Converts an array of object Short to primitives handling null
.
This method returns null
if null
array input.
This method returns null
for a null
input array.
Short
array, may be null
* @param valueForNull the value to insert if null
found
* @return a byte
array, null
if null array input
*/
- public static short[] toPrimitive(final Short[] array, final short valueForNull) {
+ public static short[] toPrimitive(Short[] array, short valueForNull) {
if (array == null) {
return null;
} else if (array.length == 0) {
@@ -1981,12 +2885,12 @@
/**
* Converts an array of primitive shorts to objects.
* - *This method returns null
if null
array input.
This method returns null
for a null
input array.
short
array
* @return a Short
array, null
if null array input
*/
- public static Short[] toObject(final short[] array) {
+ public static Short[] toObject(short[] array) {
if (array == null) {
return null;
} else if (array.length == 0) {
@@ -1997,20 +2901,20 @@
result[i] = new Short(array[i]);
}
return result;
- }
+ }
// Byte array converters
// ----------------------------------------------------------------------
/**
* Converts an array of object Bytes to primitives.
* - *This method returns null
if null
array input.
This method returns null
for a null
input array.
Byte
array, may be null
* @return a byte
array, null
if null array input
* @throws NullPointerException if array content is null
*/
- public static byte[] toPrimitive(final Byte[] array) {
+ public static byte[] toPrimitive(Byte[] array) {
if (array == null) {
return null;
} else if (array.length == 0) {
@@ -2025,14 +2929,14 @@
/**
* Converts an array of object Bytes to primitives handling null
.
This method returns null
if null
array input.
This method returns null
for a null
input array.
Byte
array, may be null
* @param valueForNull the value to insert if null
found
* @return a byte
array, null
if null array input
*/
- public static byte[] toPrimitive(final Byte[] array, final byte valueForNull) {
+ public static byte[] toPrimitive(Byte[] array, byte valueForNull) {
if (array == null) {
return null;
} else if (array.length == 0) {
@@ -2049,12 +2953,12 @@
/**
* Converts an array of primitive bytes to objects.
* - *This method returns null
if null
array input.
This method returns null
for a null
input array.
byte
array
* @return a Byte
array, null
if null array input
*/
- public static Byte[] toObject(final byte[] array) {
+ public static Byte[] toObject(byte[] array) {
if (array == null) {
return null;
} else if (array.length == 0) {
@@ -2065,20 +2969,20 @@
result[i] = new Byte(array[i]);
}
return result;
- }
-
+ }
+
// Double array converters
// ----------------------------------------------------------------------
/**
* Converts an array of object Doubles to primitives.
* - *This method returns null
if null
array input.
This method returns null
for a null
input array.
Double
array, may be null
* @return a double
array, null
if null array input
* @throws NullPointerException if array content is null
*/
- public static double[] toPrimitive(final Double[] array) {
+ public static double[] toPrimitive(Double[] array) {
if (array == null) {
return null;
} else if (array.length == 0) {
@@ -2093,14 +2997,14 @@
/**
* Converts an array of object Doubles to primitives handling null
.
This method returns null
if null
array input.
This method returns null
for a null
input array.
Double
array, may be null
* @param valueForNull the value to insert if null
found
* @return a double
array, null
if null array input
*/
- public static double[] toPrimitive(final Double[] array, final double valueForNull) {
+ public static double[] toPrimitive(Double[] array, double valueForNull) {
if (array == null) {
return null;
} else if (array.length == 0) {
@@ -2117,12 +3021,12 @@
/**
* Converts an array of primitive doubles to objects.
* - *This method returns null
if null
array input.
This method returns null
for a null
input array.
double
array
* @return a Double
array, null
if null array input
*/
- public static Double[] toObject(final double[] array) {
+ public static Double[] toObject(double[] array) {
if (array == null) {
return null;
} else if (array.length == 0) {
@@ -2140,13 +3044,13 @@
/**
* Converts an array of object Floats to primitives.
* - *This method returns null
if null
array input.
This method returns null
for a null
input array.
Float
array, may be null
* @return a float
array, null
if null array input
* @throws NullPointerException if array content is null
*/
- public static float[] toPrimitive(final Float[] array) {
+ public static float[] toPrimitive(Float[] array) {
if (array == null) {
return null;
} else if (array.length == 0) {
@@ -2161,14 +3065,14 @@
/**
* Converts an array of object Floats to primitives handling null
.
This method returns null
if null
array input.
This method returns null
for a null
input array.
Float
array, may be null
* @param valueForNull the value to insert if null
found
* @return a float
array, null
if null array input
*/
- public static float[] toPrimitive(final Float[] array, final float valueForNull) {
+ public static float[] toPrimitive(Float[] array, float valueForNull) {
if (array == null) {
return null;
} else if (array.length == 0) {
@@ -2185,12 +3089,12 @@
/**
* Converts an array of primitive floats to objects.
* - *This method returns null
if null
array input.
This method returns null
for a null
input array.
float
array
* @return a Float
array, null
if null array input
*/
- public static Float[] toObject(final float[] array) {
+ public static Float[] toObject(float[] array) {
if (array == null) {
return null;
} else if (array.length == 0) {
@@ -2208,13 +3112,13 @@
/**
* Converts an array of object Booleans to primitives.
* - *This method returns null
if null
array input.
This method returns null
for a null
input array.
Boolean
array, may be null
* @return a boolean
array, null
if null array input
* @throws NullPointerException if array content is null
*/
- public static boolean[] toPrimitive(final Boolean[] array) {
+ public static boolean[] toPrimitive(Boolean[] array) {
if (array == null) {
return null;
} else if (array.length == 0) {
@@ -2229,14 +3133,14 @@
/**
* Converts an array of object Booleans to primitives handling null
.
This method returns null
if null
array input.
This method returns null
for a null
input array.
Boolean
array, may be null
* @param valueForNull the value to insert if null
found
* @return a boolean
array, null
if null array input
*/
- public static boolean[] toPrimitive(final Boolean[] array, final boolean valueForNull) {
+ public static boolean[] toPrimitive(Boolean[] array, boolean valueForNull) {
if (array == null) {
return null;
} else if (array.length == 0) {
@@ -2253,12 +3157,12 @@
/**
* Converts an array of primitive booleans to objects.
* - *This method returns null
if null
array input.
This method returns null
for a null
input array.
boolean
array
* @return a Boolean
array, null
if null array input
*/
- public static Boolean[] toObject(final boolean[] array) {
+ public static Boolean[] toObject(boolean[] array) {
if (array == null) {
return null;
} else if (array.length == 0) {
@@ -2271,4 +3175,1705 @@
return result;
}
+ // ----------------------------------------------------------------------
+ /**
+ * Checks if an array of Objects is empty or null
.
true
if the array is empty or null
+ * @since 2.1
+ */
+ public static boolean isEmpty(Object[] array) {
+ return array == null || array.length == 0;
+ }
+
+ /**
+ * Checks if an array of primitive longs is empty or null
.
true
if the array is empty or null
+ * @since 2.1
+ */
+ public static boolean isEmpty(long[] array) {
+ return array == null || array.length == 0;
+ }
+
+ /**
+ * Checks if an array of primitive ints is empty or null
.
true
if the array is empty or null
+ * @since 2.1
+ */
+ public static boolean isEmpty(int[] array) {
+ return array == null || array.length == 0;
+ }
+
+ /**
+ * Checks if an array of primitive shorts is empty or null
.
true
if the array is empty or null
+ * @since 2.1
+ */
+ public static boolean isEmpty(short[] array) {
+ return array == null || array.length == 0;
+ }
+
+ /**
+ * Checks if an array of primitive chars is empty or null
.
true
if the array is empty or null
+ * @since 2.1
+ */
+ public static boolean isEmpty(char[] array) {
+ return array == null || array.length == 0;
+ }
+
+ /**
+ * Checks if an array of primitive bytes is empty or null
.
true
if the array is empty or null
+ * @since 2.1
+ */
+ public static boolean isEmpty(byte[] array) {
+ return array == null || array.length == 0;
+ }
+
+ /**
+ * Checks if an array of primitive doubles is empty or null
.
true
if the array is empty or null
+ * @since 2.1
+ */
+ public static boolean isEmpty(double[] array) {
+ return array == null || array.length == 0;
+ }
+
+ /**
+ * Checks if an array of primitive floats is empty or null
.
true
if the array is empty or null
+ * @since 2.1
+ */
+ public static boolean isEmpty(float[] array) {
+ return array == null || array.length == 0;
+ }
+
+ /**
+ * Checks if an array of primitive booleans is empty or null
.
true
if the array is empty or null
+ * @since 2.1
+ */
+ public static boolean isEmpty(boolean[] array) {
+ return array == null || array.length == 0;
+ }
+
+ // ----------------------------------------------------------------------
+ /**
+ * Checks if an array of Objects is not empty or not null
.
true
if the array is not empty or not null
+ * @since 2.5
+ */
+ public static boolean isNotEmpty(Object[] array) {
+ return (array != null && array.length != 0);
+ }
+
+ /**
+ * Checks if an array of primitive longs is not empty or not null
.
true
if the array is not empty or not null
+ * @since 2.5
+ */
+ public static boolean isNotEmpty(long[] array) {
+ return (array != null && array.length != 0);
+ }
+
+ /**
+ * Checks if an array of primitive ints is not empty or not null
.
true
if the array is not empty or not null
+ * @since 2.5
+ */
+ public static boolean isNotEmpty(int[] array) {
+ return (array != null && array.length != 0);
+ }
+
+ /**
+ * Checks if an array of primitive shorts is not empty or not null
.
true
if the array is not empty or not null
+ * @since 2.5
+ */
+ public static boolean isNotEmpty(short[] array) {
+ return (array != null && array.length != 0);
+ }
+
+ /**
+ * Checks if an array of primitive chars is not empty or not null
.
true
if the array is not empty or not null
+ * @since 2.5
+ */
+ public static boolean isNotEmpty(char[] array) {
+ return (array != null && array.length != 0);
+ }
+
+ /**
+ * Checks if an array of primitive bytes is not empty or not null
.
true
if the array is not empty or not null
+ * @since 2.5
+ */
+ public static boolean isNotEmpty(byte[] array) {
+ return (array != null && array.length != 0);
+ }
+
+ /**
+ * Checks if an array of primitive doubles is not empty or not null
.
true
if the array is not empty or not null
+ * @since 2.5
+ */
+ public static boolean isNotEmpty(double[] array) {
+ return (array != null && array.length != 0);
+ }
+
+ /**
+ * Checks if an array of primitive floats is not empty or not null
.
true
if the array is not empty or not null
+ * @since 2.5
+ */
+ public static boolean isNotEmpty(float[] array) {
+ return (array != null && array.length != 0);
+ }
+
+ /**
+ * Checks if an array of primitive booleans is not empty or not null
.
true
if the array is not empty or not null
+ * @since 2.5
+ */
+ public static boolean isNotEmpty(boolean[] array) {
+ return (array != null && array.length != 0);
+ }
+
+ /**
+ * Adds all the elements of the given arrays into a new array.
+ *The new array contains all of the element of array1
followed
+ * by all of the elements array2
. When an array is returned, it is always
+ * a new array.
+ * ArrayUtils.addAll(null, null) = null + * ArrayUtils.addAll(array1, null) = cloned copy of array1 + * ArrayUtils.addAll(null, array2) = cloned copy of array2 + * ArrayUtils.addAll([], []) = [] + * ArrayUtils.addAll([null], [null]) = [null, null] + * ArrayUtils.addAll(["a", "b", "c"], ["1", "2", "3"]) = ["a", "b", "c", "1", "2", "3"] + *+ * + * @param array1 the first array whose elements are added to the new array, may be
null
+ * @param array2 the second array whose elements are added to the new array, may be null
+ * @return The new array, null
if both arrays are null
.
+ * The type of the new array is the type of the first array,
+ * unless the first array is null, in which case the type is the same as the second array.
+ * @since 2.1
+ * @throws IllegalArgumentException if the array types are incompatible
+ */
+ public static Object[] addAll(Object[] array1, Object[] array2) {
+ if (array1 == null) {
+ return clone(array2);
+ } else if (array2 == null) {
+ return clone(array1);
+ }
+ Object[] joinedArray = (Object[]) Array.newInstance(array1.getClass().getComponentType(),
+ array1.length + array2.length);
+ System.arraycopy(array1, 0, joinedArray, 0, array1.length);
+ try {
+ System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);
+ } catch (ArrayStoreException ase) {
+ // Check if problem was due to incompatible types
+ /*
+ * We do this here, rather than before the copy because:
+ * - it would be a wasted check most of the time
+ * - safer, in case check turns out to be too strict
+ */
+ final Class type1 = array1.getClass().getComponentType();
+ final Class type2 = array2.getClass().getComponentType();
+ if (!type1.isAssignableFrom(type2)){
+ throw new IllegalArgumentException("Cannot store "+type2.getName()+" in an array of "+type1.getName());
+ }
+ throw ase; // No, so rethrow original
+ }
+ return joinedArray;
+ }
+
+ /**
+ * Adds all the elements of the given arrays into a new array.
+ *The new array contains all of the element of array1
followed
+ * by all of the elements array2
. When an array is returned, it is always
+ * a new array.
+ * ArrayUtils.addAll(array1, null) = cloned copy of array1 + * ArrayUtils.addAll(null, array2) = cloned copy of array2 + * ArrayUtils.addAll([], []) = [] + *+ * + * @param array1 the first array whose elements are added to the new array. + * @param array2 the second array whose elements are added to the new array. + * @return The new boolean[] array. + * @since 2.1 + */ + public static boolean[] addAll(boolean[] array1, boolean[] array2) { + if (array1 == null) { + return clone(array2); + } else if (array2 == null) { + return clone(array1); + } + boolean[] joinedArray = new boolean[array1.length + array2.length]; + System.arraycopy(array1, 0, joinedArray, 0, array1.length); + System.arraycopy(array2, 0, joinedArray, array1.length, array2.length); + return joinedArray; + } + + /** + *
Adds all the elements of the given arrays into a new array.
+ *The new array contains all of the element of array1
followed
+ * by all of the elements array2
. When an array is returned, it is always
+ * a new array.
+ * ArrayUtils.addAll(array1, null) = cloned copy of array1 + * ArrayUtils.addAll(null, array2) = cloned copy of array2 + * ArrayUtils.addAll([], []) = [] + *+ * + * @param array1 the first array whose elements are added to the new array. + * @param array2 the second array whose elements are added to the new array. + * @return The new char[] array. + * @since 2.1 + */ + public static char[] addAll(char[] array1, char[] array2) { + if (array1 == null) { + return clone(array2); + } else if (array2 == null) { + return clone(array1); + } + char[] joinedArray = new char[array1.length + array2.length]; + System.arraycopy(array1, 0, joinedArray, 0, array1.length); + System.arraycopy(array2, 0, joinedArray, array1.length, array2.length); + return joinedArray; + } + + /** + *
Adds all the elements of the given arrays into a new array.
+ *The new array contains all of the element of array1
followed
+ * by all of the elements array2
. When an array is returned, it is always
+ * a new array.
+ * ArrayUtils.addAll(array1, null) = cloned copy of array1 + * ArrayUtils.addAll(null, array2) = cloned copy of array2 + * ArrayUtils.addAll([], []) = [] + *+ * + * @param array1 the first array whose elements are added to the new array. + * @param array2 the second array whose elements are added to the new array. + * @return The new byte[] array. + * @since 2.1 + */ + public static byte[] addAll(byte[] array1, byte[] array2) { + if (array1 == null) { + return clone(array2); + } else if (array2 == null) { + return clone(array1); + } + byte[] joinedArray = new byte[array1.length + array2.length]; + System.arraycopy(array1, 0, joinedArray, 0, array1.length); + System.arraycopy(array2, 0, joinedArray, array1.length, array2.length); + return joinedArray; + } + + /** + *
Adds all the elements of the given arrays into a new array.
+ *The new array contains all of the element of array1
followed
+ * by all of the elements array2
. When an array is returned, it is always
+ * a new array.
+ * ArrayUtils.addAll(array1, null) = cloned copy of array1 + * ArrayUtils.addAll(null, array2) = cloned copy of array2 + * ArrayUtils.addAll([], []) = [] + *+ * + * @param array1 the first array whose elements are added to the new array. + * @param array2 the second array whose elements are added to the new array. + * @return The new short[] array. + * @since 2.1 + */ + public static short[] addAll(short[] array1, short[] array2) { + if (array1 == null) { + return clone(array2); + } else if (array2 == null) { + return clone(array1); + } + short[] joinedArray = new short[array1.length + array2.length]; + System.arraycopy(array1, 0, joinedArray, 0, array1.length); + System.arraycopy(array2, 0, joinedArray, array1.length, array2.length); + return joinedArray; + } + + /** + *
Adds all the elements of the given arrays into a new array.
+ *The new array contains all of the element of array1
followed
+ * by all of the elements array2
. When an array is returned, it is always
+ * a new array.
+ * ArrayUtils.addAll(array1, null) = cloned copy of array1 + * ArrayUtils.addAll(null, array2) = cloned copy of array2 + * ArrayUtils.addAll([], []) = [] + *+ * + * @param array1 the first array whose elements are added to the new array. + * @param array2 the second array whose elements are added to the new array. + * @return The new int[] array. + * @since 2.1 + */ + public static int[] addAll(int[] array1, int[] array2) { + if (array1 == null) { + return clone(array2); + } else if (array2 == null) { + return clone(array1); + } + int[] joinedArray = new int[array1.length + array2.length]; + System.arraycopy(array1, 0, joinedArray, 0, array1.length); + System.arraycopy(array2, 0, joinedArray, array1.length, array2.length); + return joinedArray; + } + + /** + *
Adds all the elements of the given arrays into a new array.
+ *The new array contains all of the element of array1
followed
+ * by all of the elements array2
. When an array is returned, it is always
+ * a new array.
+ * ArrayUtils.addAll(array1, null) = cloned copy of array1 + * ArrayUtils.addAll(null, array2) = cloned copy of array2 + * ArrayUtils.addAll([], []) = [] + *+ * + * @param array1 the first array whose elements are added to the new array. + * @param array2 the second array whose elements are added to the new array. + * @return The new long[] array. + * @since 2.1 + */ + public static long[] addAll(long[] array1, long[] array2) { + if (array1 == null) { + return clone(array2); + } else if (array2 == null) { + return clone(array1); + } + long[] joinedArray = new long[array1.length + array2.length]; + System.arraycopy(array1, 0, joinedArray, 0, array1.length); + System.arraycopy(array2, 0, joinedArray, array1.length, array2.length); + return joinedArray; + } + + /** + *
Adds all the elements of the given arrays into a new array.
+ *The new array contains all of the element of array1
followed
+ * by all of the elements array2
. When an array is returned, it is always
+ * a new array.
+ * ArrayUtils.addAll(array1, null) = cloned copy of array1 + * ArrayUtils.addAll(null, array2) = cloned copy of array2 + * ArrayUtils.addAll([], []) = [] + *+ * + * @param array1 the first array whose elements are added to the new array. + * @param array2 the second array whose elements are added to the new array. + * @return The new float[] array. + * @since 2.1 + */ + public static float[] addAll(float[] array1, float[] array2) { + if (array1 == null) { + return clone(array2); + } else if (array2 == null) { + return clone(array1); + } + float[] joinedArray = new float[array1.length + array2.length]; + System.arraycopy(array1, 0, joinedArray, 0, array1.length); + System.arraycopy(array2, 0, joinedArray, array1.length, array2.length); + return joinedArray; + } + + /** + *
Adds all the elements of the given arrays into a new array.
+ *The new array contains all of the element of array1
followed
+ * by all of the elements array2
. When an array is returned, it is always
+ * a new array.
+ * ArrayUtils.addAll(array1, null) = cloned copy of array1 + * ArrayUtils.addAll(null, array2) = cloned copy of array2 + * ArrayUtils.addAll([], []) = [] + *+ * + * @param array1 the first array whose elements are added to the new array. + * @param array2 the second array whose elements are added to the new array. + * @return The new double[] array. + * @since 2.1 + */ + public static double[] addAll(double[] array1, double[] array2) { + if (array1 == null) { + return clone(array2); + } else if (array2 == null) { + return clone(array1); + } + double[] joinedArray = new double[array1.length + array2.length]; + System.arraycopy(array1, 0, joinedArray, 0, array1.length); + System.arraycopy(array2, 0, joinedArray, array1.length, array2.length); + return joinedArray; + } + + /** + *
Copies the given array and adds the given element at the end of the new array.
+ * + *The new array contains the same elements of the input + * array plus the given element in the last position. The component type of + * the new array is the same as that of the input array.
+ * + *If the input array is null
, a new one element array is returned
+ * whose component type is the same as the element, unless the element itself is null,
+ * in which case the return type is Object[]
+ * ArrayUtils.add(null, null) = [null] + * ArrayUtils.add(null, "a") = ["a"] + * ArrayUtils.add(["a"], null) = ["a", null] + * ArrayUtils.add(["a"], "b") = ["a", "b"] + * ArrayUtils.add(["a", "b"], "c") = ["a", "b", "c"] + *+ * + * @param array the array to "add" the element to, may be
null
+ * @param element the object to add, may be null
+ * @return A new array containing the existing elements plus the new element
+ * The returned array type will be that of the input array (unless null),
+ * in which case it will have the same type as the element.
+ * @since 2.1
+ */
+ public static Object[] add(Object[] array, Object element) {
+ Class type;
+ if (array != null){
+ type = array.getClass();
+ } else if (element != null) {
+ type = element.getClass();
+ } else {
+ type = Object.class;
+ }
+ Object[] newArray = (Object[]) copyArrayGrow1(array, type);
+ newArray[newArray.length - 1] = element;
+ return newArray;
+ }
+
+ /**
+ * Copies the given array and adds the given element at the end of the new array.
+ * + *The new array contains the same elements of the input + * array plus the given element in the last position. The component type of + * the new array is the same as that of the input array.
+ * + *If the input array is null
, a new one element array is returned
+ * whose component type is the same as the element.
+ * ArrayUtils.add(null, true) = [true] + * ArrayUtils.add([true], false) = [true, false] + * ArrayUtils.add([true, false], true) = [true, false, true] + *+ * + * @param array the array to copy and add the element to, may be
null
+ * @param element the object to add at the last index of the new array
+ * @return A new array containing the existing elements plus the new element
+ * @since 2.1
+ */
+ public static boolean[] add(boolean[] array, boolean element) {
+ boolean[] newArray = (boolean[])copyArrayGrow1(array, Boolean.TYPE);
+ newArray[newArray.length - 1] = element;
+ return newArray;
+ }
+
+ /**
+ * Copies the given array and adds the given element at the end of the new array.
+ * + *The new array contains the same elements of the input + * array plus the given element in the last position. The component type of + * the new array is the same as that of the input array.
+ * + *If the input array is null
, a new one element array is returned
+ * whose component type is the same as the element.
+ * ArrayUtils.add(null, 0) = [0] + * ArrayUtils.add([1], 0) = [1, 0] + * ArrayUtils.add([1, 0], 1) = [1, 0, 1] + *+ * + * @param array the array to copy and add the element to, may be
null
+ * @param element the object to add at the last index of the new array
+ * @return A new array containing the existing elements plus the new element
+ * @since 2.1
+ */
+ public static byte[] add(byte[] array, byte element) {
+ byte[] newArray = (byte[])copyArrayGrow1(array, Byte.TYPE);
+ newArray[newArray.length - 1] = element;
+ return newArray;
+ }
+
+ /**
+ * Copies the given array and adds the given element at the end of the new array.
+ * + *The new array contains the same elements of the input + * array plus the given element in the last position. The component type of + * the new array is the same as that of the input array.
+ * + *If the input array is null
, a new one element array is returned
+ * whose component type is the same as the element.
+ * ArrayUtils.add(null, '0') = ['0'] + * ArrayUtils.add(['1'], '0') = ['1', '0'] + * ArrayUtils.add(['1', '0'], '1') = ['1', '0', '1'] + *+ * + * @param array the array to copy and add the element to, may be
null
+ * @param element the object to add at the last index of the new array
+ * @return A new array containing the existing elements plus the new element
+ * @since 2.1
+ */
+ public static char[] add(char[] array, char element) {
+ char[] newArray = (char[])copyArrayGrow1(array, Character.TYPE);
+ newArray[newArray.length - 1] = element;
+ return newArray;
+ }
+
+ /**
+ * Copies the given array and adds the given element at the end of the new array.
+ * + *The new array contains the same elements of the input + * array plus the given element in the last position. The component type of + * the new array is the same as that of the input array.
+ * + *If the input array is null
, a new one element array is returned
+ * whose component type is the same as the element.
+ * ArrayUtils.add(null, 0) = [0] + * ArrayUtils.add([1], 0) = [1, 0] + * ArrayUtils.add([1, 0], 1) = [1, 0, 1] + *+ * + * @param array the array to copy and add the element to, may be
null
+ * @param element the object to add at the last index of the new array
+ * @return A new array containing the existing elements plus the new element
+ * @since 2.1
+ */
+ public static double[] add(double[] array, double element) {
+ double[] newArray = (double[])copyArrayGrow1(array, Double.TYPE);
+ newArray[newArray.length - 1] = element;
+ return newArray;
+ }
+
+ /**
+ * Copies the given array and adds the given element at the end of the new array.
+ * + *The new array contains the same elements of the input + * array plus the given element in the last position. The component type of + * the new array is the same as that of the input array.
+ * + *If the input array is null
, a new one element array is returned
+ * whose component type is the same as the element.
+ * ArrayUtils.add(null, 0) = [0] + * ArrayUtils.add([1], 0) = [1, 0] + * ArrayUtils.add([1, 0], 1) = [1, 0, 1] + *+ * + * @param array the array to copy and add the element to, may be
null
+ * @param element the object to add at the last index of the new array
+ * @return A new array containing the existing elements plus the new element
+ * @since 2.1
+ */
+ public static float[] add(float[] array, float element) {
+ float[] newArray = (float[])copyArrayGrow1(array, Float.TYPE);
+ newArray[newArray.length - 1] = element;
+ return newArray;
+ }
+
+ /**
+ * Copies the given array and adds the given element at the end of the new array.
+ * + *The new array contains the same elements of the input + * array plus the given element in the last position. The component type of + * the new array is the same as that of the input array.
+ * + *If the input array is null
, a new one element array is returned
+ * whose component type is the same as the element.
+ * ArrayUtils.add(null, 0) = [0] + * ArrayUtils.add([1], 0) = [1, 0] + * ArrayUtils.add([1, 0], 1) = [1, 0, 1] + *+ * + * @param array the array to copy and add the element to, may be
null
+ * @param element the object to add at the last index of the new array
+ * @return A new array containing the existing elements plus the new element
+ * @since 2.1
+ */
+ public static int[] add(int[] array, int element) {
+ int[] newArray = (int[])copyArrayGrow1(array, Integer.TYPE);
+ newArray[newArray.length - 1] = element;
+ return newArray;
+ }
+
+ /**
+ * Copies the given array and adds the given element at the end of the new array.
+ * + *The new array contains the same elements of the input + * array plus the given element in the last position. The component type of + * the new array is the same as that of the input array.
+ * + *If the input array is null
, a new one element array is returned
+ * whose component type is the same as the element.
+ * ArrayUtils.add(null, 0) = [0] + * ArrayUtils.add([1], 0) = [1, 0] + * ArrayUtils.add([1, 0], 1) = [1, 0, 1] + *+ * + * @param array the array to copy and add the element to, may be
null
+ * @param element the object to add at the last index of the new array
+ * @return A new array containing the existing elements plus the new element
+ * @since 2.1
+ */
+ public static long[] add(long[] array, long element) {
+ long[] newArray = (long[])copyArrayGrow1(array, Long.TYPE);
+ newArray[newArray.length - 1] = element;
+ return newArray;
+ }
+
+ /**
+ * Copies the given array and adds the given element at the end of the new array.
+ * + *The new array contains the same elements of the input + * array plus the given element in the last position. The component type of + * the new array is the same as that of the input array.
+ * + *If the input array is null
, a new one element array is returned
+ * whose component type is the same as the element.
+ * ArrayUtils.add(null, 0) = [0] + * ArrayUtils.add([1], 0) = [1, 0] + * ArrayUtils.add([1, 0], 1) = [1, 0, 1] + *+ * + * @param array the array to copy and add the element to, may be
null
+ * @param element the object to add at the last index of the new array
+ * @return A new array containing the existing elements plus the new element
+ * @since 2.1
+ */
+ public static short[] add(short[] array, short element) {
+ short[] newArray = (short[])copyArrayGrow1(array, Short.TYPE);
+ newArray[newArray.length - 1] = element;
+ return newArray;
+ }
+
+ /**
+ * Returns a copy of the given array of size 1 greater than the argument.
+ * The last value of the array is left to the default value.
+ *
+ * @param array The array to copy, must not be null
.
+ * @param newArrayComponentType If array
is null
, create a
+ * size 1 array of this type.
+ * @return A new copy of the array of size 1 greater than the input.
+ */
+ private static Object copyArrayGrow1(Object array, Class newArrayComponentType) {
+ if (array != null) {
+ int arrayLength = Array.getLength(array);
+ Object newArray = Array.newInstance(array.getClass().getComponentType(), arrayLength + 1);
+ System.arraycopy(array, 0, newArray, 0, arrayLength);
+ return newArray;
+ }
+ return Array.newInstance(newArrayComponentType, 1);
+ }
+
+ /**
+ * Inserts the specified element at the specified position in the array. + * Shifts the element currently at that position (if any) and any subsequent + * elements to the right (adds one to their indices).
+ * + *This method returns a new array with the same elements of the input + * array plus the given element on the specified position. The component + * type of the returned array is always the same as that of the input + * array.
+ * + *If the input array is null
, a new one element array is returned
+ * whose component type is the same as the element.
+ * ArrayUtils.add(null, 0, null) = [null] + * ArrayUtils.add(null, 0, "a") = ["a"] + * ArrayUtils.add(["a"], 1, null) = ["a", null] + * ArrayUtils.add(["a"], 1, "b") = ["a", "b"] + * ArrayUtils.add(["a", "b"], 3, "c") = ["a", "b", "c"] + *+ * + * @param array the array to add the element to, may be
null
+ * @param index the position of the new object
+ * @param element the object to add
+ * @return A new array containing the existing elements and the new element
+ * @throws IndexOutOfBoundsException if the index is out of range
+ * (index < 0 || index > array.length).
+ */
+ public static Object[] add(Object[] array, int index, Object element) {
+ Class clss = null;
+ if (array != null) {
+ clss = array.getClass().getComponentType();
+ } else if (element != null) {
+ clss = element.getClass();
+ } else {
+ return new Object[]{null};
+ }
+ return (Object[]) add(array, index, element, clss);
+ }
+
+ /**
+ * Inserts the specified element at the specified position in the array. + * Shifts the element currently at that position (if any) and any subsequent + * elements to the right (adds one to their indices).
+ * + *This method returns a new array with the same elements of the input + * array plus the given element on the specified position. The component + * type of the returned array is always the same as that of the input + * array.
+ * + *If the input array is null
, a new one element array is returned
+ * whose component type is the same as the element.
+ * ArrayUtils.add(null, 0, true) = [true] + * ArrayUtils.add([true], 0, false) = [false, true] + * ArrayUtils.add([false], 1, true) = [false, true] + * ArrayUtils.add([true, false], 1, true) = [true, true, false] + *+ * + * @param array the array to add the element to, may be
null
+ * @param index the position of the new object
+ * @param element the object to add
+ * @return A new array containing the existing elements and the new element
+ * @throws IndexOutOfBoundsException if the index is out of range
+ * (index < 0 || index > array.length).
+ */
+ public static boolean[] add(boolean[] array, int index, boolean element) {
+ return (boolean[]) add(array, index, BooleanUtils.toBooleanObject(element), Boolean.TYPE);
+ }
+
+ /**
+ * Inserts the specified element at the specified position in the array. + * Shifts the element currently at that position (if any) and any subsequent + * elements to the right (adds one to their indices).
+ * + *This method returns a new array with the same elements of the input + * array plus the given element on the specified position. The component + * type of the returned array is always the same as that of the input + * array.
+ * + *If the input array is null
, a new one element array is returned
+ * whose component type is the same as the element.
+ * ArrayUtils.add(null, 0, 'a') = ['a'] + * ArrayUtils.add(['a'], 0, 'b') = ['b', 'a'] + * ArrayUtils.add(['a', 'b'], 0, 'c') = ['c', 'a', 'b'] + * ArrayUtils.add(['a', 'b'], 1, 'k') = ['a', 'k', 'b'] + * ArrayUtils.add(['a', 'b', 'c'], 1, 't') = ['a', 't', 'b', 'c'] + *+ * + * @param array the array to add the element to, may be
null
+ * @param index the position of the new object
+ * @param element the object to add
+ * @return A new array containing the existing elements and the new element
+ * @throws IndexOutOfBoundsException if the index is out of range
+ * (index < 0 || index > array.length).
+ */
+ public static char[] add(char[] array, int index, char element) {
+ return (char[]) add(array, index, new Character(element), Character.TYPE);
+ }
+
+ /**
+ * Inserts the specified element at the specified position in the array. + * Shifts the element currently at that position (if any) and any subsequent + * elements to the right (adds one to their indices).
+ * + *This method returns a new array with the same elements of the input + * array plus the given element on the specified position. The component + * type of the returned array is always the same as that of the input + * array.
+ * + *If the input array is null
, a new one element array is returned
+ * whose component type is the same as the element.
+ * ArrayUtils.add([1], 0, 2) = [2, 1] + * ArrayUtils.add([2, 6], 2, 3) = [2, 6, 3] + * ArrayUtils.add([2, 6], 0, 1) = [1, 2, 6] + * ArrayUtils.add([2, 6, 3], 2, 1) = [2, 6, 1, 3] + *+ * + * @param array the array to add the element to, may be
null
+ * @param index the position of the new object
+ * @param element the object to add
+ * @return A new array containing the existing elements and the new element
+ * @throws IndexOutOfBoundsException if the index is out of range
+ * (index < 0 || index > array.length).
+ */
+ public static byte[] add(byte[] array, int index, byte element) {
+ return (byte[]) add(array, index, new Byte(element), Byte.TYPE);
+ }
+
+ /**
+ * Inserts the specified element at the specified position in the array. + * Shifts the element currently at that position (if any) and any subsequent + * elements to the right (adds one to their indices).
+ * + *This method returns a new array with the same elements of the input + * array plus the given element on the specified position. The component + * type of the returned array is always the same as that of the input + * array.
+ * + *If the input array is null
, a new one element array is returned
+ * whose component type is the same as the element.
+ * ArrayUtils.add([1], 0, 2) = [2, 1] + * ArrayUtils.add([2, 6], 2, 10) = [2, 6, 10] + * ArrayUtils.add([2, 6], 0, -4) = [-4, 2, 6] + * ArrayUtils.add([2, 6, 3], 2, 1) = [2, 6, 1, 3] + *+ * + * @param array the array to add the element to, may be
null
+ * @param index the position of the new object
+ * @param element the object to add
+ * @return A new array containing the existing elements and the new element
+ * @throws IndexOutOfBoundsException if the index is out of range
+ * (index < 0 || index > array.length).
+ */
+ public static short[] add(short[] array, int index, short element) {
+ return (short[]) add(array, index, new Short(element), Short.TYPE);
+ }
+
+ /**
+ * Inserts the specified element at the specified position in the array. + * Shifts the element currently at that position (if any) and any subsequent + * elements to the right (adds one to their indices).
+ * + *This method returns a new array with the same elements of the input + * array plus the given element on the specified position. The component + * type of the returned array is always the same as that of the input + * array.
+ * + *If the input array is null
, a new one element array is returned
+ * whose component type is the same as the element.
+ * ArrayUtils.add([1], 0, 2) = [2, 1] + * ArrayUtils.add([2, 6], 2, 10) = [2, 6, 10] + * ArrayUtils.add([2, 6], 0, -4) = [-4, 2, 6] + * ArrayUtils.add([2, 6, 3], 2, 1) = [2, 6, 1, 3] + *+ * + * @param array the array to add the element to, may be
null
+ * @param index the position of the new object
+ * @param element the object to add
+ * @return A new array containing the existing elements and the new element
+ * @throws IndexOutOfBoundsException if the index is out of range
+ * (index < 0 || index > array.length).
+ */
+ public static int[] add(int[] array, int index, int element) {
+ return (int[]) add(array, index, new Integer(element), Integer.TYPE);
+ }
+
+ /**
+ * Inserts the specified element at the specified position in the array. + * Shifts the element currently at that position (if any) and any subsequent + * elements to the right (adds one to their indices).
+ * + *This method returns a new array with the same elements of the input + * array plus the given element on the specified position. The component + * type of the returned array is always the same as that of the input + * array.
+ * + *If the input array is null
, a new one element array is returned
+ * whose component type is the same as the element.
+ * ArrayUtils.add([1L], 0, 2L) = [2L, 1L] + * ArrayUtils.add([2L, 6L], 2, 10L) = [2L, 6L, 10L] + * ArrayUtils.add([2L, 6L], 0, -4L) = [-4L, 2L, 6L] + * ArrayUtils.add([2L, 6L, 3L], 2, 1L) = [2L, 6L, 1L, 3L] + *+ * + * @param array the array to add the element to, may be
null
+ * @param index the position of the new object
+ * @param element the object to add
+ * @return A new array containing the existing elements and the new element
+ * @throws IndexOutOfBoundsException if the index is out of range
+ * (index < 0 || index > array.length).
+ */
+ public static long[] add(long[] array, int index, long element) {
+ return (long[]) add(array, index, new Long(element), Long.TYPE);
+ }
+
+ /**
+ * Inserts the specified element at the specified position in the array. + * Shifts the element currently at that position (if any) and any subsequent + * elements to the right (adds one to their indices).
+ * + *This method returns a new array with the same elements of the input + * array plus the given element on the specified position. The component + * type of the returned array is always the same as that of the input + * array.
+ * + *If the input array is null
, a new one element array is returned
+ * whose component type is the same as the element.
+ * ArrayUtils.add([1.1f], 0, 2.2f) = [2.2f, 1.1f] + * ArrayUtils.add([2.3f, 6.4f], 2, 10.5f) = [2.3f, 6.4f, 10.5f] + * ArrayUtils.add([2.6f, 6.7f], 0, -4.8f) = [-4.8f, 2.6f, 6.7f] + * ArrayUtils.add([2.9f, 6.0f, 0.3f], 2, 1.0f) = [2.9f, 6.0f, 1.0f, 0.3f] + *+ * + * @param array the array to add the element to, may be
null
+ * @param index the position of the new object
+ * @param element the object to add
+ * @return A new array containing the existing elements and the new element
+ * @throws IndexOutOfBoundsException if the index is out of range
+ * (index < 0 || index > array.length).
+ */
+ public static float[] add(float[] array, int index, float element) {
+ return (float[]) add(array, index, new Float(element), Float.TYPE);
+ }
+
+ /**
+ * Inserts the specified element at the specified position in the array. + * Shifts the element currently at that position (if any) and any subsequent + * elements to the right (adds one to their indices).
+ * + *This method returns a new array with the same elements of the input + * array plus the given element on the specified position. The component + * type of the returned array is always the same as that of the input + * array.
+ * + *If the input array is null
, a new one element array is returned
+ * whose component type is the same as the element.
+ * ArrayUtils.add([1.1], 0, 2.2) = [2.2, 1.1] + * ArrayUtils.add([2.3, 6.4], 2, 10.5) = [2.3, 6.4, 10.5] + * ArrayUtils.add([2.6, 6.7], 0, -4.8) = [-4.8, 2.6, 6.7] + * ArrayUtils.add([2.9, 6.0, 0.3], 2, 1.0) = [2.9, 6.0, 1.0, 0.3] + *+ * + * @param array the array to add the element to, may be
null
+ * @param index the position of the new object
+ * @param element the object to add
+ * @return A new array containing the existing elements and the new element
+ * @throws IndexOutOfBoundsException if the index is out of range
+ * (index < 0 || index > array.length).
+ */
+ public static double[] add(double[] array, int index, double element) {
+ return (double[]) add(array, index, new Double(element), Double.TYPE);
+ }
+
+ /**
+ * Underlying implementation of add(array, index, element) methods.
+ * The last parameter is the class, which may not equal element.getClass
+ * for primitives.
+ *
+ * @param array the array to add the element to, may be null
+ * @param index the position of the new object
+ * @param element the object to add
+ * @param clss the type of the element being added
+ * @return A new array containing the existing elements and the new element
+ */
+ private static Object add(Object array, int index, Object element, Class clss) {
+ if (array == null) {
+ if (index != 0) {
+ throw new IndexOutOfBoundsException("Index: " + index + ", Length: 0");
+ }
+ Object joinedArray = Array.newInstance(clss, 1);
+ Array.set(joinedArray, 0, element);
+ return joinedArray;
+ }
+ int length = Array.getLength(array);
+ if (index > length || index < 0) {
+ throw new IndexOutOfBoundsException("Index: " + index + ", Length: " + length);
+ }
+ Object result = Array.newInstance(clss, length + 1);
+ System.arraycopy(array, 0, result, 0, index);
+ Array.set(result, index, element);
+ if (index < length) {
+ System.arraycopy(array, index, result, index + 1, length - index);
+ }
+ return result;
+ }
+
+ /**
+ * Removes the element at the specified position from the specified array. + * All subsequent elements are shifted to the left (substracts one from + * their indices).
+ * + *This method returns a new array with the same elements of the input + * array except the element on the specified position. The component + * type of the returned array is always the same as that of the input + * array.
+ * + *If the input array is null
, an IndexOutOfBoundsException
+ * will be thrown, because in that case no valid index can be specified.
+ * ArrayUtils.remove(["a"], 0) = [] + * ArrayUtils.remove(["a", "b"], 0) = ["b"] + * ArrayUtils.remove(["a", "b"], 1) = ["a"] + * ArrayUtils.remove(["a", "b", "c"], 1) = ["a", "c"] + *+ * + * @param array the array to remove the element from, may not be
null
+ * @param index the position of the element to be removed
+ * @return A new array containing the existing elements except the element
+ * at the specified position.
+ * @throws IndexOutOfBoundsException if the index is out of range
+ * (index < 0 || index >= array.length), or if the array is null
.
+ * @since 2.1
+ */
+ public static Object[] remove(Object[] array, int index) {
+ return (Object[]) remove((Object) array, index);
+ }
+
+ /**
+ * Removes the first occurrence of the specified element from the + * specified array. All subsequent elements are shifted to the left + * (substracts one from their indices). If the array doesn't contains + * such an element, no elements are removed from the array.
+ * + *This method returns a new array with the same elements of the input + * array except the first occurrence of the specified element. The component + * type of the returned array is always the same as that of the input + * array.
+ * + *+ * ArrayUtils.removeElement(null, "a") = null + * ArrayUtils.removeElement([], "a") = [] + * ArrayUtils.removeElement(["a"], "b") = ["a"] + * ArrayUtils.removeElement(["a", "b"], "a") = ["b"] + * ArrayUtils.removeElement(["a", "b", "a"], "a") = ["b", "a"] + *+ * + * @param array the array to remove the element from, may be
null
+ * @param element the element to be removed
+ * @return A new array containing the existing elements except the first
+ * occurrence of the specified element.
+ * @since 2.1
+ */
+ public static Object[] removeElement(Object[] array, Object element) {
+ int index = indexOf(array, element);
+ if (index == INDEX_NOT_FOUND) {
+ return clone(array);
+ }
+ return remove(array, index);
+ }
+
+ /**
+ * Removes the element at the specified position from the specified array. + * All subsequent elements are shifted to the left (substracts one from + * their indices).
+ * + *This method returns a new array with the same elements of the input + * array except the element on the specified position. The component + * type of the returned array is always the same as that of the input + * array.
+ * + *If the input array is null
, an IndexOutOfBoundsException
+ * will be thrown, because in that case no valid index can be specified.
+ * ArrayUtils.remove([true], 0) = [] + * ArrayUtils.remove([true, false], 0) = [false] + * ArrayUtils.remove([true, false], 1) = [true] + * ArrayUtils.remove([true, true, false], 1) = [true, false] + *+ * + * @param array the array to remove the element from, may not be
null
+ * @param index the position of the element to be removed
+ * @return A new array containing the existing elements except the element
+ * at the specified position.
+ * @throws IndexOutOfBoundsException if the index is out of range
+ * (index < 0 || index >= array.length), or if the array is null
.
+ * @since 2.1
+ */
+ public static boolean[] remove(boolean[] array, int index) {
+ return (boolean[]) remove((Object) array, index);
+ }
+
+ /**
+ * Removes the first occurrence of the specified element from the + * specified array. All subsequent elements are shifted to the left + * (substracts one from their indices). If the array doesn't contains + * such an element, no elements are removed from the array.
+ * + *This method returns a new array with the same elements of the input + * array except the first occurrence of the specified element. The component + * type of the returned array is always the same as that of the input + * array.
+ * + *+ * ArrayUtils.removeElement(null, true) = null + * ArrayUtils.removeElement([], true) = [] + * ArrayUtils.removeElement([true], false) = [true] + * ArrayUtils.removeElement([true, false], false) = [true] + * ArrayUtils.removeElement([true, false, true], true) = [false, true] + *+ * + * @param array the array to remove the element from, may be
null
+ * @param element the element to be removed
+ * @return A new array containing the existing elements except the first
+ * occurrence of the specified element.
+ * @since 2.1
+ */
+ public static boolean[] removeElement(boolean[] array, boolean element) {
+ int index = indexOf(array, element);
+ if (index == INDEX_NOT_FOUND) {
+ return clone(array);
+ }
+ return remove(array, index);
+ }
+
+ /**
+ * Removes the element at the specified position from the specified array. + * All subsequent elements are shifted to the left (substracts one from + * their indices).
+ * + *This method returns a new array with the same elements of the input + * array except the element on the specified position. The component + * type of the returned array is always the same as that of the input + * array.
+ * + *If the input array is null
, an IndexOutOfBoundsException
+ * will be thrown, because in that case no valid index can be specified.
+ * ArrayUtils.remove([1], 0) = [] + * ArrayUtils.remove([1, 0], 0) = [0] + * ArrayUtils.remove([1, 0], 1) = [1] + * ArrayUtils.remove([1, 0, 1], 1) = [1, 1] + *+ * + * @param array the array to remove the element from, may not be
null
+ * @param index the position of the element to be removed
+ * @return A new array containing the existing elements except the element
+ * at the specified position.
+ * @throws IndexOutOfBoundsException if the index is out of range
+ * (index < 0 || index >= array.length), or if the array is null
.
+ * @since 2.1
+ */
+ public static byte[] remove(byte[] array, int index) {
+ return (byte[]) remove((Object) array, index);
+ }
+
+ /**
+ * Removes the first occurrence of the specified element from the + * specified array. All subsequent elements are shifted to the left + * (substracts one from their indices). If the array doesn't contains + * such an element, no elements are removed from the array.
+ * + *This method returns a new array with the same elements of the input + * array except the first occurrence of the specified element. The component + * type of the returned array is always the same as that of the input + * array.
+ * + *+ * ArrayUtils.removeElement(null, 1) = null + * ArrayUtils.removeElement([], 1) = [] + * ArrayUtils.removeElement([1], 0) = [1] + * ArrayUtils.removeElement([1, 0], 0) = [1] + * ArrayUtils.removeElement([1, 0, 1], 1) = [0, 1] + *+ * + * @param array the array to remove the element from, may be
null
+ * @param element the element to be removed
+ * @return A new array containing the existing elements except the first
+ * occurrence of the specified element.
+ * @since 2.1
+ */
+ public static byte[] removeElement(byte[] array, byte element) {
+ int index = indexOf(array, element);
+ if (index == INDEX_NOT_FOUND) {
+ return clone(array);
+ }
+ return remove(array, index);
+ }
+
+ /**
+ * Removes the element at the specified position from the specified array. + * All subsequent elements are shifted to the left (substracts one from + * their indices).
+ * + *This method returns a new array with the same elements of the input + * array except the element on the specified position. The component + * type of the returned array is always the same as that of the input + * array.
+ * + *If the input array is null
, an IndexOutOfBoundsException
+ * will be thrown, because in that case no valid index can be specified.
+ * ArrayUtils.remove(['a'], 0) = [] + * ArrayUtils.remove(['a', 'b'], 0) = ['b'] + * ArrayUtils.remove(['a', 'b'], 1) = ['a'] + * ArrayUtils.remove(['a', 'b', 'c'], 1) = ['a', 'c'] + *+ * + * @param array the array to remove the element from, may not be
null
+ * @param index the position of the element to be removed
+ * @return A new array containing the existing elements except the element
+ * at the specified position.
+ * @throws IndexOutOfBoundsException if the index is out of range
+ * (index < 0 || index >= array.length), or if the array is null
.
+ * @since 2.1
+ */
+ public static char[] remove(char[] array, int index) {
+ return (char[]) remove((Object) array, index);
+ }
+
+ /**
+ * Removes the first occurrence of the specified element from the + * specified array. All subsequent elements are shifted to the left + * (substracts one from their indices). If the array doesn't contains + * such an element, no elements are removed from the array.
+ * + *This method returns a new array with the same elements of the input + * array except the first occurrence of the specified element. The component + * type of the returned array is always the same as that of the input + * array.
+ * + *+ * ArrayUtils.removeElement(null, 'a') = null + * ArrayUtils.removeElement([], 'a') = [] + * ArrayUtils.removeElement(['a'], 'b') = ['a'] + * ArrayUtils.removeElement(['a', 'b'], 'a') = ['b'] + * ArrayUtils.removeElement(['a', 'b', 'a'], 'a') = ['b', 'a'] + *+ * + * @param array the array to remove the element from, may be
null
+ * @param element the element to be removed
+ * @return A new array containing the existing elements except the first
+ * occurrence of the specified element.
+ * @since 2.1
+ */
+ public static char[] removeElement(char[] array, char element) {
+ int index = indexOf(array, element);
+ if (index == INDEX_NOT_FOUND) {
+ return clone(array);
+ }
+ return remove(array, index);
+ }
+
+ /**
+ * Removes the element at the specified position from the specified array. + * All subsequent elements are shifted to the left (substracts one from + * their indices).
+ * + *This method returns a new array with the same elements of the input + * array except the element on the specified position. The component + * type of the returned array is always the same as that of the input + * array.
+ * + *If the input array is null
, an IndexOutOfBoundsException
+ * will be thrown, because in that case no valid index can be specified.
+ * ArrayUtils.remove([1.1], 0) = [] + * ArrayUtils.remove([2.5, 6.0], 0) = [6.0] + * ArrayUtils.remove([2.5, 6.0], 1) = [2.5] + * ArrayUtils.remove([2.5, 6.0, 3.8], 1) = [2.5, 3.8] + *+ * + * @param array the array to remove the element from, may not be
null
+ * @param index the position of the element to be removed
+ * @return A new array containing the existing elements except the element
+ * at the specified position.
+ * @throws IndexOutOfBoundsException if the index is out of range
+ * (index < 0 || index >= array.length), or if the array is null
.
+ * @since 2.1
+ */
+ public static double[] remove(double[] array, int index) {
+ return (double[]) remove((Object) array, index);
+ }
+
+ /**
+ * Removes the first occurrence of the specified element from the + * specified array. All subsequent elements are shifted to the left + * (substracts one from their indices). If the array doesn't contains + * such an element, no elements are removed from the array.
+ * + *This method returns a new array with the same elements of the input + * array except the first occurrence of the specified element. The component + * type of the returned array is always the same as that of the input + * array.
+ * + *+ * ArrayUtils.removeElement(null, 1.1) = null + * ArrayUtils.removeElement([], 1.1) = [] + * ArrayUtils.removeElement([1.1], 1.2) = [1.1] + * ArrayUtils.removeElement([1.1, 2.3], 1.1) = [2.3] + * ArrayUtils.removeElement([1.1, 2.3, 1.1], 1.1) = [2.3, 1.1] + *+ * + * @param array the array to remove the element from, may be
null
+ * @param element the element to be removed
+ * @return A new array containing the existing elements except the first
+ * occurrence of the specified element.
+ * @since 2.1
+ */
+ public static double[] removeElement(double[] array, double element) {
+ int index = indexOf(array, element);
+ if (index == INDEX_NOT_FOUND) {
+ return clone(array);
+ }
+ return remove(array, index);
+ }
+
+ /**
+ * Removes the element at the specified position from the specified array. + * All subsequent elements are shifted to the left (substracts one from + * their indices).
+ * + *This method returns a new array with the same elements of the input + * array except the element on the specified position. The component + * type of the returned array is always the same as that of the input + * array.
+ * + *If the input array is null
, an IndexOutOfBoundsException
+ * will be thrown, because in that case no valid index can be specified.
+ * ArrayUtils.remove([1.1], 0) = [] + * ArrayUtils.remove([2.5, 6.0], 0) = [6.0] + * ArrayUtils.remove([2.5, 6.0], 1) = [2.5] + * ArrayUtils.remove([2.5, 6.0, 3.8], 1) = [2.5, 3.8] + *+ * + * @param array the array to remove the element from, may not be
null
+ * @param index the position of the element to be removed
+ * @return A new array containing the existing elements except the element
+ * at the specified position.
+ * @throws IndexOutOfBoundsException if the index is out of range
+ * (index < 0 || index >= array.length), or if the array is null
.
+ * @since 2.1
+ */
+ public static float[] remove(float[] array, int index) {
+ return (float[]) remove((Object) array, index);
+ }
+
+ /**
+ * Removes the first occurrence of the specified element from the + * specified array. All subsequent elements are shifted to the left + * (substracts one from their indices). If the array doesn't contains + * such an element, no elements are removed from the array.
+ * + *This method returns a new array with the same elements of the input + * array except the first occurrence of the specified element. The component + * type of the returned array is always the same as that of the input + * array.
+ * + *+ * ArrayUtils.removeElement(null, 1.1) = null + * ArrayUtils.removeElement([], 1.1) = [] + * ArrayUtils.removeElement([1.1], 1.2) = [1.1] + * ArrayUtils.removeElement([1.1, 2.3], 1.1) = [2.3] + * ArrayUtils.removeElement([1.1, 2.3, 1.1], 1.1) = [2.3, 1.1] + *+ * + * @param array the array to remove the element from, may be
null
+ * @param element the element to be removed
+ * @return A new array containing the existing elements except the first
+ * occurrence of the specified element.
+ * @since 2.1
+ */
+ public static float[] removeElement(float[] array, float element) {
+ int index = indexOf(array, element);
+ if (index == INDEX_NOT_FOUND) {
+ return clone(array);
+ }
+ return remove(array, index);
+ }
+
+ /**
+ * Removes the element at the specified position from the specified array. + * All subsequent elements are shifted to the left (substracts one from + * their indices).
+ * + *This method returns a new array with the same elements of the input + * array except the element on the specified position. The component + * type of the returned array is always the same as that of the input + * array.
+ * + *If the input array is null
, an IndexOutOfBoundsException
+ * will be thrown, because in that case no valid index can be specified.
+ * ArrayUtils.remove([1], 0) = [] + * ArrayUtils.remove([2, 6], 0) = [6] + * ArrayUtils.remove([2, 6], 1) = [2] + * ArrayUtils.remove([2, 6, 3], 1) = [2, 3] + *+ * + * @param array the array to remove the element from, may not be
null
+ * @param index the position of the element to be removed
+ * @return A new array containing the existing elements except the element
+ * at the specified position.
+ * @throws IndexOutOfBoundsException if the index is out of range
+ * (index < 0 || index >= array.length), or if the array is null
.
+ * @since 2.1
+ */
+ public static int[] remove(int[] array, int index) {
+ return (int[]) remove((Object) array, index);
+ }
+
+ /**
+ * Removes the first occurrence of the specified element from the + * specified array. All subsequent elements are shifted to the left + * (substracts one from their indices). If the array doesn't contains + * such an element, no elements are removed from the array.
+ * + *This method returns a new array with the same elements of the input + * array except the first occurrence of the specified element. The component + * type of the returned array is always the same as that of the input + * array.
+ * + *+ * ArrayUtils.removeElement(null, 1) = null + * ArrayUtils.removeElement([], 1) = [] + * ArrayUtils.removeElement([1], 2) = [1] + * ArrayUtils.removeElement([1, 3], 1) = [3] + * ArrayUtils.removeElement([1, 3, 1], 1) = [3, 1] + *+ * + * @param array the array to remove the element from, may be
null
+ * @param element the element to be removed
+ * @return A new array containing the existing elements except the first
+ * occurrence of the specified element.
+ * @since 2.1
+ */
+ public static int[] removeElement(int[] array, int element) {
+ int index = indexOf(array, element);
+ if (index == INDEX_NOT_FOUND) {
+ return clone(array);
+ }
+ return remove(array, index);
+ }
+
+ /**
+ * Removes the element at the specified position from the specified array. + * All subsequent elements are shifted to the left (substracts one from + * their indices).
+ * + *This method returns a new array with the same elements of the input + * array except the element on the specified position. The component + * type of the returned array is always the same as that of the input + * array.
+ * + *If the input array is null
, an IndexOutOfBoundsException
+ * will be thrown, because in that case no valid index can be specified.
+ * ArrayUtils.remove([1], 0) = [] + * ArrayUtils.remove([2, 6], 0) = [6] + * ArrayUtils.remove([2, 6], 1) = [2] + * ArrayUtils.remove([2, 6, 3], 1) = [2, 3] + *+ * + * @param array the array to remove the element from, may not be
null
+ * @param index the position of the element to be removed
+ * @return A new array containing the existing elements except the element
+ * at the specified position.
+ * @throws IndexOutOfBoundsException if the index is out of range
+ * (index < 0 || index >= array.length), or if the array is null
.
+ * @since 2.1
+ */
+ public static long[] remove(long[] array, int index) {
+ return (long[]) remove((Object) array, index);
+ }
+
+ /**
+ * Removes the first occurrence of the specified element from the + * specified array. All subsequent elements are shifted to the left + * (substracts one from their indices). If the array doesn't contains + * such an element, no elements are removed from the array.
+ * + *This method returns a new array with the same elements of the input + * array except the first occurrence of the specified element. The component + * type of the returned array is always the same as that of the input + * array.
+ * + *+ * ArrayUtils.removeElement(null, 1) = null + * ArrayUtils.removeElement([], 1) = [] + * ArrayUtils.removeElement([1], 2) = [1] + * ArrayUtils.removeElement([1, 3], 1) = [3] + * ArrayUtils.removeElement([1, 3, 1], 1) = [3, 1] + *+ * + * @param array the array to remove the element from, may be
null
+ * @param element the element to be removed
+ * @return A new array containing the existing elements except the first
+ * occurrence of the specified element.
+ * @since 2.1
+ */
+ public static long[] removeElement(long[] array, long element) {
+ int index = indexOf(array, element);
+ if (index == INDEX_NOT_FOUND) {
+ return clone(array);
+ }
+ return remove(array, index);
+ }
+
+ /**
+ * Removes the element at the specified position from the specified array. + * All subsequent elements are shifted to the left (substracts one from + * their indices).
+ * + *This method returns a new array with the same elements of the input + * array except the element on the specified position. The component + * type of the returned array is always the same as that of the input + * array.
+ * + *If the input array is null
, an IndexOutOfBoundsException
+ * will be thrown, because in that case no valid index can be specified.
+ * ArrayUtils.remove([1], 0) = [] + * ArrayUtils.remove([2, 6], 0) = [6] + * ArrayUtils.remove([2, 6], 1) = [2] + * ArrayUtils.remove([2, 6, 3], 1) = [2, 3] + *+ * + * @param array the array to remove the element from, may not be
null
+ * @param index the position of the element to be removed
+ * @return A new array containing the existing elements except the element
+ * at the specified position.
+ * @throws IndexOutOfBoundsException if the index is out of range
+ * (index < 0 || index >= array.length), or if the array is null
.
+ * @since 2.1
+ */
+ public static short[] remove(short[] array, int index) {
+ return (short[]) remove((Object) array, index);
+ }
+
+ /**
+ * Removes the first occurrence of the specified element from the + * specified array. All subsequent elements are shifted to the left + * (substracts one from their indices). If the array doesn't contains + * such an element, no elements are removed from the array.
+ * + *This method returns a new array with the same elements of the input + * array except the first occurrence of the specified element. The component + * type of the returned array is always the same as that of the input + * array.
+ * + *+ * ArrayUtils.removeElement(null, 1) = null + * ArrayUtils.removeElement([], 1) = [] + * ArrayUtils.removeElement([1], 2) = [1] + * ArrayUtils.removeElement([1, 3], 1) = [3] + * ArrayUtils.removeElement([1, 3, 1], 1) = [3, 1] + *+ * + * @param array the array to remove the element from, may be
null
+ * @param element the element to be removed
+ * @return A new array containing the existing elements except the first
+ * occurrence of the specified element.
+ * @since 2.1
+ */
+ public static short[] removeElement(short[] array, short element) {
+ int index = indexOf(array, element);
+ if (index == INDEX_NOT_FOUND) {
+ return clone(array);
+ }
+ return remove(array, index);
+ }
+
+ /**
+ * Removes the element at the specified position from the specified array. + * All subsequent elements are shifted to the left (substracts one from + * their indices).
+ * + *This method returns a new array with the same elements of the input + * array except the element on the specified position. The component + * type of the returned array is always the same as that of the input + * array.
+ * + *If the input array is null
, an IndexOutOfBoundsException
+ * will be thrown, because in that case no valid index can be specified.
null
+ * @param index the position of the element to be removed
+ * @return A new array containing the existing elements except the element
+ * at the specified position.
+ * @throws IndexOutOfBoundsException if the index is out of range
+ * (index < 0 || index >= array.length), or if the array is null
.
+ * @since 2.1
+ */
+ private static Object remove(Object array, int index) {
+ int length = getLength(array);
+ if (index < 0 || index >= length) {
+ throw new IndexOutOfBoundsException("Index: " + index + ", Length: " + length);
+ }
+
+ Object result = Array.newInstance(array.getClass().getComponentType(), length - 1);
+ System.arraycopy(array, 0, result, 0, index);
+ if (index < length - 1) {
+ System.arraycopy(array, index + 1, result, index, length - index - 1);
+ }
+
+ return result;
+ }
+
}
Index: 3rdParty_sources/commons-lang/org/apache/commons/lang/BitField.java
===================================================================
RCS file: /usr/local/cvsroot/3rdParty_sources/commons-lang/org/apache/commons/lang/BitField.java,v
diff -u -r1.1 -r1.2
--- 3rdParty_sources/commons-lang/org/apache/commons/lang/BitField.java 30 Aug 2012 16:24:42 -0000 1.1
+++ 3rdParty_sources/commons-lang/org/apache/commons/lang/BitField.java 15 Mar 2013 09:52:49 -0000 1.2
@@ -1,66 +1,29 @@
-/* ====================================================================
- * The Apache Software License, Version 1.1
- *
- * Copyright (c) 2002-2003 The Apache Software Foundation. All rights
- * reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in
- * the documentation and/or other materials provided with the
- * distribution.
- *
- * 3. The end-user documentation included with the redistribution, if
- * any, must include the following acknowledgement:
- * "This product includes software developed by the
- * Apache Software Foundation (http://www.apache.org/)."
- * Alternately, this acknowledgement may appear in the software itself,
- * if and wherever such third-party acknowledgements normally appear.
- *
- * 4. The names "The Jakarta Project", "Commons", and "Apache Software
- * Foundation" must not be used to endorse or promote products derived
- * from this software without prior written permission. For written
- * permission, please contact apache@apache.org.
- *
- * 5. Products derived from this software may not be called "Apache"
- * nor may "Apache" appear in their names without prior written
- * permission of the Apache Software Foundation.
- *
- * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
- * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
- * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
- * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- * ====================================================================
- *
- * This software consists of voluntary contributions made by many
- * individuals on behalf of the Apache Software Foundation. For more
- * information on the Apache Software Foundation, please see
- * Operations on bit-mapped fields.
* + * @author Apache Software Foundation * @author Apache Jakarta POI * @author Scott Sanders (sanders at apache dot org) * @author Marc Johnson (mjohnson at apache dot org) * @author Andrew C. Oliver (acoliver at apache dot org) - * @author Stephen Colebourne * @author Pete Gieser * @author Gary Gregory * @since 2.0 @@ -78,7 +41,7 @@ * BitField. Bits that are set in this mask are the bits * that this BitField operates on */ - public BitField(final int mask) { + public BitField(int mask) { _mask = mask; int count = 0; int bit_pattern = mask; @@ -101,12 +64,12 @@ * value is stored as a BitField (and so shifted left so many * bits). * - * @see #setValue + * @see #setValue(int,int) * @param holder the int data containing the bits we're interested * in * @return the selected bits, shifted right appropriately */ - public int getValue(final int holder) { + public int getValue(int holder) { return getRawValue(holder) >> _shift_count; } @@ -119,12 +82,12 @@ * value is stored as a BitField (and so shifted left so many * bits). * - * @see #setShortValue + * @see #setShortValue(short,short) * @param holder the short data containing the bits we're * interested in * @return the selected bits, shifted right appropriately */ - public short getShortValue(final short holder) { + public short getShortValue(short holder) { return (short) getValue(holder); } @@ -135,8 +98,8 @@ * interested in * @return the selected bits */ - public int getRawValue(final int holder) { - return (holder & _mask); + public int getRawValue(int holder) { + return holder & _mask; } /** @@ -146,7 +109,7 @@ * interested in * @return the selected bits */ - public short getShortRawValue(final short holder) { + public short getShortRawValue(short holder) { return (short) getRawValue(holder); } @@ -163,7 +126,7 @@ * @returntrue
if any of the bits are set,
* else false
*/
- public boolean isSet(final int holder) {
+ public boolean isSet(int holder) {
return (holder & _mask) != 0;
}
@@ -179,35 +142,35 @@
* @return true
if all of the bits are set,
* else false
*/
- public boolean isAllSet(final int holder) {
+ public boolean isAllSet(int holder) {
return (holder & _mask) == _mask;
}
/**
* Replaces the bits with new values.
* - * @see #getValue - * @param holder the int data containint the bits we're + * @see #getValue(int) + * @param holder the int data containing the bits we're * interested in * @param value the new value for the specified bits * @return the value of holder with the bits from the value * parameter replacing the old bits */ - public int setValue(final int holder, final int value) { + public int setValue(int holder, int value) { return (holder & ~_mask) | ((value << _shift_count) & _mask); } /** *Replaces the bits with new values.
* - * @see #getShortValue + * @see #getShortValue(short) * @param holder the short data containing the bits we're * interested in * @param value the new value for the specified bits * @return the value of holder with the bits from the value * parameter replacing the old bits */ - public short setShortValue(final short holder, final short value) { + public short setShortValue(short holder, short value) { return (short) setValue(holder, value); } @@ -219,7 +182,7 @@ * @return the value of holder with the specified bits cleared * (set to0
)
*/
- public int clear(final int holder) {
+ public int clear(int holder) {
return holder & ~_mask;
}
@@ -231,7 +194,7 @@
* @return the value of holder with the specified bits cleared
* (set to 0
)
*/
- public short clearShort(final short holder) {
+ public short clearShort(short holder) {
return (short) clear(holder);
}
@@ -244,7 +207,7 @@
* @return the value of holder with the specified bits cleared
* (set to 0
)
*/
- public byte clearByte(final byte holder) {
+ public byte clearByte(byte holder) {
return (byte) clear(holder);
}
@@ -256,7 +219,7 @@
* @return the value of holder with the specified bits set
* to 1
*/
- public int set(final int holder) {
+ public int set(int holder) {
return holder | _mask;
}
@@ -268,7 +231,7 @@
* @return the value of holder with the specified bits set
* to 1
*/
- public short setShort(final short holder) {
+ public short setShort(short holder) {
return (short) set(holder);
}
@@ -281,7 +244,7 @@
* @return the value of holder with the specified bits set
* to 1
*/
- public byte setByte(final byte holder) {
+ public byte setByte(byte holder) {
return (byte) set(holder);
}
@@ -294,7 +257,7 @@
* @return the value of holder with the specified bits set or
* cleared
*/
- public int setBoolean(final int holder, final boolean flag) {
+ public int setBoolean(int holder, boolean flag) {
return flag ? set(holder) : clear(holder);
}
@@ -307,7 +270,7 @@
* @return the value of holder with the specified bits set or
* cleared
*/
- public short setShortBoolean(final short holder, final boolean flag) {
+ public short setShortBoolean(short holder, boolean flag) {
return flag ? setShort(holder) : clearShort(holder);
}
@@ -320,7 +283,7 @@
* @return the value of holder with the specified bits set or
* cleared
*/
- public byte setByteBoolean(final byte holder, final boolean flag) {
+ public byte setByteBoolean(byte holder, boolean flag) {
return flag ? setByte(holder) : clearByte(holder);
}
Index: 3rdParty_sources/commons-lang/org/apache/commons/lang/BooleanUtils.java
===================================================================
RCS file: /usr/local/cvsroot/3rdParty_sources/commons-lang/org/apache/commons/lang/BooleanUtils.java,v
diff -u -r1.1 -r1.2
--- 3rdParty_sources/commons-lang/org/apache/commons/lang/BooleanUtils.java 30 Aug 2012 16:24:42 -0000 1.1
+++ 3rdParty_sources/commons-lang/org/apache/commons/lang/BooleanUtils.java 15 Mar 2013 09:52:49 -0000 1.2
@@ -1,55 +1,18 @@
-/* ====================================================================
- * The Apache Software License, Version 1.1
- *
- * Copyright (c) 2002-2003 The Apache Software Foundation. All rights
- * reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in
- * the documentation and/or other materials provided with the
- * distribution.
- *
- * 3. The end-user documentation included with the redistribution, if
- * any, must include the following acknowledgement:
- * "This product includes software developed by the
- * Apache Software Foundation (http://www.apache.org/)."
- * Alternately, this acknowledgement may appear in the software itself,
- * if and wherever such third-party acknowledgements normally appear.
- *
- * 4. The names "The Jakarta Project", "Commons", and "Apache Software
- * Foundation" must not be used to endorse or promote products derived
- * from this software without prior written permission. For written
- * permission, please contact apache@apache.org.
- *
- * 5. Products derived from this software may not be called "Apache"
- * nor may "Apache" appear in their names without prior written
- * permission of the Apache Software Foundation.
- *
- * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
- * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
- * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
- * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- * ====================================================================
- *
- * This software consists of voluntary contributions made by many
- * individuals on behalf of the Apache Software Foundation. For more
- * information on the Apache Software Foundation, please see
- * null
input.
* Each method documents its behaviour in more detail.
*
- * @author Stephen Colebourne
+ * #ThreadSafe#
+ * @author Apache Software Foundation * @author Matthew Hawthorne * @author Gary Gregory * @since 2.0 @@ -78,6 +42,7 @@ * to operate. */ public BooleanUtils() { + super(); } // Boolean utilities @@ -86,6 +51,12 @@ *Negates the specified boolean.
* *If null
is passed in, null
will be returned.
+ * 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
null
if null
input
@@ -100,21 +71,111 @@
// boolean Boolean methods
//-----------------------------------------------------------------------
/**
+ * Checks if a Boolean
value is true
,
+ * handling null
by returning false
.
+ * BooleanUtils.isTrue(Boolean.TRUE) = true + * BooleanUtils.isTrue(Boolean.FALSE) = false + * BooleanUtils.isTrue(null) = false + *+ * + * @param bool the boolean to check, null returns
false
+ * @return true
only if the input is non-null and true
+ * @since 2.1
+ */
+ public static boolean isTrue(Boolean bool) {
+ if (bool == null) {
+ return false;
+ }
+ return bool.booleanValue() ? true : false;
+ }
+
+ /**
+ * Checks if a Boolean
value is not true
,
+ * handling null
by returning true
.
+ * BooleanUtils.isNotTrue(Boolean.TRUE) = false + * BooleanUtils.isNotTrue(Boolean.FALSE) = true + * BooleanUtils.isNotTrue(null) = true + *+ * + * @param bool the boolean to check, null returns
true
+ * @return true
if the input is null or false
+ * @since 2.3
+ */
+ public static boolean isNotTrue(Boolean bool) {
+ return !isTrue(bool);
+ }
+
+ /**
+ * Checks if a Boolean
value is false
,
+ * handling null
by returning false
.
+ * BooleanUtils.isFalse(Boolean.TRUE) = false + * BooleanUtils.isFalse(Boolean.FALSE) = true + * BooleanUtils.isFalse(null) = false + *+ * + * @param bool the boolean to check, null returns
false
+ * @return true
only if the input is non-null and false
+ * @since 2.1
+ */
+ public static boolean isFalse(Boolean bool) {
+ if (bool == null) {
+ return false;
+ }
+ return bool.booleanValue() ? false : true;
+ }
+
+ /**
+ * Checks if a Boolean
value is not false
,
+ * handling null
by returning true
.
+ * BooleanUtils.isNotFalse(Boolean.TRUE) = true + * BooleanUtils.isNotFalse(Boolean.FALSE) = false + * BooleanUtils.isNotFalse(null) = true + *+ * + * @param bool the boolean to check, null returns
true
+ * @return true
if the input is null or true
+ * @since 2.3
+ */
+ public static boolean isNotFalse(Boolean bool) {
+ return !isFalse(bool);
+ }
+
+ //-----------------------------------------------------------------------
+ /**
* Boolean factory that avoids creating new Boolean objecs all the time.
* *This method was added to JDK1.4 but is available here for earlier JDKs.
- * + * + *+ * BooleanUtils.toBooleanObject(false) = Boolean.FALSE + * BooleanUtils.toBooleanObject(true) = Boolean.TRUE + *+ * * @param bool the boolean to convert * @return Boolean.TRUE or Boolean.FALSE as appropriate */ public static Boolean toBooleanObject(boolean bool) { - return (bool ? Boolean.TRUE : Boolean.FALSE); + return bool ? Boolean.TRUE : Boolean.FALSE; } /** *
Converts a Boolean to a boolean handling null
* by returning false
.
+ * BooleanUtils.toBoolean(Boolean.TRUE) = true + * BooleanUtils.toBoolean(Boolean.FALSE) = false + * BooleanUtils.toBoolean(null) = false + *+ * * @param bool the boolean to convert * @return
true
or false
,
* null
returns false
@@ -123,12 +184,18 @@
if (bool == null) {
return false;
}
- return (bool.booleanValue() ? true : false);
+ return bool.booleanValue() ? true : false;
}
/**
* Converts a Boolean to a boolean handling null
.
+ * BooleanUtils.toBooleanDefaultIfNull(Boolean.TRUE, false) = true + * BooleanUtils.toBooleanDefaultIfNull(Boolean.FALSE, true) = false + * BooleanUtils.toBooleanDefaultIfNull(null, true) = true + *+ * * @param bool the boolean to convert * @param valueIfNull the boolean value to return if
null
* @return true
or false
@@ -137,7 +204,7 @@
if (bool == null) {
return valueIfNull;
}
- return (bool.booleanValue() ? true : false);
+ return bool.booleanValue() ? true : false;
}
// Integer to Boolean methods
@@ -146,32 +213,50 @@
* Converts an int to a boolean using the convention that zero
* is false
.
+ * BooleanUtils.toBoolean(0) = false + * BooleanUtils.toBoolean(1) = true + * BooleanUtils.toBoolean(2) = true + *+ * * @param value the int to convert * @return
true
if non-zero, false
* if zero
*/
public static boolean toBoolean(int value) {
- return (value == 0 ? false : true);
+ return value == 0 ? false : true;
}
/**
* Converts an int to a Boolean using the convention that zero
* is false
.
+ * 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, *
null
if null
*/
public static Boolean toBooleanObject(int value) {
- return (value == 0 ? Boolean.FALSE : Boolean.TRUE);
+ return value == 0 ? Boolean.FALSE : Boolean.TRUE;
}
/**
* Converts an Integer to a Boolean using the convention that zero
* is false
.
null
will be converted to null
.
+ * BooleanUtils.toBoolean(new Integer(0)) = Boolean.FALSE + * BooleanUtils.toBoolean(new Integer(1)) = Boolean.TRUE + * BooleanUtils.toBoolean(new Integer(null)) = null + *+ * * @param value the Integer to convert * @return Boolean.TRUE if non-zero, Boolean.FALSE if zero, *
null
if null
input
@@ -180,12 +265,19 @@
if (value == null) {
return null;
}
- return (value.intValue() == 0 ? Boolean.FALSE : Boolean.TRUE);
+ return value.intValue() == 0 ? Boolean.FALSE : Boolean.TRUE;
}
/**
* Converts an int to a boolean specifying the conversion values.
* + *+ * BooleanUtils.toBoolean(0, 1, 0) = false + * BooleanUtils.toBoolean(1, 1, 0) = true + * BooleanUtils.toBoolean(2, 1, 2) = false + * BooleanUtils.toBoolean(2, 2, 0) = true + *+ * * @param value the Integer to convert * @param trueValue the value to match for
true
* @param falseValue the value to match for false
@@ -205,6 +297,14 @@
/**
* Converts an Integer to a boolean specifying the conversion values.
* + *+ * BooleanUtils.toBoolean(new Integer(0), new Integer(1), new Integer(0)) = false + * BooleanUtils.toBoolean(new Integer(1), new Integer(1), new Integer(0)) = true + * BooleanUtils.toBoolean(new Integer(2), new Integer(1), new Integer(2)) = false + * BooleanUtils.toBoolean(new Integer(2), new Integer(2), new Integer(0)) = true + * BooleanUtils.toBoolean(null, null, new Integer(0)) = true + *+ * * @param value the Integer to convert * @param trueValue the value to match for
true
,
* may be null
@@ -232,6 +332,12 @@
/**
* Converts an int to a Boolean specifying the conversion values.
* + *+ * BooleanUtils.toBooleanObject(0, 0, 2, 3) = Boolean.TRUE + * BooleanUtils.toBooleanObject(2, 1, 2, 3) = Boolean.FALSE + * BooleanUtils.toBooleanObject(3, 1, 2, 3) = null + *+ * * @param value the Integer to convert * @param trueValue the value to match for
true
* @param falseValue the value to match for false
@@ -254,6 +360,12 @@
/**
* Converts an Integer to a Boolean specifying the conversion values.
* + *+ * BooleanUtils.toBooleanObject(new Integer(0), new Integer(0), new Integer(2), new Integer(3)) = Boolean.TRUE + * BooleanUtils.toBooleanObject(new Integer(2), new Integer(1), new Integer(2), new Integer(3)) = Boolean.FALSE + * BooleanUtils.toBooleanObject(new Integer(3), new Integer(1), new Integer(2), new Integer(3)) = null + *+ * * @param value the Integer to convert * @param trueValue the value to match for
true
,
* may be null
@@ -289,56 +401,82 @@
/**
* Converts a boolean to an int using the convention that
* zero
is false
.
+ * BooleanUtils.toInteger(true) = 1 + * BooleanUtils.toInteger(false) = 0 + *+ * * @param bool the boolean to convert * @return one if
true
, zero if false
*/
public static int toInteger(boolean bool) {
- return (bool ? 1 : 0);
+ return bool ? 1 : 0;
}
/**
* Converts a boolean to an Integer using the convention that
* zero
is false
.
+ * BooleanUtils.toIntegerObject(true) = new Integer(1) + * BooleanUtils.toIntegerObject(false) = new Integer(0) + *+ * * @param bool the boolean to convert * @return one if
true
, zero if false
*/
public static Integer toIntegerObject(boolean bool) {
- return (bool ? NumberUtils.INTEGER_ONE : NumberUtils.INTEGER_ZERO);
+ return bool ? NumberUtils.INTEGER_ONE : NumberUtils.INTEGER_ZERO;
}
/**
* Converts a Boolean to a Integer using the convention that
* zero
is false
.
null
will be converted to null
.
+ * BooleanUtils.toIntegerObject(Boolean.TRUE) = new Integer(1) + * BooleanUtils.toIntegerObject(Boolean.FALSE) = new Integer(0) + *+ * * @param bool the Boolean to convert * @return one if Boolean.TRUE, zero if Boolean.FALSE,
null
if null
*/
public static Integer toIntegerObject(Boolean bool) {
if (bool == null) {
return null;
}
- return (bool.booleanValue() ? NumberUtils.INTEGER_ONE : NumberUtils.INTEGER_ZERO);
+ 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
true
* @param falseValue the value to return if false
* @return the appropriate value
*/
public static int toInteger(boolean bool, int trueValue, int falseValue) {
- return (bool ? trueValue : 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
true
* @param falseValue the value to return if false
@@ -349,12 +487,17 @@
if (bool == null) {
return nullValue;
}
- return (bool.booleanValue() ? trueValue : falseValue);
+ return bool.booleanValue() ? trueValue : falseValue;
}
/**
* Converts a boolean to an Integer specifying the conversion values.
* + *+ * BooleanUtils.toIntegerObject(true, new Integer(1), new Integer(0)) = new Integer(1) + * BooleanUtils.toIntegerObject(false, new Integer(1), new Integer(0)) = new Integer(0) + *+ * * @param bool the to convert * @param trueValue the value to return if
true
,
* may be null
@@ -363,12 +506,18 @@
* @return the appropriate value
*/
public static Integer toIntegerObject(boolean bool, Integer trueValue, Integer falseValue) {
- return (bool ? trueValue : falseValue);
+ return bool ? trueValue : falseValue;
}
/**
* Converts a Boolean to an Integer specifying the conversion values.
* + *+ * BooleanUtils.toIntegerObject(Boolean.TRUE, new Integer(1), new Integer(0), new Integer(2)) = new Integer(1) + * BooleanUtils.toIntegerObject(Boolean.FALSE, new Integer(1), new Integer(0), new Integer(2)) = new Integer(0) + * BooleanUtils.toIntegerObject(null, new Integer(1), new Integer(0), new Integer(2)) = new Integer(2) + *+ * * @param bool the Boolean to convert * @param trueValue the value to return if
true
,
* may be null
@@ -382,7 +531,7 @@
if (bool == null) {
return nullValue;
}
- return (bool.booleanValue() ? trueValue : falseValue);
+ return bool.booleanValue() ? trueValue : falseValue;
}
// String to Boolean methods
@@ -396,31 +545,126 @@
* (case insensitive) will return false
.
* Otherwise, null
is returned.
*
+ * + * BooleanUtils.toBooleanObject(null) = null + * BooleanUtils.toBooleanObject("true") = Boolean.TRUE + * BooleanUtils.toBooleanObject("false") = Boolean.FALSE + * BooleanUtils.toBooleanObject("on") = Boolean.TRUE + * BooleanUtils.toBooleanObject("ON") = Boolean.TRUE + * BooleanUtils.toBooleanObject("off") = Boolean.FALSE + * BooleanUtils.toBooleanObject("oFf") = Boolean.FALSE + * BooleanUtils.toBooleanObject("blue") = null + *+ * * @param str the String to check * @return the Boolean value of the string, *
null
if no match or null
input
*/
public static Boolean toBooleanObject(String str) {
- if ("true".equalsIgnoreCase(str)) {
+ // Previously used equalsIgnoreCase, which was fast for interned 'true'.
+ // Non interned 'true' matched 15 times slower.
+ //
+ // Optimisation provides same performance as before for interned 'true'.
+ // Similar performance for null, 'false', and other strings not length 2/3/4.
+ // 'true'/'TRUE' match 4 times slower, 'tRUE'/'True' 7 times slower.
+ if (str == "true") {
return Boolean.TRUE;
- } else if ("false".equalsIgnoreCase(str)) {
- return Boolean.FALSE;
- } else if ("on".equalsIgnoreCase(str)) {
- return Boolean.TRUE;
- } else if ("off".equalsIgnoreCase(str)) {
- return Boolean.FALSE;
- } else if ("yes".equalsIgnoreCase(str)) {
- return Boolean.TRUE;
- } else if ("no".equalsIgnoreCase(str)) {
- return Boolean.FALSE;
}
- // no match
+ if (str == null) {
+ return null;
+ }
+ switch (str.length()) {
+ case 1: {
+ char ch0 = str.charAt(0);
+ if ((ch0 == 'y' || ch0 == 'Y') ||
+ (ch0 == 't' || ch0 == 'T'))
+ {
+ return Boolean.TRUE;
+ }
+ if ((ch0 == 'n' || ch0 == 'N') ||
+ (ch0 == 'f' || ch0 == 'F'))
+ {
+ return Boolean.FALSE;
+ }
+ break;
+ }
+ case 2: {
+ char ch0 = str.charAt(0);
+ char ch1 = str.charAt(1);
+ if ((ch0 == 'o' || ch0 == 'O') &&
+ (ch1 == 'n' || ch1 == 'N') )
+ {
+ return Boolean.TRUE;
+ }
+ if ((ch0 == 'n' || ch0 == 'N') &&
+ (ch1 == 'o' || ch1 == 'O') )
+ {
+ return Boolean.FALSE;
+ }
+ break;
+ }
+ case 3: {
+ char ch0 = str.charAt(0);
+ char ch1 = str.charAt(1);
+ char ch2 = str.charAt(2);
+ if ((ch0 == 'y' || ch0 == 'Y') &&
+ (ch1 == 'e' || ch1 == 'E') &&
+ (ch2 == 's' || ch2 == 'S') )
+ {
+ return Boolean.TRUE;
+ }
+ if ((ch0 == 'o' || ch0 == 'O') &&
+ (ch1 == 'f' || ch1 == 'F') &&
+ (ch2 == 'f' || ch2 == 'F') )
+ {
+ return Boolean.FALSE;
+ }
+ break;
+ }
+ case 4: {
+ char ch0 = str.charAt(0);
+ char ch1 = str.charAt(1);
+ char ch2 = str.charAt(2);
+ char ch3 = str.charAt(3);
+ if ((ch0 == 't' || ch0 == 'T') &&
+ (ch1 == 'r' || ch1 == 'R') &&
+ (ch2 == 'u' || ch2 == 'U') &&
+ (ch3 == 'e' || ch3 == 'E') )
+ {
+ return Boolean.TRUE;
+ }
+ break;
+ }
+ case 5: {
+ char ch0 = str.charAt(0);
+ char ch1 = str.charAt(1);
+ char ch2 = str.charAt(2);
+ char ch3 = str.charAt(3);
+ char ch4 = str.charAt(4);
+ if ((ch0 == 'f' || ch0 == 'F') &&
+ (ch1 == 'a' || ch1 == 'A') &&
+ (ch2 == 'l' || ch2 == 'L') &&
+ (ch3 == 's' || ch3 == 'S') &&
+ (ch4 == 'e' || ch4 == 'E') )
+ {
+ return Boolean.FALSE;
+ }
+ break;
+ }
+ }
+
return null;
}
/**
* Converts a String to a Boolean throwing an exception if no match.
* + *+ * BooleanUtils.toBooleanObject("true", "true", "false", "null") = Boolean.TRUE + * BooleanUtils.toBooleanObject("false", "true", "false", "null") = Boolean.FALSE + * BooleanUtils.toBooleanObject("null", "true", "false", "null") = null + *+ * * @param str the String to check * @param trueString the String to match for
true
* (case sensitive), may be null
@@ -429,7 +673,10 @@
* @param nullString the String to match for null
* (case sensitive), may be null
* @return the Boolean value of the string,
- * null
if no match or null
input
+ * null
if either the String matches nullString
+ * or if null
input and nullString
is
+ * null
+ * @throws IllegalArgumentException if the String doesn't match
*/
public static Boolean toBooleanObject(String str, String trueString, String falseString, String nullString) {
if (str == null) {
@@ -454,32 +701,44 @@
// String to boolean methods
//-----------------------------------------------------------------------
/**
- * Converts a String to a boolean.
+ *Converts a String to a boolean (optimised for performance).
* *'true'
, 'on'
or 'yes'
* (case insensitive) will return true
. Otherwise,
* false
is returned.
This method performs 4 times faster (JDK1.4) than
+ * Boolean.valueOf(String)
. However, this method accepts
+ * 'on' and 'yes' 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 + *+ * * @param str the String to check - * @return the boolean value of the string,
false
if no match
+ * @return the boolean value of the string, false
if no match or the String is null
*/
public static boolean toBoolean(String str) {
- if ("true".equalsIgnoreCase(str)) {
- return true;
- } else if ("on".equalsIgnoreCase(str)) {
- return true;
- } else if ("yes".equalsIgnoreCase(str)) {
- return true;
- }
- // no match
- return false;
+ return toBoolean(toBooleanObject(str));
}
-
+
/**
* Converts a String to a Boolean throwing an exception if no match found.
* *null is returned if there is no match.
* + *+ * 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
true
* (case sensitive), may be null
@@ -510,6 +769,12 @@
* Converts a Boolean to a String returning 'true'
,
* 'false'
, or null
.
+ * BooleanUtils.toStringTrueFalse(Boolean.TRUE) = "true" + * BooleanUtils.toStringTrueFalse(Boolean.FALSE) = "false" + * BooleanUtils.toStringTrueFalse(null) = null; + *+ * * @param bool the Boolean to check * @return
'true'
, 'false'
,
* or null
@@ -522,6 +787,12 @@
* Converts a Boolean to a String returning 'on'
,
* 'off'
, or null
.
+ * BooleanUtils.toStringOnOff(Boolean.TRUE) = "on" + * BooleanUtils.toStringOnOff(Boolean.FALSE) = "off" + * BooleanUtils.toStringOnOff(null) = null; + *+ * * @param bool the Boolean to check * @return
'on'
, 'off'
,
* or null
@@ -534,6 +805,12 @@
* Converts a Boolean to a String returning 'yes'
,
* 'no'
, or null
.
+ * BooleanUtils.toStringYesNo(Boolean.TRUE) = "yes" + * BooleanUtils.toStringYesNo(Boolean.FALSE) = "no" + * BooleanUtils.toStringYesNo(null) = null; + *+ * * @param bool the Boolean to check * @return
'yes'
, 'no'
,
* or null
@@ -545,6 +822,12 @@
/**
* Converts a Boolean to a String returning one of the input Strings.
* + *+ * BooleanUtils.toString(Boolean.TRUE, "true", "false", null) = "true" + * BooleanUtils.toString(Boolean.FALSE, "true", "false", null) = "false" + * BooleanUtils.toString(null, "true", "false", null) = null; + *+ * * @param bool the Boolean to check * @param trueString the String to return if
true
,
* may be null
@@ -558,7 +841,7 @@
if (bool == null) {
return nullString;
}
- return (bool.booleanValue() ? trueString : falseString);
+ return bool.booleanValue() ? trueString : falseString;
}
// boolean to String methods
@@ -567,6 +850,11 @@
* Converts a boolean to a String returning 'true'
* or 'false'
.
+ * BooleanUtils.toStringTrueFalse(true) = "true" + * BooleanUtils.toStringTrueFalse(false) = "false" + *+ * * @param bool the Boolean to check * @return
'true'
, 'false'
,
* or null
@@ -579,6 +867,11 @@
* Converts a boolean to a String returning 'on'
* or 'off'
.
+ * BooleanUtils.toStringOnOff(true) = "on" + * BooleanUtils.toStringOnOff(false) = "off" + *+ * * @param bool the Boolean to check * @return
'on'
, 'off'
,
* or null
@@ -591,6 +884,11 @@
* Converts a boolean to a String returning 'yes'
* or 'no'
.
+ * BooleanUtils.toStringYesNo(true) = "yes" + * BooleanUtils.toStringYesNo(false) = "no" + *+ * * @param bool the Boolean to check * @return
'yes'
, 'no'
,
* or null
@@ -602,6 +900,11 @@
/**
* Converts a boolean to a String returning one of the input Strings.
* + *+ * BooleanUtils.toString(true, "true", "false") = "true" + * BooleanUtils.toString(false, "true", "false") = "false" + *+ * * @param bool the Boolean to check * @param trueString the String to return if
true
,
* may be null
@@ -610,14 +913,20 @@
* @return one of the two input Strings
*/
public static String toString(boolean bool, String trueString, String falseString) {
- return (bool ? trueString : falseString);
+ return bool ? trueString : falseString;
}
// xor methods
// ----------------------------------------------------------------------
/**
* Performs an xor on a set of booleans.
- * + * + *+ * BooleanUtils.xor(new boolean[] { true, true }) = false + * BooleanUtils.xor(new boolean[] { false, false }) = false + * BooleanUtils.xor(new boolean[] { true, false }) = true + *+ * * @param array an array of
booleans
* @return true
if the xor is successful.
* @throws IllegalArgumentException if array
is null
@@ -652,6 +961,12 @@
/**
* Performs an xor on an array of Booleans.
*
+ *
+ * BooleanUtils.xor(new Boolean[] { Boolean.TRUE, Boolean.TRUE }) = Boolean.FALSE
+ * BooleanUtils.xor(new Boolean[] { Boolean.FALSE, Boolean.FALSE }) = Boolean.FALSE
+ * BooleanUtils.xor(new Boolean[] { Boolean.TRUE, Boolean.FALSE }) = Boolean.TRUE
+ *
+ *
* @param array an array of Booleans
* @return true
if the xor is successful.
* @throws IllegalArgumentException if array
is null
@@ -668,9 +983,9 @@
try {
primitive = ArrayUtils.toPrimitive(array);
} catch (NullPointerException ex) {
- throw new IllegalArgumentException("The array must not conatin any null elements");
+ throw new IllegalArgumentException("The array must not contain any null elements");
}
- return (xor(primitive) ? Boolean.TRUE : Boolean.FALSE);
+ return xor(primitive) ? Boolean.TRUE : Boolean.FALSE;
}
}
Index: 3rdParty_sources/commons-lang/org/apache/commons/lang/CharEncoding.java
===================================================================
RCS file: /usr/local/cvsroot/3rdParty_sources/commons-lang/org/apache/commons/lang/CharEncoding.java,v
diff -u
--- /dev/null 1 Jan 1970 00:00:00 -0000
+++ 3rdParty_sources/commons-lang/org/apache/commons/lang/CharEncoding.java 15 Mar 2013 09:52:49 -0000 1.1
@@ -0,0 +1,153 @@
+/*
+ * 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.lang;
+
+import java.io.UnsupportedEncodingException;
+
+/**
+ *
+ * Character encoding names required of every implementation of the Java platform.
+ *
+ *
+ *
+ * According to JRE character
+ * encoding names:
+ *
+ * Every implementation of the Java platform is required to support the following character encodings. Consult the
+ * release documentation for your implementation to see if any other encodings are supported.
+ *
+ *
+ *
+ * @see JRE character encoding
+ * names
+ * @author Apache Software Foundation
+ * @since 2.1
+ * @version $Id: CharEncoding.java,v 1.1 2013/03/15 09:52:49 andreyb Exp $
+ */
+public class CharEncoding {
+
+ /**
+ *
+ * ISO Latin Alphabet #1, also known as ISO-LATIN-1.
+ *
+ *
+ * Every implementation of the Java platform is required to support this character encoding.
+ *
+ *
+ * @see JRE character
+ * encoding names
+ */
+ public static final String ISO_8859_1 = "ISO-8859-1";
+
+ /**
+ *
+ * Seven-bit ASCII, also known as ISO646-US, also known as the Basic Latin block of the Unicode character set.
+ *
+ *
+ * Every implementation of the Java platform is required to support this character encoding.
+ *
+ *
+ * @see JRE character
+ * encoding names
+ */
+ public static final String US_ASCII = "US-ASCII";
+
+ /**
+ *
+ * Sixteen-bit Unicode Transformation Format, byte order specified by a mandatory initial byte-order mark (either
+ * order accepted on input, big-endian used on output).
+ *
+ *
+ * Every implementation of the Java platform is required to support this character encoding.
+ *
+ *
+ * @see JRE character
+ * encoding names
+ */
+ public static final String UTF_16 = "UTF-16";
+
+ /**
+ *
+ * Sixteen-bit Unicode Transformation Format, big-endian byte order.
+ *
+ *
+ * Every implementation of the Java platform is required to support this character encoding.
+ *
+ *
+ * @see JRE character
+ * encoding names
+ */
+ public static final String UTF_16BE = "UTF-16BE";
+
+ /**
+ *
+ * Sixteen-bit Unicode Transformation Format, little-endian byte order.
+ *
+ *
+ * Every implementation of the Java platform is required to support this character encoding.
+ *
+ *
+ * @see JRE character
+ * encoding names
+ */
+ public static final String UTF_16LE = "UTF-16LE";
+
+ /**
+ *
+ * Eight-bit Unicode Transformation Format.
+ *
+ *
+ * Every implementation of the Java platform is required to support this character encoding.
+ *
+ *
+ * @see JRE character
+ * encoding names
+ */
+ public static final String UTF_8 = "UTF-8";
+
+ /**
+ *
+ * Returns whether the named charset is supported.
+ *
+ *
+ * This is similar to
+ * java.nio.charset.Charset.isSupported(String)
+ *
+ *
+ * @param name
+ * the name of the requested charset; may be either a canonical name or an alias
+ * @return true
if, and only if, support for the named charset is available in the current Java
+ * virtual machine
+ *
+ * @see JRE character
+ * encoding names
+ */
+ public static boolean isSupported(String name) {
+ if (name == null) {
+ return false;
+ }
+ try {
+ new String(ArrayUtils.EMPTY_BYTE_ARRAY, name);
+ } catch (UnsupportedEncodingException e) {
+ return false;
+ }
+ return true;
+ }
+
+}
Index: 3rdParty_sources/commons-lang/org/apache/commons/lang/CharRange.java
===================================================================
RCS file: /usr/local/cvsroot/3rdParty_sources/commons-lang/org/apache/commons/lang/CharRange.java,v
diff -u -r1.1 -r1.2
--- 3rdParty_sources/commons-lang/org/apache/commons/lang/CharRange.java 30 Aug 2012 16:24:42 -0000 1.1
+++ 3rdParty_sources/commons-lang/org/apache/commons/lang/CharRange.java 15 Mar 2013 09:52:49 -0000 1.2
@@ -1,75 +1,46 @@
-/* ====================================================================
- * The Apache Software License, Version 1.1
- *
- * Copyright (c) 2002-2003 The Apache Software Foundation. All rights
- * reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in
- * the documentation and/or other materials provided with the
- * distribution.
- *
- * 3. The end-user documentation included with the redistribution, if
- * any, must include the following acknowledgement:
- * "This product includes software developed by the
- * Apache Software Foundation (http://www.apache.org/)."
- * Alternately, this acknowledgement may appear in the software itself,
- * if and wherever such third-party acknowledgements normally appear.
- *
- * 4. The names "The Jakarta Project", "Commons", and "Apache Software
- * Foundation" must not be used to endorse or promote products derived
- * from this software without prior written permission. For written
- * permission, please contact apache@apache.org.
- *
- * 5. Products derived from this software may not be called "Apache"
- * nor may "Apache" appear in their names without prior written
- * permission of the Apache Software Foundation.
- *
- * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
- * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
- * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
- * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- * ====================================================================
- *
- * This software consists of voluntary contributions made by many
- * individuals on behalf of the Apache Software Foundation. For more
- * information on the Apache Software Foundation, please see
- * .
+/*
+ * 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.lang;
import java.io.Serializable;
+import java.util.Iterator;
+import java.util.NoSuchElementException;
+import org.apache.commons.lang.text.StrBuilder;
+
/**
* A contiguous range of characters, optionally negated.
*
* Instances are immutable.
*
- * @author Henri Yandell
- * @author Stephen Colebourne
+ * #ThreadSafe#
+ * @author Apache Software Foundation
* @author Chris Feldhacker
* @author Gary Gregory
* @since 1.0
* @version $Id$
*/
public final class CharRange implements Serializable {
- /** Serialization lock, Lang version 2.0. */
+ /**
+ * Required for serialization support. Lang version 2.0.
+ *
+ * @see java.io.Serializable
+ */
private static final long serialVersionUID = 8270183163158333422L;
/** The first character, inclusive, in the range. */
@@ -82,12 +53,64 @@
/** Cached toString. */
private transient String iToString;
+ // Static
//-----------------------------------------------------------------------
/**
* Constructs a CharRange
over a 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 is(char ch) {
+ return new CharRange(ch, ch, false);
+ }
+
+ /**
+ * Constructs a negated CharRange
over a 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(char ch) {
+ return new CharRange(ch, ch, true);
+ }
+
+ /**
+ * Constructs a CharRange
over a set of characters.
+ *
+ * @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(char start, char end) {
+ return new CharRange(start, end, false);
+ }
+
+ /**
+ * Constructs a negated CharRange
over a set of characters.
+ *
+ * @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(char start, char end) {
+ return new CharRange(start, end, true);
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Constructs a CharRange
over a single character.
+ *
+ * @param ch only character in this range
+ */
public CharRange(char ch) {
this(ch, ch, false);
}
@@ -183,7 +206,7 @@
* @return true
if this range contains the input character
*/
public boolean contains(char ch) {
- return ((ch >= start && ch <= end) != negated);
+ return (ch >= start && ch <= end) != negated;
}
/**
@@ -200,17 +223,14 @@
}
if (negated) {
if (range.negated) {
- return (start >= range.start && end <= range.end);
- } else {
- return (range.end < start || range.start > end);
+ return start >= range.start && end <= range.end;
}
- } else {
- if (range.negated) {
- return (start == 0 && end == Character.MAX_VALUE);
- } else {
- return (start <= range.start && end >= range.end);
- }
+ return range.end < start || range.start > end;
}
+ if (range.negated) {
+ return start == 0 && end == Character.MAX_VALUE;
+ }
+ return start <= range.start && end >= range.end;
}
// Basics
@@ -230,11 +250,11 @@
return false;
}
CharRange other = (CharRange) obj;
- return (start == other.start && end == other.end && negated == other.negated);
+ return start == other.start && end == other.end && negated == other.negated;
}
/**
- * Gets a hashCode compatable with the equals method.
+ * Gets a hashCode compatible with the equals method.
*
* @return a suitable hashCode
*/
@@ -249,7 +269,7 @@
*/
public String toString() {
if (iToString == null) {
- StringBuffer buf = new StringBuffer(4);
+ StrBuilder buf = new StrBuilder(4);
if (isNegated()) {
buf.append('^');
}
@@ -262,5 +282,110 @@
}
return iToString;
}
-
+
+ // Expansions
+ //-----------------------------------------------------------------------
+ /**
+ * Returns an iterator which can be used to walk through the characters described by this range.
+ *
+ * #NotThreadSafe# the iterator is not threadsafe
+ * @return an iterator to the chars represented by this range
+ * @since 2.5
+ */
+ public Iterator iterator() {
+ return new CharacterIterator(this);
+ }
+
+ /**
+ * Character {@link Iterator}.
+ * #NotThreadSafe#
+ */
+ private static class CharacterIterator implements Iterator {
+ /** The current character */
+ private char current;
+
+ private final CharRange range;
+ private boolean hasNext;
+
+ /**
+ * Construct a new iterator for the character range.
+ *
+ * @param r The character range
+ */
+ private CharacterIterator(CharRange r) {
+ range = r;
+ hasNext = true;
+
+ if (range.negated) {
+ if (range.start == 0) {
+ if (range.end == Character.MAX_VALUE) {
+ // This range is an empty set
+ hasNext = false;
+ } else {
+ current = (char) (range.end + 1);
+ }
+ } else {
+ current = 0;
+ }
+ } else {
+ current = range.start;
+ }
+ }
+
+ /**
+ * Prepare the next character in the range.
+ */
+ private void prepareNext() {
+ if (range.negated) {
+ if (current == Character.MAX_VALUE) {
+ hasNext = false;
+ } else if (current + 1 == range.start) {
+ if (range.end == Character.MAX_VALUE) {
+ hasNext = false;
+ } else {
+ current = (char) (range.end + 1);
+ }
+ } else {
+ current = (char) (current + 1);
+ }
+ } else if (current < range.end) {
+ current = (char) (current + 1);
+ } else {
+ hasNext = false;
+ }
+ }
+
+ /**
+ * Has the iterator not reached the end character yet?
+ *
+ * @return true
if the iterator has yet to reach the character date
+ */
+ public boolean hasNext() {
+ return hasNext;
+ }
+
+ /**
+ * Return the next character in the iteration
+ *
+ * @return Character
for the next character
+ */
+ public Object next() {
+ if (hasNext == false) {
+ throw new NoSuchElementException();
+ }
+ char cur = current;
+ prepareNext();
+ return new Character(cur);
+ }
+
+ /**
+ * Always throws UnsupportedOperationException.
+ *
+ * @throws UnsupportedOperationException
+ * @see java.util.Iterator#remove()
+ */
+ public void remove() {
+ throw new UnsupportedOperationException();
+ }
+ }
}
Index: 3rdParty_sources/commons-lang/org/apache/commons/lang/CharSet.java
===================================================================
RCS file: /usr/local/cvsroot/3rdParty_sources/commons-lang/org/apache/commons/lang/CharSet.java,v
diff -u -r1.1 -r1.2
--- 3rdParty_sources/commons-lang/org/apache/commons/lang/CharSet.java 30 Aug 2012 16:24:42 -0000 1.1
+++ 3rdParty_sources/commons-lang/org/apache/commons/lang/CharSet.java 15 Mar 2013 09:52:49 -0000 1.2
@@ -1,59 +1,23 @@
-/* ====================================================================
- * The Apache Software License, Version 1.1
- *
- * Copyright (c) 2002-2003 The Apache Software Foundation. All rights
- * reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in
- * the documentation and/or other materials provided with the
- * distribution.
- *
- * 3. The end-user documentation included with the redistribution, if
- * any, must include the following acknowledgement:
- * "This product includes software developed by the
- * Apache Software Foundation (http://www.apache.org/)."
- * Alternately, this acknowledgement may appear in the software itself,
- * if and wherever such third-party acknowledgements normally appear.
- *
- * 4. The names "The Jakarta Project", "Commons", and "Apache Software
- * Foundation" must not be used to endorse or promote products derived
- * from this software without prior written permission. For written
- * permission, please contact apache@apache.org.
- *
- * 5. Products derived from this software may not be called "Apache"
- * nor may "Apache" appear in their names without prior written
- * permission of the Apache Software Foundation.
- *
- * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
- * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
- * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
- * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- * ====================================================================
- *
- * This software consists of voluntary contributions made by many
- * individuals on behalf of the Apache Software Foundation. For more
- * information on the Apache Software Foundation, please see
- * .
+/*
+ * 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.lang;
import java.io.Serializable;
+import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
@@ -65,8 +29,8 @@
*
* Instances are immutable, but instances of subclasses may not be.
*
- * @author Henri Yandell
- * @author Stephen Colebourne
+ * #ThreadSafe#
+ * @author Apache Software Foundation
* @author Phil Steitz
* @author Pete Gieser
* @author Gary Gregory
@@ -75,7 +39,11 @@
*/
public class CharSet implements Serializable {
- /** Serialization lock, Lang version 2.0. */
+ /**
+ * Required for serialization support. Lang version 2.0.
+ *
+ * @see java.io.Serializable
+ */
private static final long serialVersionUID = 5947847346149275958L;
/**
@@ -110,10 +78,10 @@
/**
* A Map of the common cases used in the factory.
- * Subclasses can add more common patterns if desired.
+ * Subclasses can add more common patterns if desired
* @since 2.0
*/
- protected static final Map COMMON = new HashMap();
+ protected static final Map COMMON = Collections.synchronizedMap(new HashMap());
static {
COMMON.put(null, EMPTY);
@@ -126,7 +94,7 @@
}
/** The set of CharRange objects. */
- private Set set = new HashSet();
+ private final Set set = Collections.synchronizedSet(new HashSet());
//-----------------------------------------------------------------------
/**
@@ -180,6 +148,21 @@
return new CharSet(setStr);
}
+ /**
+ * Constructs a new CharSet using the set syntax.
+ * Each string is merged in with the set.
+ *
+ * @param setStrs Strings to merge into the initial set, may be null
+ * @return a CharSet instance
+ * @since 2.4
+ */
+ public static CharSet getInstance(String[] setStrs) {
+ if (setStrs == null) {
+ return null;
+ }
+ return new CharSet(setStrs);
+ }
+
//-----------------------------------------------------------------------
/**
* Constructs a new CharSet using the set syntax.
@@ -224,19 +207,19 @@
int remainder = (len - pos);
if (remainder >= 4 && str.charAt(pos) == '^' && str.charAt(pos + 2) == '-') {
// negated range
- set.add(new CharRange(str.charAt(pos + 1), str.charAt(pos + 3), true));
+ set.add(CharRange.isNotIn(str.charAt(pos + 1), str.charAt(pos + 3)));
pos += 4;
} else if (remainder >= 3 && str.charAt(pos + 1) == '-') {
// range
- set.add(new CharRange(str.charAt(pos), str.charAt(pos + 2)));
+ set.add(CharRange.isIn(str.charAt(pos), str.charAt(pos + 2)));
pos += 3;
} else if (remainder >= 2 && str.charAt(pos) == '^') {
// negated char
- set.add(new CharRange(str.charAt(pos + 1), true));
+ set.add(CharRange.isNot(str.charAt(pos + 1)));
pos += 2;
} else {
// char
- set.add(new CharRange(str.charAt(pos)));
+ set.add(CharRange.is(str.charAt(pos)));
pos += 1;
}
}
@@ -292,11 +275,11 @@
return false;
}
CharSet other = (CharSet) obj;
- return (set.equals(other.set));
+ return set.equals(other.set);
}
/**
- * Gets a hashCode compatable with the equals method.
+ * Gets a hashCode compatible with the equals method.
*
* @return a suitable hashCode
* @since 2.0
Index: 3rdParty_sources/commons-lang/org/apache/commons/lang/CharSetUtils.java
===================================================================
RCS file: /usr/local/cvsroot/3rdParty_sources/commons-lang/org/apache/commons/lang/CharSetUtils.java,v
diff -u -r1.1 -r1.2
--- 3rdParty_sources/commons-lang/org/apache/commons/lang/CharSetUtils.java 30 Aug 2012 16:24:42 -0000 1.1
+++ 3rdParty_sources/commons-lang/org/apache/commons/lang/CharSetUtils.java 15 Mar 2013 09:52:49 -0000 1.2
@@ -1,68 +1,33 @@
-/* ====================================================================
- * The Apache Software License, Version 1.1
- *
- * Copyright (c) 2002-2003 The Apache Software Foundation. All rights
- * reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in
- * the documentation and/or other materials provided with the
- * distribution.
- *
- * 3. The end-user documentation included with the redistribution, if
- * any, must include the following acknowledgement:
- * "This product includes software developed by the
- * Apache Software Foundation (http://www.apache.org/)."
- * Alternately, this acknowledgement may appear in the software itself,
- * if and wherever such third-party acknowledgements normally appear.
- *
- * 4. The names "The Jakarta Project", "Commons", and "Apache Software
- * Foundation" must not be used to endorse or promote products derived
- * from this software without prior written permission. For written
- * permission, please contact apache@apache.org.
- *
- * 5. Products derived from this software may not be called "Apache"
- * nor may "Apache" appear in their names without prior written
- * permission of the Apache Software Foundation.
- *
- * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
- * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
- * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
- * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- * ====================================================================
- *
- * This software consists of voluntary contributions made by many
- * individuals on behalf of the Apache Software Foundation. For more
- * information on the Apache Software Foundation, please see
- * .
+/*
+ * 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.lang;
+import org.apache.commons.lang.text.StrBuilder;
+
/**
* Operations on CharSet
s.
*
* This class handles null
input gracefully.
* An exception will not be thrown for a null
input.
* Each method documents its behaviour in more detail.
*
+ * #ThreadSafe#
* @see CharSet
- * @author Henri Yandell
- * @author Stephen Colebourne
+ * @author Apache Software Foundation
* @author Phil Steitz
* @author Gary Gregory
* @since 1.0
@@ -78,6 +43,7 @@
* to operate.
*/
public CharSetUtils() {
+ super();
}
// Factory
@@ -89,7 +55,7 @@
*
* - "aeio" which implies 'a','e',..
* - "^e" implies not e.
- * - "ej-m" implies e,j->m. e,j,k,l,m.
+ * - "ej-m" implies e,j->m. e,j,k,l,m.
*
*
*
@@ -100,7 +66,7 @@
*
* @param set the set, may be null
* @return a CharSet instance, null
if null input
- * @deprecated Use {@link CharSet#getInstance(String)}.
+ * @deprecated Use {@link CharSet#getInstance(String[])}.
* Method will be removed in Commons Lang 3.0.
*/
public static CharSet evaluateSet(String[] set) {
@@ -113,7 +79,7 @@
// Squeeze
//-----------------------------------------------------------------------
/**
- * Squeezes any repititions of a character that is mentioned in the
+ *
Squeezes any repetitions of a character that is mentioned in the
* supplied set.
*
*
@@ -125,13 +91,13 @@
* CharSetUtils.squeeze("hello", "a-e") = "hello"
*
*
- * @see #evaluateSet(java.lang.String[]) for set-syntax.
+ * @see CharSet#getInstance(java.lang.String) for set-syntax.
* @param str the string to squeeze, may be null
* @param set the character set to use for manipulation, may be null
* @return modified String, null
if null string input
*/
public static String squeeze(String str, String set) {
- if (str == null || str.length() == 0 || set == null || set.length() == 0) {
+ if (StringUtils.isEmpty(str) || StringUtils.isEmpty(set)) {
return str;
}
String[] strs = new String[1];
@@ -140,25 +106,25 @@
}
/**
- * Squeezes any repititions of a character that is mentioned in the
+ *
Squeezes any repetitions of a character that is mentioned in the
* supplied set.
*
* An example is:
*
* - squeeze("hello", {"el"}) => "helo"
*
*
- * @see #evaluateSet(java.lang.String[]) for set-syntax.
+ * @see CharSet#getInstance(java.lang.String) for set-syntax.
* @param str the string to squeeze, may be null
* @param set the character set to use for manipulation, may be null
* @return modified String, null
if null string input
*/
public static String squeeze(String str, String[] set) {
- if (str == null || str.length() == 0 || set == null || set.length == 0) {
+ if (StringUtils.isEmpty(str) || ArrayUtils.isEmpty(set)) {
return str;
}
- CharSet chars = evaluateSet(set);
- StringBuffer buffer = new StringBuffer(str.length());
+ CharSet chars = CharSet.getInstance(set);
+ StrBuilder buffer = new StrBuilder(str.length());
char[] chrs = str.toCharArray();
int sz = chrs.length;
char lastChar = ' ';
@@ -191,13 +157,13 @@
* CharSetUtils.count("hello", "a-e") = 1
*
*
- * @see #evaluateSet(java.lang.String[]) for set-syntax.
+ * @see CharSet#getInstance(java.lang.String) for set-syntax.
* @param str String to count characters in, may be null
* @param set String set of characters to count, may be null
* @return character count, zero if null string input
*/
public static int count(String str, String set) {
- if (str == null || str.length() == 0 || set == null || set.length() == 0) {
+ if (StringUtils.isEmpty(str) || StringUtils.isEmpty(set)) {
return 0;
}
String[] strs = new String[1];
@@ -214,16 +180,16 @@
* count("hello", {"c-f", "o"}) returns 2.
*
*
- * @see #evaluateSet(java.lang.String[]) for set-syntax.
+ * @see CharSet#getInstance(java.lang.String) for set-syntax.
* @param str String to count characters in, may be null
* @param set String[] set of characters to count, may be null
* @return character count, zero if null string input
*/
public static int count(String str, String[] set) {
- if (str == null || str.length() == 0 || set == null || set.length == 0) {
+ if (StringUtils.isEmpty(str) || ArrayUtils.isEmpty(set)) {
return 0;
}
- CharSet chars = evaluateSet(set);
+ CharSet chars = CharSet.getInstance(set);
int count = 0;
char[] chrs = str.toCharArray();
int sz = chrs.length;
@@ -246,11 +212,11 @@
* CharSetUtils.keep("", *) = ""
* CharSetUtils.keep(*, null) = ""
* CharSetUtils.keep(*, "") = ""
- * CharSetUtils.keep("hello", "hl") = "hll"
- * CharSetUtils.keep("hello", "le") = "ell"
+ * CharSetUtils.keep("hello", "hl") = "hll"
+ * CharSetUtils.keep("hello", "le") = "ell"
*
*
- * @see #evaluateSet(java.lang.String[]) for set-syntax.
+ * @see CharSet#getInstance(java.lang.String) for set-syntax.
* @param str String to keep characters from, may be null
* @param set String set of characters to keep, may be null
* @return modified String, null
if null string input
@@ -260,7 +226,7 @@
if (str == null) {
return null;
}
- if (str.length() == 0 || set == null || set.length() == 0) {
+ if (str.length() == 0 || StringUtils.isEmpty(set)) {
return "";
}
String[] strs = new String[1];
@@ -275,10 +241,10 @@
* An example would be:
*
* - keep("hello", {"c-f", "o"})
- * returns "hll"
+ * returns "eo"
*
*
- * @see #evaluateSet(java.lang.String[]) for set-syntax.
+ * @see CharSet#getInstance(java.lang.String) for set-syntax.
* @param str String to keep characters from, may be null
* @param set String[] set of characters to keep, may be null
* @return modified String, null
if null string input
@@ -288,7 +254,7 @@
if (str == null) {
return null;
}
- if (str.length() == 0 || set == null || set.length == 0) {
+ if (str.length() == 0 || ArrayUtils.isEmpty(set)) {
return "";
}
return modify(str, set, true);
@@ -305,17 +271,17 @@
* CharSetUtils.delete("", *) = ""
* CharSetUtils.delete(*, null) = *
* CharSetUtils.delete(*, "") = *
- * CharSetUtils.delete("hello", "hl") = "hll"
- * CharSetUtils.delete("hello", "le") = "ell"
+ * CharSetUtils.delete("hello", "hl") = "eo"
+ * CharSetUtils.delete("hello", "le") = "ho"
*
*
- * @see #evaluateSet(java.lang.String[]) for set-syntax.
+ * @see CharSet#getInstance(java.lang.String) for set-syntax.
* @param str String to delete characters from, may be null
* @param set String set of characters to delete, may be null
* @return modified String, null
if null string input
*/
public static String delete(String str, String set) {
- if (str == null || str.length() == 0 || set == null || set.length() == 0) {
+ if (StringUtils.isEmpty(str) || StringUtils.isEmpty(set)) {
return str;
}
String[] strs = new String[1];
@@ -333,23 +299,30 @@
* "hll"
*
*
- * @see #evaluateSet(java.lang.String[]) for set-syntax.
+ * @see CharSet#getInstance(java.lang.String) for set-syntax.
* @param str String to delete characters from, may be null
* @param set String[] set of characters to delete, may be null
* @return modified String, null
if null string input
*/
public static String delete(String str, String[] set) {
- if (str == null || str.length() == 0 || set == null || set.length == 0) {
+ if (StringUtils.isEmpty(str) || ArrayUtils.isEmpty(set)) {
return str;
}
return modify(str, set, false);
}
//-----------------------------------------------------------------------
- // Implementation of delete and keep
+ /**
+ * Implementation of delete and keep
+ *
+ * @param str String to modify characters within
+ * @param set String[] set of characters to modify
+ * @param expect whether to evaluate on match, or non-match
+ * @return modified String
+ */
private static String modify(String str, String[] set, boolean expect) {
- CharSet chars = evaluateSet(set);
- StringBuffer buffer = new StringBuffer(str.length());
+ CharSet chars = CharSet.getInstance(set);
+ StrBuilder buffer = new StrBuilder(str.length());
char[] chrs = str.toCharArray();
int sz = chrs.length;
for(int i=0; iAn example is:
*
* - translate("hello", "ho", "jy")
- * => jelly
+ * => jelly
*
*
* If the length of characters to search for is greater than the
@@ -378,24 +351,27 @@
*
*
* CharSetUtils.translate(null, *, *) = null
- * CharSetUtils.translate("", *, *) = ""
+ * CharSetUtils.translate("", *, *) = ""
*
*
* @param str String to replace characters in, may be null
* @param searchChars a set of characters to search for, must not be null
- * @param replaceChars a set of characters to replace, must not be null or empty ("")
+ * @param replaceChars a set of characters to replace, must not be null or empty ("")
* @return translated String, null
if null string input
- * @throws NullPointerException if with
or repl
+ * @throws NullPointerException if searchChars
or replaceChars
* is null
- * @throws ArrayIndexOutOfBoundsException if with
is empty ("")
+ * @throws ArrayIndexOutOfBoundsException if replaceChars
is empty ("")
* @deprecated Use {@link StringUtils#replaceChars(String, String, String)}.
* Method will be removed in Commons Lang 3.0.
+ * NOTE: StringUtils#replaceChars behaves differently when 'searchChars' is longer
+ * than 'replaceChars'. CharSetUtils#translate will use the last char of the replacement
+ * string whereas StringUtils#replaceChars will delete
*/
public static String translate(String str, String searchChars, String replaceChars) {
- if (str == null || str.length() == 0) {
+ if (StringUtils.isEmpty(str)) {
return str;
}
- StringBuffer buffer = new StringBuffer(str.length());
+ StrBuilder buffer = new StrBuilder(str.length());
char[] chrs = str.toCharArray();
char[] withChrs = replaceChars.toCharArray();
int sz = chrs.length;
Index: 3rdParty_sources/commons-lang/org/apache/commons/lang/CharUtils.java
===================================================================
RCS file: /usr/local/cvsroot/3rdParty_sources/commons-lang/org/apache/commons/lang/CharUtils.java,v
diff -u
--- /dev/null 1 Jan 1970 00:00:00 -0000
+++ 3rdParty_sources/commons-lang/org/apache/commons/lang/CharUtils.java 15 Mar 2013 09:52:49 -0000 1.1
@@ -0,0 +1,576 @@
+/*
+ * 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.lang;
+
+/**
+ * Operations on char primitives and Character objects.
+ *
+ * This class tries to handle null
input gracefully.
+ * An exception will not be thrown for a null
input.
+ * Each method documents its behaviour in more detail.
+ *
+ * #ThreadSafe#
+ * @author Apache Software Foundation
+ * @since 2.1
+ * @version $Id: CharUtils.java,v 1.1 2013/03/15 09:52:49 andreyb Exp $
+ */
+public class CharUtils {
+
+ private static final String CHAR_STRING =
+ "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007" +
+ "\b\t\n\u000b\f\r\u000e\u000f" +
+ "\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017" +
+ "\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f" +
+ "\u0020\u0021\"\u0023\u0024\u0025\u0026\u0027" +
+ "\u0028\u0029\u002a\u002b\u002c\u002d\u002e\u002f" +
+ "\u0030\u0031\u0032\u0033\u0034\u0035\u0036\u0037" +
+ "\u0038\u0039\u003a\u003b\u003c\u003d\u003e\u003f" +
+ "\u0040\u0041\u0042\u0043\u0044\u0045\u0046\u0047" +
+ "\u0048\u0049\u004a\u004b\u004c\u004d\u004e\u004f" +
+ "\u0050\u0051\u0052\u0053\u0054\u0055\u0056\u0057" +
+ "\u0058\u0059\u005a\u005b\\\u005d\u005e\u005f" +
+ "\u0060\u0061\u0062\u0063\u0064\u0065\u0066\u0067" +
+ "\u0068\u0069\u006a\u006b\u006c\u006d\u006e\u006f" +
+ "\u0070\u0071\u0072\u0073\u0074\u0075\u0076\u0077" +
+ "\u0078\u0079\u007a\u007b\u007c\u007d\u007e\u007f";
+
+ private static final String[] CHAR_STRING_ARRAY = new String[128];
+ private static final Character[] CHAR_ARRAY = new Character[128];
+
+ /**
+ * \u000a
linefeed LF ('\n').
+ *
+ * @see JLF: Escape Sequences
+ * for Character and String Literals
+ * @since 2.2
+ */
+ public static final char LF = '\n';
+
+ /**
+ * \u000d
carriage return CR ('\r').
+ *
+ * @see JLF: Escape Sequences
+ * for Character and String Literals
+ * @since 2.2
+ */
+ public static final char CR = '\r';
+
+
+ static {
+ for (int i = 127; i >= 0; i--) {
+ CHAR_STRING_ARRAY[i] = CHAR_STRING.substring(i, i + 1);
+ CHAR_ARRAY[i] = new Character((char) i);
+ }
+ }
+
+ /**
+ * CharUtils
instances should NOT be constructed in standard programming.
+ * Instead, the class should be used as CharUtils.toString('c');
.
+ *
+ * This constructor is public to permit tools that require a JavaBean instance
+ * to operate.
+ */
+ public CharUtils() {
+ super();
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Converts the character to a Character.
+ *
+ * For ASCII 7 bit characters, this uses a cache that will return the
+ * same Character object each time.
+ *
+ *
+ * CharUtils.toCharacterObject(' ') = ' '
+ * CharUtils.toCharacterObject('A') = 'A'
+ *
+ *
+ * @param ch the character to convert
+ * @return a Character of the specified character
+ */
+ public static Character toCharacterObject(char ch) {
+ if (ch < CHAR_ARRAY.length) {
+ return CHAR_ARRAY[ch];
+ }
+ return new Character(ch);
+ }
+
+ /**
+ * Converts the String to a Character using the first character, returning
+ * null for empty Strings.
+ *
+ * For ASCII 7 bit characters, this uses a cache that will return the
+ * same Character object each time.
+ *
+ *
+ * CharUtils.toCharacterObject(null) = null
+ * CharUtils.toCharacterObject("") = null
+ * CharUtils.toCharacterObject("A") = 'A'
+ * CharUtils.toCharacterObject("BA") = 'B'
+ *
+ *
+ * @param str the character to convert
+ * @return the Character value of the first letter of the String
+ */
+ public static Character toCharacterObject(String str) {
+ if (StringUtils.isEmpty(str)) {
+ return null;
+ }
+ return toCharacterObject(str.charAt(0));
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Converts the Character to a char throwing an exception for null
.
+ *
+ *
+ * CharUtils.toChar(null) = IllegalArgumentException
+ * CharUtils.toChar(' ') = ' '
+ * CharUtils.toChar('A') = 'A'
+ *
+ *
+ * @param ch the character to convert
+ * @return the char value of the Character
+ * @throws IllegalArgumentException if the Character is null
+ */
+ public static char toChar(Character ch) {
+ if (ch == null) {
+ throw new IllegalArgumentException("The Character must not be null");
+ }
+ return ch.charValue();
+ }
+
+ /**
+ * Converts the Character to a char handling null
.
+ *
+ *
+ * CharUtils.toChar(null, 'X') = 'X'
+ * CharUtils.toChar(' ', 'X') = ' '
+ * CharUtils.toChar('A', 'X') = 'A'
+ *
+ *
+ * @param ch the character to convert
+ * @param defaultValue the value to use if the Character is null
+ * @return the char value of the Character or the default if null
+ */
+ public static char toChar(Character ch, char defaultValue) {
+ if (ch == null) {
+ return defaultValue;
+ }
+ return ch.charValue();
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Converts the String to a char using the first character, throwing
+ * an exception on empty Strings.
+ *
+ *
+ * CharUtils.toChar(null) = IllegalArgumentException
+ * CharUtils.toChar("") = IllegalArgumentException
+ * CharUtils.toChar("A") = 'A'
+ * CharUtils.toChar("BA") = 'B'
+ *
+ *
+ * @param str the character to convert
+ * @return the char value of the first letter of the String
+ * @throws IllegalArgumentException if the String is empty
+ */
+ public static char toChar(String str) {
+ if (StringUtils.isEmpty(str)) {
+ throw new IllegalArgumentException("The String must not be empty");
+ }
+ return str.charAt(0);
+ }
+
+ /**
+ * Converts the String to a char using the first character, defaulting
+ * the value on empty Strings.
+ *
+ *
+ * CharUtils.toChar(null, 'X') = 'X'
+ * CharUtils.toChar("", 'X') = 'X'
+ * CharUtils.toChar("A", 'X') = 'A'
+ * CharUtils.toChar("BA", 'X') = 'B'
+ *
+ *
+ * @param str the character to convert
+ * @param defaultValue the value to use if the Character is null
+ * @return the char value of the first letter of the String or the default if null
+ */
+ public static char toChar(String str, char defaultValue) {
+ if (StringUtils.isEmpty(str)) {
+ return defaultValue;
+ }
+ return str.charAt(0);
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Converts the character to the Integer it represents, throwing an
+ * exception if the character is not numeric.
+ *
+ * This method coverts the char '1' to the int 1 and so on.
+ *
+ *
+ * CharUtils.toIntValue('3') = 3
+ * CharUtils.toIntValue('A') = IllegalArgumentException
+ *
+ *
+ * @param ch the character to convert
+ * @return the int value of the character
+ * @throws IllegalArgumentException if the character is not ASCII numeric
+ */
+ public static int toIntValue(char ch) {
+ if (isAsciiNumeric(ch) == false) {
+ throw new IllegalArgumentException("The character " + ch + " is not in the range '0' - '9'");
+ }
+ return ch - 48;
+ }
+
+ /**
+ * Converts the character to the Integer it represents, throwing an
+ * exception if the character is not numeric.
+ *
+ * This method coverts the char '1' to the int 1 and so on.
+ *
+ *
+ * CharUtils.toIntValue('3', -1) = 3
+ * CharUtils.toIntValue('A', -1) = -1
+ *
+ *
+ * @param ch the character to convert
+ * @param defaultValue the default value to use if the character is not numeric
+ * @return the int value of the character
+ */
+ public static int toIntValue(char ch, int defaultValue) {
+ if (isAsciiNumeric(ch) == false) {
+ return defaultValue;
+ }
+ return ch - 48;
+ }
+
+ /**
+ * Converts the character to the Integer it represents, throwing an
+ * exception if the character is not numeric.
+ *
+ * This method coverts the char '1' to the int 1 and so on.
+ *
+ *
+ * CharUtils.toIntValue(null) = IllegalArgumentException
+ * CharUtils.toIntValue('3') = 3
+ * CharUtils.toIntValue('A') = IllegalArgumentException
+ *
+ *
+ * @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
+ */
+ public static int toIntValue(Character ch) {
+ if (ch == null) {
+ throw new IllegalArgumentException("The character must not be null");
+ }
+ return toIntValue(ch.charValue());
+ }
+
+ /**
+ * Converts the character to the Integer it represents, throwing an
+ * exception if the character is not numeric.
+ *
+ * This method coverts the char '1' to the int 1 and so on.
+ *
+ *
+ * CharUtils.toIntValue(null, -1) = -1
+ * CharUtils.toIntValue('3', -1) = 3
+ * CharUtils.toIntValue('A', -1) = -1
+ *
+ *
+ * @param ch the character to convert
+ * @param defaultValue the default value to use if the character is not numeric
+ * @return the int value of the character
+ */
+ public static int toIntValue(Character ch, int defaultValue) {
+ if (ch == null) {
+ return defaultValue;
+ }
+ return toIntValue(ch.charValue(), defaultValue);
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Converts the character to a String that contains the one character.
+ *
+ * For ASCII 7 bit characters, this uses a cache that will return the
+ * same String object each time.
+ *
+ *
+ * CharUtils.toString(' ') = " "
+ * CharUtils.toString('A') = "A"
+ *
+ *
+ * @param ch the character to convert
+ * @return a String containing the one specified character
+ */
+ public static String toString(char ch) {
+ if (ch < 128) {
+ return CHAR_STRING_ARRAY[ch];
+ }
+ return new String(new char[] {ch});
+ }
+
+ /**
+ * Converts the character to a String that contains the one character.
+ *
+ * For ASCII 7 bit characters, this uses a cache that will return the
+ * same String object each time.
+ *
+ * If null
is passed in, null
will be returned.
+ *
+ *
+ * CharUtils.toString(null) = null
+ * CharUtils.toString(' ') = " "
+ * CharUtils.toString('A') = "A"
+ *
+ *
+ * @param ch the character to convert
+ * @return a String containing the one specified character
+ */
+ public static String toString(Character ch) {
+ if (ch == null) {
+ return null;
+ }
+ return toString(ch.charValue());
+ }
+
+ //--------------------------------------------------------------------------
+ /**
+ * Converts the string to the unicode format '\u0020'.
+ *
+ * This format is the Java source code format.
+ *
+ *
+ * CharUtils.unicodeEscaped(' ') = "\u0020"
+ * CharUtils.unicodeEscaped('A') = "\u0041"
+ *
+ *
+ * @param ch the character to convert
+ * @return the escaped unicode string
+ */
+ public static String unicodeEscaped(char ch) {
+ if (ch < 0x10) {
+ return "\\u000" + Integer.toHexString(ch);
+ } else if (ch < 0x100) {
+ return "\\u00" + Integer.toHexString(ch);
+ } else if (ch < 0x1000) {
+ return "\\u0" + Integer.toHexString(ch);
+ }
+ return "\\u" + Integer.toHexString(ch);
+ }
+
+ /**
+ * Converts the string to the unicode format '\u0020'.
+ *
+ * This format is the Java source code format.
+ *
+ * If null
is passed in, null
will be returned.
+ *
+ *
+ * CharUtils.unicodeEscaped(null) = null
+ * CharUtils.unicodeEscaped(' ') = "\u0020"
+ * CharUtils.unicodeEscaped('A') = "\u0041"
+ *
+ *
+ * @param ch the character to convert, may be null
+ * @return the escaped unicode string, null if null input
+ */
+ public static String unicodeEscaped(Character ch) {
+ if (ch == null) {
+ return null;
+ }
+ return unicodeEscaped(ch.charValue());
+ }
+
+ //--------------------------------------------------------------------------
+ /**
+ * Checks whether the character is ASCII 7 bit.
+ *
+ *
+ * CharUtils.isAscii('a') = true
+ * CharUtils.isAscii('A') = true
+ * CharUtils.isAscii('3') = true
+ * CharUtils.isAscii('-') = true
+ * CharUtils.isAscii('\n') = true
+ * CharUtils.isAscii('©') = false
+ *
+ *
+ * @param ch the character to check
+ * @return true if less than 128
+ */
+ public static boolean isAscii(char ch) {
+ return ch < 128;
+ }
+
+ /**
+ * Checks whether the character is ASCII 7 bit printable.
+ *
+ *
+ * CharUtils.isAsciiPrintable('a') = true
+ * CharUtils.isAsciiPrintable('A') = true
+ * CharUtils.isAsciiPrintable('3') = true
+ * CharUtils.isAsciiPrintable('-') = true
+ * CharUtils.isAsciiPrintable('\n') = false
+ * CharUtils.isAsciiPrintable('©') = false
+ *
+ *
+ * @param ch the character to check
+ * @return true if between 32 and 126 inclusive
+ */
+ public static boolean isAsciiPrintable(char ch) {
+ return ch >= 32 && ch < 127;
+ }
+
+ /**
+ * Checks whether the character is ASCII 7 bit control.
+ *
+ *
+ * CharUtils.isAsciiControl('a') = false
+ * CharUtils.isAsciiControl('A') = false
+ * CharUtils.isAsciiControl('3') = false
+ * CharUtils.isAsciiControl('-') = false
+ * CharUtils.isAsciiControl('\n') = true
+ * CharUtils.isAsciiControl('©') = false
+ *
+ *
+ * @param ch the character to check
+ * @return true if less than 32 or equals 127
+ */
+ public static boolean isAsciiControl(char ch) {
+ return ch < 32 || ch == 127;
+ }
+
+ /**
+ * Checks whether the character is ASCII 7 bit alphabetic.
+ *
+ *
+ * CharUtils.isAsciiAlpha('a') = true
+ * CharUtils.isAsciiAlpha('A') = true
+ * CharUtils.isAsciiAlpha('3') = false
+ * CharUtils.isAsciiAlpha('-') = false
+ * CharUtils.isAsciiAlpha('\n') = false
+ * CharUtils.isAsciiAlpha('©') = false
+ *
+ *
+ * @param ch the character to check
+ * @return true if between 65 and 90 or 97 and 122 inclusive
+ */
+ public static boolean isAsciiAlpha(char ch) {
+ return (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z');
+ }
+
+ /**
+ * Checks whether the character is ASCII 7 bit alphabetic upper case.
+ *
+ *
+ * CharUtils.isAsciiAlphaUpper('a') = false
+ * CharUtils.isAsciiAlphaUpper('A') = true
+ * CharUtils.isAsciiAlphaUpper('3') = false
+ * CharUtils.isAsciiAlphaUpper('-') = false
+ * CharUtils.isAsciiAlphaUpper('\n') = false
+ * CharUtils.isAsciiAlphaUpper('©') = false
+ *
+ *
+ * @param ch the character to check
+ * @return true if between 65 and 90 inclusive
+ */
+ public static boolean isAsciiAlphaUpper(char ch) {
+ return ch >= 'A' && ch <= 'Z';
+ }
+
+ /**
+ * Checks whether the character is ASCII 7 bit alphabetic lower case.
+ *
+ *
+ * CharUtils.isAsciiAlphaLower('a') = true
+ * CharUtils.isAsciiAlphaLower('A') = false
+ * CharUtils.isAsciiAlphaLower('3') = false
+ * CharUtils.isAsciiAlphaLower('-') = false
+ * CharUtils.isAsciiAlphaLower('\n') = false
+ * CharUtils.isAsciiAlphaLower('©') = false
+ *
+ *
+ * @param ch the character to check
+ * @return true if between 97 and 122 inclusive
+ */
+ public static boolean isAsciiAlphaLower(char ch) {
+ return ch >= 'a' && ch <= 'z';
+ }
+
+ /**
+ * Checks whether the character is ASCII 7 bit numeric.
+ *
+ *
+ * CharUtils.isAsciiNumeric('a') = false
+ * CharUtils.isAsciiNumeric('A') = false
+ * CharUtils.isAsciiNumeric('3') = true
+ * CharUtils.isAsciiNumeric('-') = false
+ * CharUtils.isAsciiNumeric('\n') = false
+ * CharUtils.isAsciiNumeric('©') = false
+ *
+ *
+ * @param ch the character to check
+ * @return true if between 48 and 57 inclusive
+ */
+ public static boolean isAsciiNumeric(char ch) {
+ return ch >= '0' && ch <= '9';
+ }
+
+ /**
+ * Checks whether the character is ASCII 7 bit numeric.
+ *
+ *
+ * CharUtils.isAsciiAlphanumeric('a') = true
+ * CharUtils.isAsciiAlphanumeric('A') = true
+ * CharUtils.isAsciiAlphanumeric('3') = true
+ * CharUtils.isAsciiAlphanumeric('-') = false
+ * CharUtils.isAsciiAlphanumeric('\n') = false
+ * CharUtils.isAsciiAlphanumeric('©') = false
+ *
+ *
+ * @param ch the character to check
+ * @return true if between 48 and 57 or 65 and 90 or 97 and 122 inclusive
+ */
+ public static boolean isAsciiAlphanumeric(char ch) {
+ return (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9');
+ }
+
+ // ----------------- Following code copied from Apache Harmony (Character class)
+ /**
+ * Indicates whether {@code ch} is a high- (or leading-) surrogate code unit
+ * that is used for representing supplementary characters in UTF-16
+ * encoding.
+ *
+ * @param ch
+ * the character to test.
+ * @return {@code true} if {@code ch} is a high-surrogate code unit;
+ * {@code false} otherwise.
+ */
+ static boolean isHighSurrogate(char ch) {
+ return ('\uD800' <= ch && '\uDBFF' >= ch);
+ }
+
+}
Index: 3rdParty_sources/commons-lang/org/apache/commons/lang/ClassUtils.java
===================================================================
RCS file: /usr/local/cvsroot/3rdParty_sources/commons-lang/org/apache/commons/lang/ClassUtils.java,v
diff -u -r1.1 -r1.2
--- 3rdParty_sources/commons-lang/org/apache/commons/lang/ClassUtils.java 30 Aug 2012 16:24:42 -0000 1.1
+++ 3rdParty_sources/commons-lang/org/apache/commons/lang/ClassUtils.java 15 Mar 2013 09:52:49 -0000 1.2
@@ -1,95 +1,138 @@
-/* ====================================================================
- * The Apache Software License, Version 1.1
+/*
+ * 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
*
- * Copyright (c) 2002-2003 The Apache Software Foundation. All rights
- * reserved.
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in
- * the documentation and/or other materials provided with the
- * distribution.
- *
- * 3. The end-user documentation included with the redistribution, if
- * any, must include the following acknowledgement:
- * "This product includes software developed by the
- * Apache Software Foundation (http://www.apache.org/)."
- * Alternately, this acknowledgement may appear in the software itself,
- * if and wherever such third-party acknowledgements normally appear.
- *
- * 4. The names "The Jakarta Project", "Commons", and "Apache Software
- * Foundation" must not be used to endorse or promote products derived
- * from this software without prior written permission. For written
- * permission, please contact apache@apache.org.
- *
- * 5. Products derived from this software may not be called "Apache"
- * nor may "Apache" appear in their names without prior written
- * permission of the Apache Software Foundation.
- *
- * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
- * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
- * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
- * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- * ====================================================================
- *
- * This software consists of voluntary contributions made by many
- * individuals on behalf of the Apache Software Foundation. For more
- * information on the Apache Software Foundation, please see
- * .
+ * 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.lang;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
import java.util.ArrayList;
+import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
+import java.util.Map;
+
+import org.apache.commons.lang.text.StrBuilder;
+
/**
* Operates on classes without using reflection.
*
* This class handles invalid null
inputs as best it can.
* Each method documents its behaviour in more detail.
*
- * @author Stephen Colebourne
+ * The notion of a canonical name
includes the human
+ * readable name for the type, for example int[]
. The
+ * non-canonical method variants work with the JVM names, such as
+ * [I
.
+ *
+ * @author Apache Software Foundation
* @author Gary Gregory
+ * @author Norm Deane
+ * @author Alban Peignier
+ * @author Tomasz Blachowicz
* @since 2.0
* @version $Id$
*/
public class ClassUtils {
/**
- * The package separator character: .
.
+ * The package separator character: '.' == {@value}
.
*/
public static final char PACKAGE_SEPARATOR_CHAR = '.';
-
+
/**
- * The package separator String: .
.
+ * The package separator String: "."
.
*/
public static final String PACKAGE_SEPARATOR = String.valueOf(PACKAGE_SEPARATOR_CHAR);
-
+
/**
- * The inner class separator character: $
.
+ * The inner class separator character: '$' == {@value}
.
*/
public static final char INNER_CLASS_SEPARATOR_CHAR = '$';
-
+
/**
- * The inner class separator String: $
.
+ * The inner class separator String: "$"
.
*/
public static final String INNER_CLASS_SEPARATOR = String.valueOf(INNER_CLASS_SEPARATOR_CHAR);
-
+
/**
+ * Maps primitive Class
es to their corresponding wrapper Class
.
+ */
+ private static final Map primitiveWrapperMap = new HashMap();
+ static {
+ primitiveWrapperMap.put(Boolean.TYPE, Boolean.class);
+ primitiveWrapperMap.put(Byte.TYPE, Byte.class);
+ primitiveWrapperMap.put(Character.TYPE, Character.class);
+ primitiveWrapperMap.put(Short.TYPE, Short.class);
+ primitiveWrapperMap.put(Integer.TYPE, Integer.class);
+ primitiveWrapperMap.put(Long.TYPE, Long.class);
+ primitiveWrapperMap.put(Double.TYPE, Double.class);
+ primitiveWrapperMap.put(Float.TYPE, Float.class);
+ primitiveWrapperMap.put(Void.TYPE, Void.TYPE);
+ }
+
+ /**
+ * Maps wrapper Class
es to their corresponding primitive types.
+ */
+ private static final Map wrapperPrimitiveMap = new HashMap();
+ static {
+ for (Iterator it = primitiveWrapperMap.keySet().iterator(); it.hasNext();) {
+ Class primitiveClass = (Class) it.next();
+ Class wrapperClass = (Class) primitiveWrapperMap.get(primitiveClass);
+ if (!primitiveClass.equals(wrapperClass)) {
+ wrapperPrimitiveMap.put(wrapperClass, primitiveClass);
+ }
+ }
+ }
+
+ /**
+ * Maps a primitive class name to its corresponding abbreviation used in array class names.
+ */
+ private static final Map abbreviationMap = new HashMap();
+
+ /**
+ * Maps an abbreviation used in array class names to corresponding primitive class name.
+ */
+ private static final Map reverseAbbreviationMap = new HashMap();
+
+ /**
+ * Add primitive type abbreviation to maps of abbreviations.
+ *
+ * @param primitive Canonical name of primitive type
+ * @param abbreviation Corresponding abbreviation of primitive type
+ */
+ private static void addAbbreviation(String primitive, String abbreviation) {
+ abbreviationMap.put(primitive, abbreviation);
+ reverseAbbreviationMap.put(abbreviation, primitive);
+ }
+
+ /**
+ * Feed abbreviation maps
+ */
+ static {
+ addAbbreviation("int", "I");
+ addAbbreviation("boolean", "Z");
+ addAbbreviation("float", "F");
+ addAbbreviation("long", "J");
+ addAbbreviation("short", "S");
+ addAbbreviation("byte", "B");
+ addAbbreviation("double", "D");
+ addAbbreviation("char", "C");
+ }
+
+ /**
* ClassUtils instances should NOT be constructed in standard programming.
* Instead, the class should be used as
* ClassUtils.getShortClassName(cls)
.
@@ -98,13 +141,14 @@
* instance to operate.
*/
public ClassUtils() {
+ super();
}
// Short class name
// ----------------------------------------------------------------------
/**
* Gets the class name minus the package name for an Object
.
- *
+ *
* @param object the class to get the short name for, may be null
* @param valueIfNull the value to return if null
* @return the class name of the object without the package name, or the null value
@@ -113,55 +157,71 @@
if (object == null) {
return valueIfNull;
}
- return getShortClassName(object.getClass().getName());
+ return getShortClassName(object.getClass());
}
-
+
/**
* Gets the class name minus the package name from a Class
.
- *
- * @param cls the class to get the short name for, must not be
- * null
- * @return the class name without the package name
- * @throws IllegalArgumentException if the class is null
+ *
+ * @param cls the class to get the short name for.
+ * @return the class name without the package name or an empty string
*/
public static String getShortClassName(Class cls) {
if (cls == null) {
- throw new IllegalArgumentException("The class must not be null");
+ return StringUtils.EMPTY;
}
return getShortClassName(cls.getName());
}
-
+
/**
* Gets the class name minus the package name from a String.
*
* The string passed in is assumed to be a class name - it is not checked.
- *
- * @param className the className to get the short name for,
- * must not be empty or null
- * @return the class name of the class without the package name
- * @throws IllegalArgumentException if the className is empty
+ *
+ * @param className the className to get the short name for
+ * @return the class name of the class without the package name or an empty string
*/
public static String getShortClassName(String className) {
- if (StringUtils.isEmpty(className)) {
- throw new IllegalArgumentException("The class name must not be empty");
+ if (className == null) {
+ return StringUtils.EMPTY;
}
- char[] chars = className.toCharArray();
- int lastDot = 0;
- for (int i = 0; i < chars.length; i++) {
- if (chars[i] == PACKAGE_SEPARATOR_CHAR) {
- lastDot = i + 1;
- } else if (chars[i] == INNER_CLASS_SEPARATOR_CHAR) { // handle inner classes
- chars[i] = PACKAGE_SEPARATOR_CHAR;
+ if (className.length() == 0) {
+ return StringUtils.EMPTY;
+ }
+
+ StrBuilder arrayPrefix = new StrBuilder();
+
+ // Handle array encoding
+ if (className.startsWith("[")) {
+ while (className.charAt(0) == '[') {
+ className = className.substring(1);
+ arrayPrefix.append("[]");
}
+ // Strip Object type encoding
+ if (className.charAt(0) == 'L' && className.charAt(className.length() - 1) == ';') {
+ className = className.substring(1, className.length() - 1);
+ }
}
- return new String(chars, lastDot, chars.length - lastDot);
+
+ if (reverseAbbreviationMap.containsKey(className)) {
+ className = (String)reverseAbbreviationMap.get(className);
+ }
+
+ int lastDotIdx = className.lastIndexOf(PACKAGE_SEPARATOR_CHAR);
+ int innerIdx = className.indexOf(
+ INNER_CLASS_SEPARATOR_CHAR, lastDotIdx == -1 ? 0 : lastDotIdx + 1);
+ String out = className.substring(lastDotIdx + 1);
+ if (innerIdx != -1) {
+ out = out.replace(INNER_CLASS_SEPARATOR_CHAR, PACKAGE_SEPARATOR_CHAR);
+ }
+ return out + arrayPrefix;
}
-
+
// Package name
// ----------------------------------------------------------------------
/**
* Gets the package name of an Object
.
- *
+ *
* @param object the class to get the package name for, may be null
* @param valueIfNull the value to return if null
* @return the package name of the object, or the null value
@@ -170,51 +230,58 @@
if (object == null) {
return valueIfNull;
}
- return getPackageName(object.getClass().getName());
+ return getPackageName(object.getClass());
}
-
+
/**
* Gets the package name of a Class
.
- *
- * @param cls the class to get the package name for,
- * must not be null
- * @return the package name
- * @throws IllegalArgumentException if the class is null
+ *
+ * @param cls the class to get the package name for, may be null
.
+ * @return the package name or an empty string
*/
public static String getPackageName(Class cls) {
if (cls == null) {
- throw new IllegalArgumentException("The class must not be null");
+ return StringUtils.EMPTY;
}
return getPackageName(cls.getName());
}
-
+
/**
* Gets the package name from a String
.
*
* The string passed in is assumed to be a class name - it is not checked.
- *
- * @param className the className to get the package name for,
- * must not be empty or null
- * @return the package name
- * @throws IllegalArgumentException if the className is empty
+ * If the class is unpackaged, return an empty string.
+ *
+ * @param className the className to get the package name for, may be null
+ * @return the package name or an empty string
*/
public static String getPackageName(String className) {
- if (StringUtils.isEmpty(className)) {
- throw new IllegalArgumentException("The class name must not be empty");
+ if (className == null || className.length() == 0) {
+ return StringUtils.EMPTY;
}
+
+ // Strip array encoding
+ while (className.charAt(0) == '[') {
+ className = className.substring(1);
+ }
+ // Strip Object type encoding
+ if (className.charAt(0) == 'L' && className.charAt(className.length() - 1) == ';') {
+ className = className.substring(1);
+ }
+
int i = className.lastIndexOf(PACKAGE_SEPARATOR_CHAR);
if (i == -1) {
- return "";
+ return StringUtils.EMPTY;
}
return className.substring(0, i);
}
-
+
// Superclasses/Superinterfaces
// ----------------------------------------------------------------------
/**
* Gets a List
of superclasses for the given class.
- *
- * @param cls the class to look up, must not be null
+ *
+ * @param cls the class to look up, may be null
* @return the List
of superclasses in order going up from this one
* null
if null input
*/
@@ -230,97 +297,52 @@
}
return classes;
}
-
+
/**
* Gets a List
of all interfaces implemented by the given
* class and its superclasses.
*
* The order is determined by looking through each interface in turn as
- * declared in the source file and following its hieracrchy up. Then each
- * superclass is considered in the same way. Later duplicates are ignored,
+ * declared in the source file and following its hierarchy up. Then each
+ * superclass is considered in the same way. Later duplicates are ignored,
* so the order is maintained.
- *
- * @param cls the class to look up, must not be null
+ *
+ * @param cls the class to look up, may be null
* @return the List
of interfaces in order,
* null
if null input
*/
public static List getAllInterfaces(Class cls) {
if (cls == null) {
return null;
}
- List list = new ArrayList();
+
+ List interfacesFound = new ArrayList();
+ getAllInterfaces(cls, interfacesFound);
+
+ return interfacesFound;
+ }
+
+ /**
+ * Get the interfaces for the specified class.
+ *
+ * @param cls the class to look up, may be null
+ * @param interfacesFound the Set
of interfaces for the class
+ */
+ private static void getAllInterfaces(Class cls, List interfacesFound) {
while (cls != null) {
Class[] interfaces = cls.getInterfaces();
+
for (int i = 0; i < interfaces.length; i++) {
- if (list.contains(interfaces[i]) == false) {
- list.add(interfaces[i]);
+ if (!interfacesFound.contains(interfaces[i])) {
+ interfacesFound.add(interfaces[i]);
+ getAllInterfaces(interfaces[i], interfacesFound);
}
- List superInterfaces = getAllInterfaces(interfaces[i]);
- for (Iterator it = superInterfaces.iterator(); it.hasNext();) {
- Class intface = (Class) it.next();
- if (list.contains(intface) == false) {
- list.add(intface);
- }
- }
}
+
cls = cls.getSuperclass();
- }
- return list;
- }
-
-// /**
-// * Gets a List
of subclasses of the specified class.
-// *
-// * This method searches the classpath to find all the subclasses
-// * of a particular class available. No classes are loaded, the
-// * returned list contains class names, not classes.
-// *
-// * @param cls the class to find subclasses for
-// * @return the List
of subclass String class names
-// * @throws IllegalArgumentException if the class is null
-// */
-// public static List getAllSubclassNames(Class cls) {
-// if (cls == null) {
-// throw new IllegalArgumentException("The class must not be null");
-// }
-// // TODO Use JavaWorld tip for searching the classpath
-// return null;
-// }
+ }
+ }
-// /**
-// * Gets a List
of subclasses of the specified class.
-// *
-// * This method searches the classpath to find all the subclasses
-// * of a particular class available.
-// *
-// * @param cls the class to find subclasses for
-// * @return the List
of subclasses
-// * @throws IllegalArgumentException if the class is null
-// */
-// public static List getAllSubclasses(Class cls) {
-// List names = getAllSubclassNames(cls);
-// return convertClassNamesToClasses(names);
-// }
-
-// /**
-// * Gets a List
of implementations of the specified interface.
-// *
-// * This method searches the classpath to find all the implementations
-// * of a particular interface available. No classes are loaded, the
-// * returned list contains class names, not classes.
-// *
-// * @param cls the class to find sub classes for
-// * @return the List
of implementation String class names
-// * @throws IllegalArgumentException if the class is null
-// */
-// public static List getAllImplementationClassNames(Class cls) {
-// if (cls == null) {
-// throw new IllegalArgumentException("The class must not be null");
-// }
-// // TODO Use JavaWorld tip for searching the classpath
-// return null;
-// }
-
// Convert list
// ----------------------------------------------------------------------
/**
@@ -329,7 +351,7 @@
* A new List
is returned. If the class name cannot be found, null
* is stored in the List
. If the class name in the List
is
* null
, null
is stored in the output List
.
- *
+ *
* @param classNames the classNames to change
* @return a List
of Class objects corresponding to the class names,
* null
if null input
@@ -350,18 +372,18 @@
}
return classes;
}
-
+
/**
* Given a List
of Class
objects, this method converts
* them into class names.
*
* A new List
is returned. null
objects will be copied into
* the returned list as null
.
- *
+ *
* @param classes the classes to change
- * @return a List
of Class objects corresponding to the class names,
+ * @return a List
of class names corresponding to the Class objects,
* null
if null input
- * @throws ClassCastException if classNames contains a non Class or null entry
+ * @throws ClassCastException if classes
contains a non-Class
entry
*/
public static List convertClassesToClassNames(List classes) {
if (classes == null) {
@@ -378,15 +400,15 @@
}
return classNames;
}
-
+
// Is assignable
// ----------------------------------------------------------------------
/**
* Checks if an array of Classes can be assigned to another array of Classes.
*
* This method calls {@link #isAssignable(Class, Class) isAssignable} for each
* Class pair in the input arrays. It can be used to check if a set of arguments
- * (the first parameter) are suitably compatable with a set of method parameter types
+ * (the first parameter) are suitably compatible with a set of method parameter types
* (the second parameter).
*
* Unlike the {@link Class#isAssignableFrom(java.lang.Class)} method, this
@@ -404,7 +426,7 @@
*
Specifically, this method tests whether the type represented by the
* specified Class
parameter can be converted to the type
* represented by this Class
object via an identity conversion
- * widening primitive or widening reference conversion. See
+ * widening primitive or widening reference conversion. See
* The Java Language Specification,
* sections 5.1.1, 5.1.2 and 5.1.4 for details.
*
@@ -413,6 +435,43 @@
* @return true
if assignment possible
*/
public static boolean isAssignable(Class[] classArray, Class[] toClassArray) {
+ return isAssignable(classArray, toClassArray, false);
+ }
+
+ /**
+ * Checks if an array of Classes can be assigned to another array of Classes.
+ *
+ * This method calls {@link #isAssignable(Class, Class) isAssignable} for each
+ * Class pair in the input arrays. It can be used to check if a set of arguments
+ * (the first parameter) are suitably compatible with a set of method parameter types
+ * (the second parameter).
+ *
+ * Unlike the {@link Class#isAssignableFrom(java.lang.Class)} method, this
+ * method takes into account widenings of primitive classes and
+ * null
s.
+ *
+ * Primitive widenings allow an int to be assigned to a long
,
+ * float
or double
. This method returns the correct
+ * result for these cases.
+ *
+ * Null
may be assigned to any reference type. This method will
+ * return true
if null
is passed in and the toClass is
+ * non-primitive.
+ *
+ * Specifically, this method tests whether the type represented by the
+ * specified Class
parameter can be converted to the type
+ * represented by this Class
object via an identity conversion
+ * widening primitive or widening reference conversion. See
+ * The Java Language Specification,
+ * sections 5.1.1, 5.1.2 and 5.1.4 for details.
+ *
+ * @param classArray the array of Classes to check, may be null
+ * @param toClassArray the array of Classes to try to assign into, may be null
+ * @param autoboxing whether to use implicit autoboxing/unboxing between primitives and wrappers
+ * @return true
if assignment possible
+ * @since 2.5
+ */
+ public static boolean isAssignable(Class[] classArray, Class[] toClassArray, boolean autoboxing) {
if (ArrayUtils.isSameLength(classArray, toClassArray) == false) {
return false;
}
@@ -423,13 +482,13 @@
toClassArray = ArrayUtils.EMPTY_CLASS_ARRAY;
}
for (int i = 0; i < classArray.length; i++) {
- if (isAssignable(classArray[i], toClassArray[i]) == false) {
+ if (isAssignable(classArray[i], toClassArray[i], autoboxing) == false) {
return false;
}
}
return true;
}
-
+
/**
* Checks if one Class
can be assigned to a variable of
* another Class
.
@@ -448,7 +507,7 @@
* Specifically, this method tests whether the type represented by the
* specified Class
parameter can be converted to the type
* represented by this Class
object via an identity conversion
- * widening primitive or widening reference conversion. See
+ * widening primitive or widening reference conversion. See
* The Java Language Specification,
* sections 5.1.1, 5.1.2 and 5.1.4 for details.
*
@@ -457,13 +516,60 @@
* @return true
if assignment possible
*/
public static boolean isAssignable(Class cls, Class toClass) {
+ return isAssignable(cls, toClass, false);
+ }
+
+ /**
+ * Checks if one Class
can be assigned to a variable of
+ * another Class
.
+ *
+ * Unlike the {@link Class#isAssignableFrom(java.lang.Class)} method,
+ * this method takes into account widenings of primitive classes and
+ * null
s.
+ *
+ * Primitive widenings allow an int to be assigned to a long, float or
+ * double. This method returns the correct result for these cases.
+ *
+ * Null
may be assigned to any reference type. This method
+ * will return true
if null
is passed in and the
+ * toClass is non-primitive.
+ *
+ * Specifically, this method tests whether the type represented by the
+ * specified Class
parameter can be converted to the type
+ * represented by this Class
object via an identity conversion
+ * widening primitive or widening reference conversion. See
+ * The Java Language Specification,
+ * sections 5.1.1, 5.1.2 and 5.1.4 for details.
+ *
+ * @param cls the Class to check, may be null
+ * @param toClass the Class to try to assign into, returns false if null
+ * @param autoboxing whether to use implicit autoboxing/unboxing between primitives and wrappers
+ * @return true
if assignment possible
+ * @since 2.5
+ */
+ public static boolean isAssignable(Class cls, Class toClass, boolean autoboxing) {
if (toClass == null) {
return false;
}
// have to check for null, as isAssignableFrom doesn't
if (cls == null) {
return !(toClass.isPrimitive());
}
+ //autoboxing:
+ if (autoboxing) {
+ if (cls.isPrimitive() && !toClass.isPrimitive()) {
+ cls = primitiveToWrapper(cls);
+ if (cls == null) {
+ return false;
+ }
+ }
+ if (toClass.isPrimitive() && !cls.isPrimitive()) {
+ cls = wrapperToPrimitive(cls);
+ if (cls == null) {
+ return false;
+ }
+ }
+ }
if (cls.equals(toClass)) {
return true;
}
@@ -472,12 +578,12 @@
return false;
}
if (Integer.TYPE.equals(cls)) {
- return Long.TYPE.equals(toClass)
- || Float.TYPE.equals(toClass)
+ return Long.TYPE.equals(toClass)
+ || Float.TYPE.equals(toClass)
|| Double.TYPE.equals(toClass);
}
if (Long.TYPE.equals(cls)) {
- return Float.TYPE.equals(toClass)
+ return Float.TYPE.equals(toClass)
|| Double.TYPE.equals(toClass);
}
if (Boolean.TYPE.equals(cls)) {
@@ -490,44 +596,474 @@
return Double.TYPE.equals(toClass);
}
if (Character.TYPE.equals(cls)) {
- return Integer.TYPE.equals(toClass)
- || Long.TYPE.equals(toClass)
- || Float.TYPE.equals(toClass)
+ return Integer.TYPE.equals(toClass)
+ || Long.TYPE.equals(toClass)
+ || Float.TYPE.equals(toClass)
|| Double.TYPE.equals(toClass);
}
if (Short.TYPE.equals(cls)) {
- return Integer.TYPE.equals(toClass)
- || Long.TYPE.equals(toClass)
- || Float.TYPE.equals(toClass)
+ return Integer.TYPE.equals(toClass)
+ || Long.TYPE.equals(toClass)
+ || Float.TYPE.equals(toClass)
|| Double.TYPE.equals(toClass);
}
if (Byte.TYPE.equals(cls)) {
- return Short.TYPE.equals(toClass)
- || Integer.TYPE.equals(toClass)
- || Long.TYPE.equals(toClass)
- || Float.TYPE.equals(toClass)
+ return Short.TYPE.equals(toClass)
+ || Integer.TYPE.equals(toClass)
+ || Long.TYPE.equals(toClass)
+ || Float.TYPE.equals(toClass)
|| Double.TYPE.equals(toClass);
}
// should never get here
return false;
}
return toClass.isAssignableFrom(cls);
}
-
+
+ /**
+ * Converts the specified primitive Class object to its corresponding
+ * wrapper Class object.
+ *
+ * NOTE: From v2.2, this method handles Void.TYPE
,
+ * returning Void.TYPE
.
+ *
+ * @param cls the class to convert, may be null
+ * @return the wrapper class for cls
or cls
if
+ * cls
is not a primitive. null
if null input.
+ * @since 2.1
+ */
+ public static Class primitiveToWrapper(Class cls) {
+ Class convertedClass = cls;
+ if (cls != null && cls.isPrimitive()) {
+ convertedClass = (Class) primitiveWrapperMap.get(cls);
+ }
+ return convertedClass;
+ }
+
+ /**
+ * Converts the specified array of primitive Class objects to an array of
+ * its corresponding wrapper Class objects.
+ *
+ * @param classes the class array to convert, may be null or empty
+ * @return an array which contains for each given class, the wrapper class or
+ * the original class if class is not a primitive. null
if null input.
+ * Empty array if an empty array passed in.
+ * @since 2.1
+ */
+ public static Class[] primitivesToWrappers(Class[] classes) {
+ if (classes == null) {
+ return null;
+ }
+
+ if (classes.length == 0) {
+ return classes;
+ }
+
+ Class[] convertedClasses = new Class[classes.length];
+ for (int i = 0; i < classes.length; i++) {
+ convertedClasses[i] = primitiveToWrapper(classes[i]);
+ }
+ return convertedClasses;
+ }
+
+ /**
+ * Converts the specified wrapper class to its corresponding primitive
+ * class.
+ *
+ * This method is the counter part of primitiveToWrapper()
.
+ * If the passed in class is a wrapper class for a primitive type, this
+ * primitive type will be returned (e.g. Integer.TYPE
for
+ * Integer.class
). For other classes, or if the parameter is
+ * null, the return value is null.
+ *
+ * @param cls the class to convert, may be null
+ * @return the corresponding primitive type if cls
is a
+ * wrapper class, null otherwise
+ * @see #primitiveToWrapper(Class)
+ * @since 2.4
+ */
+ public static Class wrapperToPrimitive(Class cls) {
+ return (Class) wrapperPrimitiveMap.get(cls);
+ }
+
+ /**
+ * Converts the specified array of wrapper Class objects to an array of
+ * its corresponding primitive Class objects.
+ *
+ * This method invokes wrapperToPrimitive()
for each element
+ * of the passed in array.
+ *
+ * @param classes the class array to convert, may be null or empty
+ * @return an array which contains for each given class, the primitive class or
+ * null if the original class is not a wrapper class. null
if null input.
+ * Empty array if an empty array passed in.
+ * @see #wrapperToPrimitive(Class)
+ * @since 2.4
+ */
+ public static Class[] wrappersToPrimitives(Class[] classes) {
+ if (classes == null) {
+ return null;
+ }
+
+ if (classes.length == 0) {
+ return classes;
+ }
+
+ Class[] convertedClasses = new Class[classes.length];
+ for (int i = 0; i < classes.length; i++) {
+ convertedClasses[i] = wrapperToPrimitive(classes[i]);
+ }
+ return convertedClasses;
+ }
+
// Inner class
// ----------------------------------------------------------------------
/**
* Is the specified class an inner class or static nested class.
- *
- * @param cls the class to check
+ *
+ * @param cls the class to check, may be null
* @return true
if the class is an inner or static nested class,
* false if not or null
*/
public static boolean isInnerClass(Class cls) {
if (cls == null) {
return false;
}
- return (cls.getName().indexOf(INNER_CLASS_SEPARATOR_CHAR) >= 0);
+ return cls.getName().indexOf(INNER_CLASS_SEPARATOR_CHAR) >= 0;
}
-
+
+ // Class loading
+ // ----------------------------------------------------------------------
+ /**
+ * Returns the class represented by className
using the
+ * classLoader
. This implementation supports the syntaxes
+ * "java.util.Map.Entry[]
", "java.util.Map$Entry[]
",
+ * "[Ljava.util.Map.Entry;
", and "[Ljava.util.Map$Entry;
".
+ *
+ * @param classLoader the class loader to use to load the class
+ * @param className the class name
+ * @param initialize whether the class must be initialized
+ * @return the class represented by className
using the classLoader
+ * @throws ClassNotFoundException if the class is not found
+ */
+ public static Class getClass(
+ ClassLoader classLoader, String className, boolean initialize) throws ClassNotFoundException {
+ try {
+ Class clazz;
+ if (abbreviationMap.containsKey(className)) {
+ String clsName = "[" + abbreviationMap.get(className);
+ clazz = Class.forName(clsName, initialize, classLoader).getComponentType();
+ } else {
+ clazz = Class.forName(toCanonicalName(className), initialize, classLoader);
+ }
+ return clazz;
+ } catch (ClassNotFoundException ex) {
+ // allow path separators (.) as inner class name separators
+ int lastDotIndex = className.lastIndexOf(PACKAGE_SEPARATOR_CHAR);
+
+ if (lastDotIndex != -1) {
+ try {
+ return getClass(classLoader, className.substring(0, lastDotIndex) +
+ INNER_CLASS_SEPARATOR_CHAR + className.substring(lastDotIndex + 1),
+ initialize);
+ } catch (ClassNotFoundException ex2) {
+ }
+ }
+
+ throw ex;
+ }
+ }
+
+ /**
+ * Returns the (initialized) class represented by className
+ * using the classLoader
. This implementation supports
+ * the syntaxes "java.util.Map.Entry[]
",
+ * "java.util.Map$Entry[]
", "[Ljava.util.Map.Entry;
",
+ * and "[Ljava.util.Map$Entry;
".
+ *
+ * @param classLoader the class loader to use to load the class
+ * @param className the class name
+ * @return the class represented by className
using the classLoader
+ * @throws ClassNotFoundException if the class is not found
+ */
+ public static Class getClass(ClassLoader classLoader, String className) throws ClassNotFoundException {
+ return getClass(classLoader, className, true);
+ }
+
+ /**
+ * Returns the (initialized) class represented by className
+ * using the current thread's context class loader. This implementation
+ * supports the syntaxes "java.util.Map.Entry[]
",
+ * "java.util.Map$Entry[]
", "[Ljava.util.Map.Entry;
",
+ * and "[Ljava.util.Map$Entry;
".
+ *
+ * @param className the class name
+ * @return the class represented by className
using the current thread's context class loader
+ * @throws ClassNotFoundException if the class is not found
+ */
+ public static Class getClass(String className) throws ClassNotFoundException {
+ return getClass(className, true);
+ }
+
+ /**
+ * Returns the class represented by className
using the
+ * current thread's context class loader. This implementation supports the
+ * syntaxes "java.util.Map.Entry[]
", "java.util.Map$Entry[]
",
+ * "[Ljava.util.Map.Entry;
", and "[Ljava.util.Map$Entry;
".
+ *
+ * @param className the class name
+ * @param initialize whether the class must be initialized
+ * @return the class represented by className
using the current thread's context class loader
+ * @throws ClassNotFoundException if the class is not found
+ */
+ public static Class getClass(String className, boolean initialize) throws ClassNotFoundException {
+ ClassLoader contextCL = Thread.currentThread().getContextClassLoader();
+ ClassLoader loader = contextCL == null ? ClassUtils.class.getClassLoader() : contextCL;
+ return getClass(loader, className, initialize );
+ }
+
+ // Public method
+ // ----------------------------------------------------------------------
+ /**
+ * Returns the desired Method much like Class.getMethod
, however
+ * it ensures that the returned Method is from a public class or interface and not
+ * from an anonymous inner class. This means that the Method is invokable and
+ * doesn't fall foul of Java bug
+ * 4071957).
+ *
+ * Set set = Collections.unmodifiableSet(...);
+ * Method method = ClassUtils.getPublicMethod(set.getClass(), "isEmpty", new Class[0]);
+ * Object result = method.invoke(set, new Object[]);
+ *
+ *
+ * @param cls the class to check, not null
+ * @param methodName the name of the method
+ * @param parameterTypes the list of parameters
+ * @return the method
+ * @throws NullPointerException if the class is null
+ * @throws SecurityException if a a security violation occured
+ * @throws NoSuchMethodException if the method is not found in the given class
+ * or if the metothod doen't conform with the requirements
+ */
+ public static Method getPublicMethod(Class cls, String methodName, Class parameterTypes[])
+ throws SecurityException, NoSuchMethodException {
+
+ Method declaredMethod = cls.getMethod(methodName, parameterTypes);
+ if (Modifier.isPublic(declaredMethod.getDeclaringClass().getModifiers())) {
+ return declaredMethod;
+ }
+
+ List candidateClasses = new ArrayList();
+ candidateClasses.addAll(getAllInterfaces(cls));
+ candidateClasses.addAll(getAllSuperclasses(cls));
+
+ for (Iterator it = candidateClasses.iterator(); it.hasNext(); ) {
+ Class candidateClass = (Class) it.next();
+ if (!Modifier.isPublic(candidateClass.getModifiers())) {
+ continue;
+ }
+ Method candidateMethod;
+ try {
+ candidateMethod = candidateClass.getMethod(methodName, parameterTypes);
+ } catch (NoSuchMethodException ex) {
+ continue;
+ }
+ if (Modifier.isPublic(candidateMethod.getDeclaringClass().getModifiers())) {
+ return candidateMethod;
+ }
+ }
+
+ throw new NoSuchMethodException("Can't find a public method for " +
+ methodName + " " + ArrayUtils.toString(parameterTypes));
+ }
+
+ // ----------------------------------------------------------------------
+ /**
+ * Converts a class name to a JLS style class name.
+ *
+ * @param className the class name
+ * @return the converted name
+ */
+ private static String toCanonicalName(String className) {
+ className = StringUtils.deleteWhitespace(className);
+ if (className == null) {
+ throw new NullArgumentException("className");
+ } else if (className.endsWith("[]")) {
+ StrBuilder classNameBuffer = new StrBuilder();
+ while (className.endsWith("[]")) {
+ className = className.substring(0, className.length() - 2);
+ classNameBuffer.append("[");
+ }
+ String abbreviation = (String) abbreviationMap.get(className);
+ if (abbreviation != null) {
+ classNameBuffer.append(abbreviation);
+ } else {
+ classNameBuffer.append("L").append(className).append(";");
+ }
+ className = classNameBuffer.toString();
+ }
+ return className;
+ }
+
+ /**
+ * Converts an array of Object
in to an array of Class
objects.
+ * If any of these objects is null, a null element will be inserted into the array.
+ *
+ * This method returns null
for a null
input array.
+ *
+ * @param array an Object
array
+ * @return a Class
array, null
if null array input
+ * @since 2.4
+ */
+ public static Class[] toClass(Object[] array) {
+ if (array == null) {
+ return null;
+ } else if (array.length == 0) {
+ return ArrayUtils.EMPTY_CLASS_ARRAY;
+ }
+ Class[] classes = new Class[array.length];
+ for (int i = 0; i < array.length; i++) {
+ classes[i] = array[i] == null ? null : array[i].getClass();
+ }
+ return classes;
+ }
+
+ // Short canonical name
+ // ----------------------------------------------------------------------
+ /**
+ * Gets the canonical name minus the package name for an Object
.
+ *
+ * @param object the class to get the short name for, may be null
+ * @param valueIfNull the value to return if null
+ * @return the canonical name of the object without the package name, or the null value
+ * @since 2.4
+ */
+ public static String getShortCanonicalName(Object object, String valueIfNull) {
+ if (object == null) {
+ return valueIfNull;
+ }
+ return getShortCanonicalName(object.getClass().getName());
+ }
+
+ /**
+ * Gets the canonical name minus the package name from a Class
.
+ *
+ * @param cls the class to get the short name for.
+ * @return the canonical name without the package name or an empty string
+ * @since 2.4
+ */
+ public static String getShortCanonicalName(Class cls) {
+ if (cls == null) {
+ return StringUtils.EMPTY;
+ }
+ return getShortCanonicalName(cls.getName());
+ }
+
+ /**
+ * Gets the canonical name minus the package name from a String.
+ *
+ * The string passed in is assumed to be a canonical name - it is not checked.
+ *
+ * @param canonicalName the class name to get the short name for
+ * @return the canonical name of the class without the package name or an empty string
+ * @since 2.4
+ */
+ public static String getShortCanonicalName(String canonicalName) {
+ return ClassUtils.getShortClassName(getCanonicalName(canonicalName));
+ }
+
+ // Package name
+ // ----------------------------------------------------------------------
+ /**
+ * Gets the package name from the canonical name of an Object
.
+ *
+ * @param object the class to get the package name for, may be null
+ * @param valueIfNull the value to return if null
+ * @return the package name of the object, or the null value
+ * @since 2.4
+ */
+ public static String getPackageCanonicalName(Object object, String valueIfNull) {
+ if (object == null) {
+ return valueIfNull;
+ }
+ return getPackageCanonicalName(object.getClass().getName());
+ }
+
+ /**
+ * Gets the package name from the canonical name of a Class
.
+ *
+ * @param cls the class to get the package name for, may be null
.
+ * @return the package name or an empty string
+ * @since 2.4
+ */
+ public static String getPackageCanonicalName(Class cls) {
+ if (cls == null) {
+ return StringUtils.EMPTY;
+ }
+ return getPackageCanonicalName(cls.getName());
+ }
+
+ /**
+ * Gets the package name from the canonical name.
+ *
+ * The string passed in is assumed to be a canonical name - it is not checked.
+ * If the class is unpackaged, return an empty string.
+ *
+ * @param canonicalName the canonical name to get the package name for, may be null
+ * @return the package name or an empty string
+ * @since 2.4
+ */
+ public static String getPackageCanonicalName(String canonicalName) {
+ return ClassUtils.getPackageName(getCanonicalName(canonicalName));
+ }
+
+ /**
+ * Converts a given name of class into canonical format.
+ * If name of class is not a name of array class it returns
+ * unchanged name.
+ * Example:
+ *
+ * getCanonicalName("[I") = "int[]"
+ * getCanonicalName("[Ljava.lang.String;") = "java.lang.String[]"
+ * getCanonicalName("java.lang.String") = "java.lang.String"
+ *
+ *
+ *
+ * @param className the name of class
+ * @return canonical form of class name
+ * @since 2.4
+ */
+ private static String getCanonicalName(String className) {
+ className = StringUtils.deleteWhitespace(className);
+ if (className == null) {
+ return null;
+ } else {
+ int dim = 0;
+ while (className.startsWith("[")) {
+ dim++;
+ className = className.substring(1);
+ }
+ if (dim < 1) {
+ return className;
+ } else {
+ if (className.startsWith("L")) {
+ className = className.substring(
+ 1,
+ className.endsWith(";")
+ ? className.length() - 1
+ : className.length());
+ } else {
+ if (className.length() > 0) {
+ className = (String) reverseAbbreviationMap.get(
+ className.substring(0, 1));
+ }
+ }
+ StrBuilder canonicalClassNameBuffer = new StrBuilder(className);
+ for (int i = 0; i < dim; i++) {
+ canonicalClassNameBuffer.append("[]");
+ }
+ return canonicalClassNameBuffer.toString();
+ }
+ }
+ }
}
Index: 3rdParty_sources/commons-lang/org/apache/commons/lang/Entities.java
===================================================================
RCS file: /usr/local/cvsroot/3rdParty_sources/commons-lang/org/apache/commons/lang/Entities.java,v
diff -u -r1.1 -r1.2
--- 3rdParty_sources/commons-lang/org/apache/commons/lang/Entities.java 30 Aug 2012 16:24:42 -0000 1.1
+++ 3rdParty_sources/commons-lang/org/apache/commons/lang/Entities.java 15 Mar 2013 09:52:48 -0000 1.2
@@ -1,123 +1,89 @@
-/* ====================================================================
- * The Apache Software License, Version 1.1
- *
- * Copyright (c) 2002-2003 The Apache Software Foundation. All rights
- * reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in
- * the documentation and/or other materials provided with the
- * distribution.
- *
- * 3. The end-user documentation included with the redistribution, if
- * any, must include the following acknowledgement:
- * "This product includes software developed by the
- * Apache Software Foundation (http://www.apache.org/)."
- * Alternately, this acknowledgement may appear in the software itself,
- * if and wherever such third-party acknowledgements normally appear.
- *
- * 4. The names "The Jakarta Project", "Commons", and "Apache Software
- * Foundation" must not be used to endorse or promote products derived
- * from this software without prior written permission. For written
- * permission, please contact apache@apache.org.
- *
- * 5. Products derived from this software may not be called "Apache"
- * nor may "Apache" appear in their names without prior written
- * permission of the Apache Software Foundation.
- *
- * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
- * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
- * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
- * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- * ====================================================================
- *
- * This software consists of voluntary contributions made by many
- * individuals on behalf of the Apache Software Foundation. For more
- * information on the Apache Software Foundation, please see
- * .
+/*
+ * 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.lang;
+import java.io.IOException;
+import java.io.StringWriter;
+import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
/**
- * Provides HTML and XML entity utilities.
- *
+ *
+ * Provides HTML and XML entity utilities.
+ *
+ *
* @see ISO Entities
- * @see HTML 3.2 Character Entities for ISO Latin-1
- * @see HTML 4.0 Character entity references
- * @see HTML 4.01 Character References
- * @see HTML 4.01 Code positions
- *
+ * @see HTML 3.2 Character Entities for ISO Latin-1
+ * @see HTML 4.0 Character entity references
+ * @see HTML 4.01 Character References
+ * @see HTML 4.01 Code positions
+ *
* @author Alexander Day Chaffee
* @author Gary Gregory
* @since 2.0
* @version $Id$
*/
class Entities {
- private static final String[][] BASIC_ARRAY = {
- {"quot", "34"}, // " - double-quote
+ private static final String[][] BASIC_ARRAY = {{"quot", "34"}, // " - double-quote
{"amp", "38"}, // & - ampersand
{"lt", "60"}, // < - less-than
{"gt", "62"}, // > - greater-than
};
- private static final String[][] APOS_ARRAY = {
- {"apos", "39"}, // XML apostrophe
+ private static final String[][] APOS_ARRAY = {{"apos", "39"}, // XML apostrophe
};
// package scoped for testing
- static final String[][] ISO8859_1_ARRAY = {
- {"nbsp", "160"}, // non-breaking space
- {"iexcl", "161"}, //inverted exclamation mark
- {"cent", "162"}, //cent sign
- {"pound", "163"}, //pound sign
- {"curren", "164"}, //currency sign
- {"yen", "165"}, //yen sign = yuan sign
- {"brvbar", "166"}, //broken bar = broken vertical bar
- {"sect", "167"}, //section sign
- {"uml", "168"}, //diaeresis = spacing diaeresis
+ static final String[][] ISO8859_1_ARRAY = {{"nbsp", "160"}, // non-breaking space
+ {"iexcl", "161"}, // inverted exclamation mark
+ {"cent", "162"}, // cent sign
+ {"pound", "163"}, // pound sign
+ {"curren", "164"}, // currency sign
+ {"yen", "165"}, // yen sign = yuan sign
+ {"brvbar", "166"}, // broken bar = broken vertical bar
+ {"sect", "167"}, // section sign
+ {"uml", "168"}, // diaeresis = spacing diaeresis
{"copy", "169"}, // � - copyright sign
- {"ordf", "170"}, //feminine ordinal indicator
- {"laquo", "171"}, //left-pointing double angle quotation mark = left pointing guillemet
- {"not", "172"}, //not sign
- {"shy", "173"}, //soft hyphen = discretionary hyphen
+ {"ordf", "170"}, // feminine ordinal indicator
+ {"laquo", "171"}, // left-pointing double angle quotation mark = left pointing guillemet
+ {"not", "172"}, // not sign
+ {"shy", "173"}, // soft hyphen = discretionary hyphen
{"reg", "174"}, // � - registered trademark sign
- {"macr", "175"}, //macron = spacing macron = overline = APL overbar
- {"deg", "176"}, //degree sign
- {"plusmn", "177"}, //plus-minus sign = plus-or-minus sign
- {"sup2", "178"}, //superscript two = superscript digit two = squared
- {"sup3", "179"}, //superscript three = superscript digit three = cubed
- {"acute", "180"}, //acute accent = spacing acute
- {"micro", "181"}, //micro sign
- {"para", "182"}, //pilcrow sign = paragraph sign
- {"middot", "183"}, //middle dot = Georgian comma = Greek middle dot
- {"cedil", "184"}, //cedilla = spacing cedilla
- {"sup1", "185"}, //superscript one = superscript digit one
- {"ordm", "186"}, //masculine ordinal indicator
- {"raquo", "187"}, //right-pointing double angle quotation mark = right pointing guillemet
- {"frac14", "188"}, //vulgar fraction one quarter = fraction one quarter
- {"frac12", "189"}, //vulgar fraction one half = fraction one half
- {"frac34", "190"}, //vulgar fraction three quarters = fraction three quarters
- {"iquest", "191"}, //inverted question mark = turned question mark
+ {"macr", "175"}, // macron = spacing macron = overline = APL overbar
+ {"deg", "176"}, // degree sign
+ {"plusmn", "177"}, // plus-minus sign = plus-or-minus sign
+ {"sup2", "178"}, // superscript two = superscript digit two = squared
+ {"sup3", "179"}, // superscript three = superscript digit three = cubed
+ {"acute", "180"}, // acute accent = spacing acute
+ {"micro", "181"}, // micro sign
+ {"para", "182"}, // pilcrow sign = paragraph sign
+ {"middot", "183"}, // middle dot = Georgian comma = Greek middle dot
+ {"cedil", "184"}, // cedilla = spacing cedilla
+ {"sup1", "185"}, // superscript one = superscript digit one
+ {"ordm", "186"}, // masculine ordinal indicator
+ {"raquo", "187"}, // right-pointing double angle quotation mark = right pointing guillemet
+ {"frac14", "188"}, // vulgar fraction one quarter = fraction one quarter
+ {"frac12", "189"}, // vulgar fraction one half = fraction one half
+ {"frac34", "190"}, // vulgar fraction three quarters = fraction three quarters
+ {"iquest", "191"}, // inverted question mark = turned question mark
{"Agrave", "192"}, // � - uppercase A, grave accent
{"Aacute", "193"}, // � - uppercase A, acute accent
{"Acirc", "194"}, // � - uppercase A, circumflex accent
@@ -141,7 +107,7 @@
{"Ocirc", "212"}, // � - uppercase O, circumflex accent
{"Otilde", "213"}, // � - uppercase O, tilde
{"Ouml", "214"}, // � - uppercase O, umlaut
- {"times", "215"}, //multiplication sign
+ {"times", "215"}, // multiplication sign
{"Oslash", "216"}, // � - uppercase O, slash
{"Ugrave", "217"}, // � - uppercase U, grave accent
{"Uacute", "218"}, // � - uppercase U, acute accent
@@ -187,310 +153,422 @@
// http://www.w3.org/TR/REC-html40/sgml/entities.html
// package scoped for testing
static final String[][] HTML40_ARRAY = {
-//
- {"fnof", "402"}, //latin small f with hook = function= florin, U+0192 ISOtech -->
-//
- {"Alpha", "913"}, //greek capital letter alpha, U+0391 -->
- {"Beta", "914"}, //greek capital letter beta, U+0392 -->
- {"Gamma", "915"}, //greek capital letter gamma,U+0393 ISOgrk3 -->
- {"Delta", "916"}, //greek capital letter delta,U+0394 ISOgrk3 -->
- {"Epsilon", "917"}, //greek capital letter epsilon, U+0395 -->
- {"Zeta", "918"}, //greek capital letter zeta, U+0396 -->
- {"Eta", "919"}, //greek capital letter eta, U+0397 -->
- {"Theta", "920"}, //greek capital letter theta,U+0398 ISOgrk3 -->
- {"Iota", "921"}, //greek capital letter iota, U+0399 -->
- {"Kappa", "922"}, //greek capital letter kappa, U+039A -->
- {"Lambda", "923"}, //greek capital letter lambda,U+039B ISOgrk3 -->
- {"Mu", "924"}, //greek capital letter mu, U+039C -->
- {"Nu", "925"}, //greek capital letter nu, U+039D -->
- {"Xi", "926"}, //greek capital letter xi, U+039E ISOgrk3 -->
- {"Omicron", "927"}, //greek capital letter omicron, U+039F -->
- {"Pi", "928"}, //greek capital letter pi, U+03A0 ISOgrk3 -->
- {"Rho", "929"}, //greek capital letter rho, U+03A1 -->
-//
- {"Sigma", "931"}, //greek capital letter sigma,U+03A3 ISOgrk3 -->
- {"Tau", "932"}, //greek capital letter tau, U+03A4 -->
- {"Upsilon", "933"}, //greek capital letter upsilon,U+03A5 ISOgrk3 -->
- {"Phi", "934"}, //greek capital letter phi,U+03A6 ISOgrk3 -->
- {"Chi", "935"}, //greek capital letter chi, U+03A7 -->
- {"Psi", "936"}, //greek capital letter psi,U+03A8 ISOgrk3 -->
- {"Omega", "937"}, //greek capital letter omega,U+03A9 ISOgrk3 -->
- {"alpha", "945"}, //greek small letter alpha,U+03B1 ISOgrk3 -->
- {"beta", "946"}, //greek small letter beta, U+03B2 ISOgrk3 -->
- {"gamma", "947"}, //greek small letter gamma,U+03B3 ISOgrk3 -->
- {"delta", "948"}, //greek small letter delta,U+03B4 ISOgrk3 -->
- {"epsilon", "949"}, //greek small letter epsilon,U+03B5 ISOgrk3 -->
- {"zeta", "950"}, //greek small letter zeta, U+03B6 ISOgrk3 -->
- {"eta", "951"}, //greek small letter eta, U+03B7 ISOgrk3 -->
- {"theta", "952"}, //greek small letter theta,U+03B8 ISOgrk3 -->
- {"iota", "953"}, //greek small letter iota, U+03B9 ISOgrk3 -->
- {"kappa", "954"}, //greek small letter kappa,U+03BA ISOgrk3 -->
- {"lambda", "955"}, //greek small letter lambda,U+03BB ISOgrk3 -->
- {"mu", "956"}, //greek small letter mu, U+03BC ISOgrk3 -->
- {"nu", "957"}, //greek small letter nu, U+03BD ISOgrk3 -->
- {"xi", "958"}, //greek small letter xi, U+03BE ISOgrk3 -->
- {"omicron", "959"}, //greek small letter omicron, U+03BF NEW -->
- {"pi", "960"}, //greek small letter pi, U+03C0 ISOgrk3 -->
- {"rho", "961"}, //greek small letter rho, U+03C1 ISOgrk3 -->
- {"sigmaf", "962"}, //greek small letter final sigma,U+03C2 ISOgrk3 -->
- {"sigma", "963"}, //greek small letter sigma,U+03C3 ISOgrk3 -->
- {"tau", "964"}, //greek small letter tau, U+03C4 ISOgrk3 -->
- {"upsilon", "965"}, //greek small letter upsilon,U+03C5 ISOgrk3 -->
- {"phi", "966"}, //greek small letter phi, U+03C6 ISOgrk3 -->
- {"chi", "967"}, //greek small letter chi, U+03C7 ISOgrk3 -->
- {"psi", "968"}, //greek small letter psi, U+03C8 ISOgrk3 -->
- {"omega", "969"}, //greek small letter omega,U+03C9 ISOgrk3 -->
- {"thetasym", "977"}, //greek small letter theta symbol,U+03D1 NEW -->
- {"upsih", "978"}, //greek upsilon with hook symbol,U+03D2 NEW -->
- {"piv", "982"}, //greek pi symbol, U+03D6 ISOgrk3 -->
-//
- {"bull", "8226"}, //bullet = black small circle,U+2022 ISOpub -->
-//
- {"hellip", "8230"}, //horizontal ellipsis = three dot leader,U+2026 ISOpub -->
- {"prime", "8242"}, //prime = minutes = feet, U+2032 ISOtech -->
- {"Prime", "8243"}, //double prime = seconds = inches,U+2033 ISOtech -->
- {"oline", "8254"}, //overline = spacing overscore,U+203E NEW -->
- {"frasl", "8260"}, //fraction slash, U+2044 NEW -->
-//
- {"weierp", "8472"}, //script capital P = power set= Weierstrass p, U+2118 ISOamso -->
- {"image", "8465"}, //blackletter capital I = imaginary part,U+2111 ISOamso -->
- {"real", "8476"}, //blackletter capital R = real part symbol,U+211C ISOamso -->
- {"trade", "8482"}, //trade mark sign, U+2122 ISOnum -->
- {"alefsym", "8501"}, //alef symbol = first transfinite cardinal,U+2135 NEW -->
-//
-//
- {"larr", "8592"}, //leftwards arrow, U+2190 ISOnum -->
- {"uarr", "8593"}, //upwards arrow, U+2191 ISOnum-->
- {"rarr", "8594"}, //rightwards arrow, U+2192 ISOnum -->
- {"darr", "8595"}, //downwards arrow, U+2193 ISOnum -->
- {"harr", "8596"}, //left right arrow, U+2194 ISOamsa -->
- {"crarr", "8629"}, //downwards arrow with corner leftwards= carriage return, U+21B5 NEW -->
- {"lArr", "8656"}, //leftwards double arrow, U+21D0 ISOtech -->
-//
- {"uArr", "8657"}, //upwards double arrow, U+21D1 ISOamsa -->
- {"rArr", "8658"}, //rightwards double arrow,U+21D2 ISOtech -->
-//
- {"dArr", "8659"}, //downwards double arrow, U+21D3 ISOamsa -->
- {"hArr", "8660"}, //left right double arrow,U+21D4 ISOamsa -->
-//
- {"forall", "8704"}, //for all, U+2200 ISOtech -->
- {"part", "8706"}, //partial differential, U+2202 ISOtech -->
- {"exist", "8707"}, //there exists, U+2203 ISOtech -->
- {"empty", "8709"}, //empty set = null set = diameter,U+2205 ISOamso -->
- {"nabla", "8711"}, //nabla = backward difference,U+2207 ISOtech -->
- {"isin", "8712"}, //element of, U+2208 ISOtech -->
- {"notin", "8713"}, //not an element of, U+2209 ISOtech -->
- {"ni", "8715"}, //contains as member, U+220B ISOtech -->
-//
- {"prod", "8719"}, //n-ary product = product sign,U+220F ISOamsb -->
-//
- {"sum", "8721"}, //n-ary sumation, U+2211 ISOamsb -->
-//
- {"minus", "8722"}, //minus sign, U+2212 ISOtech -->
- {"lowast", "8727"}, //asterisk operator, U+2217 ISOtech -->
- {"radic", "8730"}, //square root = radical sign,U+221A ISOtech -->
- {"prop", "8733"}, //proportional to, U+221D ISOtech -->
- {"infin", "8734"}, //infinity, U+221E ISOtech -->
- {"ang", "8736"}, //angle, U+2220 ISOamso -->
- {"and", "8743"}, //logical and = wedge, U+2227 ISOtech -->
- {"or", "8744"}, //logical or = vee, U+2228 ISOtech -->
- {"cap", "8745"}, //intersection = cap, U+2229 ISOtech -->
- {"cup", "8746"}, //union = cup, U+222A ISOtech -->
- {"int", "8747"}, //integral, U+222B ISOtech -->
- {"there4", "8756"}, //therefore, U+2234 ISOtech -->
- {"sim", "8764"}, //tilde operator = varies with = similar to,U+223C ISOtech -->
-//
- {"cong", "8773"}, //approximately equal to, U+2245 ISOtech -->
- {"asymp", "8776"}, //almost equal to = asymptotic to,U+2248 ISOamsr -->
- {"ne", "8800"}, //not equal to, U+2260 ISOtech -->
- {"equiv", "8801"}, //identical to, U+2261 ISOtech -->
- {"le", "8804"}, //less-than or equal to, U+2264 ISOtech -->
- {"ge", "8805"}, //greater-than or equal to,U+2265 ISOtech -->
- {"sub", "8834"}, //subset of, U+2282 ISOtech -->
- {"sup", "8835"}, //superset of, U+2283 ISOtech -->
-//
- {"sube", "8838"}, //subset of or equal to, U+2286 ISOtech -->
- {"supe", "8839"}, //superset of or equal to,U+2287 ISOtech -->
- {"oplus", "8853"}, //circled plus = direct sum,U+2295 ISOamsb -->
- {"otimes", "8855"}, //circled times = vector product,U+2297 ISOamsb -->
- {"perp", "8869"}, //up tack = orthogonal to = perpendicular,U+22A5 ISOtech -->
- {"sdot", "8901"}, //dot operator, U+22C5 ISOamsb -->
-//
-//
- {"lceil", "8968"}, //left ceiling = apl upstile,U+2308 ISOamsc -->
- {"rceil", "8969"}, //right ceiling, U+2309 ISOamsc -->
- {"lfloor", "8970"}, //left floor = apl downstile,U+230A ISOamsc -->
- {"rfloor", "8971"}, //right floor, U+230B ISOamsc -->
- {"lang", "9001"}, //left-pointing angle bracket = bra,U+2329 ISOtech -->
-//
- {"rang", "9002"}, //right-pointing angle bracket = ket,U+232A ISOtech -->
-//
-//
- {"loz", "9674"}, //lozenge, U+25CA ISOpub -->
-//
- {"spades", "9824"}, //black spade suit, U+2660 ISOpub -->
-//
- {"clubs", "9827"}, //black club suit = shamrock,U+2663 ISOpub -->
- {"hearts", "9829"}, //black heart suit = valentine,U+2665 ISOpub -->
- {"diams", "9830"}, //black diamond suit, U+2666 ISOpub -->
+ //
+ {"fnof", "402"}, // latin small f with hook = function= florin, U+0192 ISOtech -->
+ //
+ {"Alpha", "913"}, // greek capital letter alpha, U+0391 -->
+ {"Beta", "914"}, // greek capital letter beta, U+0392 -->
+ {"Gamma", "915"}, // greek capital letter gamma,U+0393 ISOgrk3 -->
+ {"Delta", "916"}, // greek capital letter delta,U+0394 ISOgrk3 -->
+ {"Epsilon", "917"}, // greek capital letter epsilon, U+0395 -->
+ {"Zeta", "918"}, // greek capital letter zeta, U+0396 -->
+ {"Eta", "919"}, // greek capital letter eta, U+0397 -->
+ {"Theta", "920"}, // greek capital letter theta,U+0398 ISOgrk3 -->
+ {"Iota", "921"}, // greek capital letter iota, U+0399 -->
+ {"Kappa", "922"}, // greek capital letter kappa, U+039A -->
+ {"Lambda", "923"}, // greek capital letter lambda,U+039B ISOgrk3 -->
+ {"Mu", "924"}, // greek capital letter mu, U+039C -->
+ {"Nu", "925"}, // greek capital letter nu, U+039D -->
+ {"Xi", "926"}, // greek capital letter xi, U+039E ISOgrk3 -->
+ {"Omicron", "927"}, // greek capital letter omicron, U+039F -->
+ {"Pi", "928"}, // greek capital letter pi, U+03A0 ISOgrk3 -->
+ {"Rho", "929"}, // greek capital letter rho, U+03A1 -->
+ //
+ {"Sigma", "931"}, // greek capital letter sigma,U+03A3 ISOgrk3 -->
+ {"Tau", "932"}, // greek capital letter tau, U+03A4 -->
+ {"Upsilon", "933"}, // greek capital letter upsilon,U+03A5 ISOgrk3 -->
+ {"Phi", "934"}, // greek capital letter phi,U+03A6 ISOgrk3 -->
+ {"Chi", "935"}, // greek capital letter chi, U+03A7 -->
+ {"Psi", "936"}, // greek capital letter psi,U+03A8 ISOgrk3 -->
+ {"Omega", "937"}, // greek capital letter omega,U+03A9 ISOgrk3 -->
+ {"alpha", "945"}, // greek small letter alpha,U+03B1 ISOgrk3 -->
+ {"beta", "946"}, // greek small letter beta, U+03B2 ISOgrk3 -->
+ {"gamma", "947"}, // greek small letter gamma,U+03B3 ISOgrk3 -->
+ {"delta", "948"}, // greek small letter delta,U+03B4 ISOgrk3 -->
+ {"epsilon", "949"}, // greek small letter epsilon,U+03B5 ISOgrk3 -->
+ {"zeta", "950"}, // greek small letter zeta, U+03B6 ISOgrk3 -->
+ {"eta", "951"}, // greek small letter eta, U+03B7 ISOgrk3 -->
+ {"theta", "952"}, // greek small letter theta,U+03B8 ISOgrk3 -->
+ {"iota", "953"}, // greek small letter iota, U+03B9 ISOgrk3 -->
+ {"kappa", "954"}, // greek small letter kappa,U+03BA ISOgrk3 -->
+ {"lambda", "955"}, // greek small letter lambda,U+03BB ISOgrk3 -->
+ {"mu", "956"}, // greek small letter mu, U+03BC ISOgrk3 -->
+ {"nu", "957"}, // greek small letter nu, U+03BD ISOgrk3 -->
+ {"xi", "958"}, // greek small letter xi, U+03BE ISOgrk3 -->
+ {"omicron", "959"}, // greek small letter omicron, U+03BF NEW -->
+ {"pi", "960"}, // greek small letter pi, U+03C0 ISOgrk3 -->
+ {"rho", "961"}, // greek small letter rho, U+03C1 ISOgrk3 -->
+ {"sigmaf", "962"}, // greek small letter final sigma,U+03C2 ISOgrk3 -->
+ {"sigma", "963"}, // greek small letter sigma,U+03C3 ISOgrk3 -->
+ {"tau", "964"}, // greek small letter tau, U+03C4 ISOgrk3 -->
+ {"upsilon", "965"}, // greek small letter upsilon,U+03C5 ISOgrk3 -->
+ {"phi", "966"}, // greek small letter phi, U+03C6 ISOgrk3 -->
+ {"chi", "967"}, // greek small letter chi, U+03C7 ISOgrk3 -->
+ {"psi", "968"}, // greek small letter psi, U+03C8 ISOgrk3 -->
+ {"omega", "969"}, // greek small letter omega,U+03C9 ISOgrk3 -->
+ {"thetasym", "977"}, // greek small letter theta symbol,U+03D1 NEW -->
+ {"upsih", "978"}, // greek upsilon with hook symbol,U+03D2 NEW -->
+ {"piv", "982"}, // greek pi symbol, U+03D6 ISOgrk3 -->
+ //
+ {"bull", "8226"}, // bullet = black small circle,U+2022 ISOpub -->
+ //
+ {"hellip", "8230"}, // horizontal ellipsis = three dot leader,U+2026 ISOpub -->
+ {"prime", "8242"}, // prime = minutes = feet, U+2032 ISOtech -->
+ {"Prime", "8243"}, // double prime = seconds = inches,U+2033 ISOtech -->
+ {"oline", "8254"}, // overline = spacing overscore,U+203E NEW -->
+ {"frasl", "8260"}, // fraction slash, U+2044 NEW -->
+ //
+ {"weierp", "8472"}, // script capital P = power set= Weierstrass p, U+2118 ISOamso -->
+ {"image", "8465"}, // blackletter capital I = imaginary part,U+2111 ISOamso -->
+ {"real", "8476"}, // blackletter capital R = real part symbol,U+211C ISOamso -->
+ {"trade", "8482"}, // trade mark sign, U+2122 ISOnum -->
+ {"alefsym", "8501"}, // alef symbol = first transfinite cardinal,U+2135 NEW -->
+ //
+ //
+ {"larr", "8592"}, // leftwards arrow, U+2190 ISOnum -->
+ {"uarr", "8593"}, // upwards arrow, U+2191 ISOnum-->
+ {"rarr", "8594"}, // rightwards arrow, U+2192 ISOnum -->
+ {"darr", "8595"}, // downwards arrow, U+2193 ISOnum -->
+ {"harr", "8596"}, // left right arrow, U+2194 ISOamsa -->
+ {"crarr", "8629"}, // downwards arrow with corner leftwards= carriage return, U+21B5 NEW -->
+ {"lArr", "8656"}, // leftwards double arrow, U+21D0 ISOtech -->
+ //
+ {"uArr", "8657"}, // upwards double arrow, U+21D1 ISOamsa -->
+ {"rArr", "8658"}, // rightwards double arrow,U+21D2 ISOtech -->
+ //
+ {"dArr", "8659"}, // downwards double arrow, U+21D3 ISOamsa -->
+ {"hArr", "8660"}, // left right double arrow,U+21D4 ISOamsa -->
+ //
+ {"forall", "8704"}, // for all, U+2200 ISOtech -->
+ {"part", "8706"}, // partial differential, U+2202 ISOtech -->
+ {"exist", "8707"}, // there exists, U+2203 ISOtech -->
+ {"empty", "8709"}, // empty set = null set = diameter,U+2205 ISOamso -->
+ {"nabla", "8711"}, // nabla = backward difference,U+2207 ISOtech -->
+ {"isin", "8712"}, // element of, U+2208 ISOtech -->
+ {"notin", "8713"}, // not an element of, U+2209 ISOtech -->
+ {"ni", "8715"}, // contains as member, U+220B ISOtech -->
+ //
+ {"prod", "8719"}, // n-ary product = product sign,U+220F ISOamsb -->
+ //
+ {"sum", "8721"}, // n-ary summation, U+2211 ISOamsb -->
+ //
+ {"minus", "8722"}, // minus sign, U+2212 ISOtech -->
+ {"lowast", "8727"}, // asterisk operator, U+2217 ISOtech -->
+ {"radic", "8730"}, // square root = radical sign,U+221A ISOtech -->
+ {"prop", "8733"}, // proportional to, U+221D ISOtech -->
+ {"infin", "8734"}, // infinity, U+221E ISOtech -->
+ {"ang", "8736"}, // angle, U+2220 ISOamso -->
+ {"and", "8743"}, // logical and = wedge, U+2227 ISOtech -->
+ {"or", "8744"}, // logical or = vee, U+2228 ISOtech -->
+ {"cap", "8745"}, // intersection = cap, U+2229 ISOtech -->
+ {"cup", "8746"}, // union = cup, U+222A ISOtech -->
+ {"int", "8747"}, // integral, U+222B ISOtech -->
+ {"there4", "8756"}, // therefore, U+2234 ISOtech -->
+ {"sim", "8764"}, // tilde operator = varies with = similar to,U+223C ISOtech -->
+ //
+ {"cong", "8773"}, // approximately equal to, U+2245 ISOtech -->
+ {"asymp", "8776"}, // almost equal to = asymptotic to,U+2248 ISOamsr -->
+ {"ne", "8800"}, // not equal to, U+2260 ISOtech -->
+ {"equiv", "8801"}, // identical to, U+2261 ISOtech -->
+ {"le", "8804"}, // less-than or equal to, U+2264 ISOtech -->
+ {"ge", "8805"}, // greater-than or equal to,U+2265 ISOtech -->
+ {"sub", "8834"}, // subset of, U+2282 ISOtech -->
+ {"sup", "8835"}, // superset of, U+2283 ISOtech -->
+ //
+ {"sube", "8838"}, // subset of or equal to, U+2286 ISOtech -->
+ {"supe", "8839"}, // superset of or equal to,U+2287 ISOtech -->
+ {"oplus", "8853"}, // circled plus = direct sum,U+2295 ISOamsb -->
+ {"otimes", "8855"}, // circled times = vector product,U+2297 ISOamsb -->
+ {"perp", "8869"}, // up tack = orthogonal to = perpendicular,U+22A5 ISOtech -->
+ {"sdot", "8901"}, // dot operator, U+22C5 ISOamsb -->
+ //
+ //
+ {"lceil", "8968"}, // left ceiling = apl upstile,U+2308 ISOamsc -->
+ {"rceil", "8969"}, // right ceiling, U+2309 ISOamsc -->
+ {"lfloor", "8970"}, // left floor = apl downstile,U+230A ISOamsc -->
+ {"rfloor", "8971"}, // right floor, U+230B ISOamsc -->
+ {"lang", "9001"}, // left-pointing angle bracket = bra,U+2329 ISOtech -->
+ //
+ {"rang", "9002"}, // right-pointing angle bracket = ket,U+232A ISOtech -->
+ //
+ //
+ {"loz", "9674"}, // lozenge, U+25CA ISOpub -->
+ //
+ {"spades", "9824"}, // black spade suit, U+2660 ISOpub -->
+ //
+ {"clubs", "9827"}, // black club suit = shamrock,U+2663 ISOpub -->
+ {"hearts", "9829"}, // black heart suit = valentine,U+2665 ISOpub -->
+ {"diams", "9830"}, // black diamond suit, U+2666 ISOpub -->
-//
- {"OElig", "338"}, // -- latin capital ligature OE,U+0152 ISOlat2 -->
- {"oelig", "339"}, // -- latin small ligature oe, U+0153 ISOlat2 -->
-//
- {"Scaron", "352"}, // -- latin capital letter S with caron,U+0160 ISOlat2 -->
- {"scaron", "353"}, // -- latin small letter s with caron,U+0161 ISOlat2 -->
- {"Yuml", "376"}, // -- latin capital letter Y with diaeresis,U+0178 ISOlat2 -->
-//
- {"circ", "710"}, // -- modifier letter circumflex accent,U+02C6 ISOpub -->
- {"tilde", "732"}, //small tilde, U+02DC ISOdia -->
-//
- {"ensp", "8194"}, //en space, U+2002 ISOpub -->
- {"emsp", "8195"}, //em space, U+2003 ISOpub -->
- {"thinsp", "8201"}, //thin space, U+2009 ISOpub -->
- {"zwnj", "8204"}, //zero width non-joiner,U+200C NEW RFC 2070 -->
- {"zwj", "8205"}, //zero width joiner, U+200D NEW RFC 2070 -->
- {"lrm", "8206"}, //left-to-right mark, U+200E NEW RFC 2070 -->
- {"rlm", "8207"}, //right-to-left mark, U+200F NEW RFC 2070 -->
- {"ndash", "8211"}, //en dash, U+2013 ISOpub -->
- {"mdash", "8212"}, //em dash, U+2014 ISOpub -->
- {"lsquo", "8216"}, //left single quotation mark,U+2018 ISOnum -->
- {"rsquo", "8217"}, //right single quotation mark,U+2019 ISOnum -->
- {"sbquo", "8218"}, //single low-9 quotation mark, U+201A NEW -->
- {"ldquo", "8220"}, //left double quotation mark,U+201C ISOnum -->
- {"rdquo", "8221"}, //right double quotation mark,U+201D ISOnum -->
- {"bdquo", "8222"}, //double low-9 quotation mark, U+201E NEW -->
- {"dagger", "8224"}, //dagger, U+2020 ISOpub -->
- {"Dagger", "8225"}, //double dagger, U+2021 ISOpub -->
- {"permil", "8240"}, //per mille sign, U+2030 ISOtech -->
- {"lsaquo", "8249"}, //single left-pointing angle quotation mark,U+2039 ISO proposed -->
-//
- {"rsaquo", "8250"}, //single right-pointing angle quotation mark,U+203A ISO proposed -->
-//
- {"euro", "8364"}, // -- euro sign, U+20AC NEW -->
+ //
+ {"OElig", "338"}, // -- latin capital ligature OE,U+0152 ISOlat2 -->
+ {"oelig", "339"}, // -- latin small ligature oe, U+0153 ISOlat2 -->
+ //
+ {"Scaron", "352"}, // -- latin capital letter S with caron,U+0160 ISOlat2 -->
+ {"scaron", "353"}, // -- latin small letter s with caron,U+0161 ISOlat2 -->
+ {"Yuml", "376"}, // -- latin capital letter Y with diaeresis,U+0178 ISOlat2 -->
+ //
+ {"circ", "710"}, // -- modifier letter circumflex accent,U+02C6 ISOpub -->
+ {"tilde", "732"}, // small tilde, U+02DC ISOdia -->
+ //
+ {"ensp", "8194"}, // en space, U+2002 ISOpub -->
+ {"emsp", "8195"}, // em space, U+2003 ISOpub -->
+ {"thinsp", "8201"}, // thin space, U+2009 ISOpub -->
+ {"zwnj", "8204"}, // zero width non-joiner,U+200C NEW RFC 2070 -->
+ {"zwj", "8205"}, // zero width joiner, U+200D NEW RFC 2070 -->
+ {"lrm", "8206"}, // left-to-right mark, U+200E NEW RFC 2070 -->
+ {"rlm", "8207"}, // right-to-left mark, U+200F NEW RFC 2070 -->
+ {"ndash", "8211"}, // en dash, U+2013 ISOpub -->
+ {"mdash", "8212"}, // em dash, U+2014 ISOpub -->
+ {"lsquo", "8216"}, // left single quotation mark,U+2018 ISOnum -->
+ {"rsquo", "8217"}, // right single quotation mark,U+2019 ISOnum -->
+ {"sbquo", "8218"}, // single low-9 quotation mark, U+201A NEW -->
+ {"ldquo", "8220"}, // left double quotation mark,U+201C ISOnum -->
+ {"rdquo", "8221"}, // right double quotation mark,U+201D ISOnum -->
+ {"bdquo", "8222"}, // double low-9 quotation mark, U+201E NEW -->
+ {"dagger", "8224"}, // dagger, U+2020 ISOpub -->
+ {"Dagger", "8225"}, // double dagger, U+2021 ISOpub -->
+ {"permil", "8240"}, // per mille sign, U+2030 ISOtech -->
+ {"lsaquo", "8249"}, // single left-pointing angle quotation mark,U+2039 ISO proposed -->
+ //
+ {"rsaquo", "8250"}, // single right-pointing angle quotation mark,U+203A ISO proposed -->
+ //
+ {"euro", "8364"}, // -- euro sign, U+20AC NEW -->
};
/**
- * The set of entities supported by standard XML.
+ *
+ * The set of entities supported by standard XML.
+ *
*/
public static final Entities XML;
/**
- * The set of entities supported by HTML 3.2.
+ *
+ * The set of entities supported by HTML 3.2.
+ *
*/
public static final Entities HTML32;
/**
- * The set of entities supported by HTML 4.0.
+ *
+ * The set of entities supported by HTML 4.0.
+ *
*/
public static final Entities HTML40;
static {
- XML = new Entities();
- XML.addEntities(BASIC_ARRAY);
- XML.addEntities(APOS_ARRAY);
+ Entities xml = new Entities();
+ xml.addEntities(BASIC_ARRAY);
+ xml.addEntities(APOS_ARRAY);
+ XML = xml;
}
static {
- HTML32 = new Entities();
- HTML32.addEntities(BASIC_ARRAY);
- HTML32.addEntities(ISO8859_1_ARRAY);
+ Entities html32 = new Entities();
+ html32.addEntities(BASIC_ARRAY);
+ html32.addEntities(ISO8859_1_ARRAY);
+ HTML32 = html32;
}
static {
- HTML40 = new Entities();
- fillWithHtml40Entities(HTML40);
+ Entities html40 = new Entities();
+ fillWithHtml40Entities(html40);
+ HTML40 = html40;
}
+ /**
+ *
+ * Fills the specified entities instance with HTML 40 entities.
+ *
+ *
+ * @param entities
+ * the instance to be filled.
+ */
static void fillWithHtml40Entities(Entities entities) {
entities.addEntities(BASIC_ARRAY);
entities.addEntities(ISO8859_1_ARRAY);
entities.addEntities(HTML40_ARRAY);
}
static interface EntityMap {
+ /**
+ *
+ * Add an entry to this entity map.
+ *
+ *
+ * @param name
+ * the entity name
+ * @param value
+ * the entity value
+ */
void add(String name, int value);
+ /**
+ *
+ * Returns the name of the entity identified by the specified value.
+ *
+ *
+ * @param value
+ * the value to locate
+ * @return entity name associated with the specified value
+ */
String name(int value);
+ /**
+ *
+ * Returns the value of the entity identified by the specified name.
+ *
+ *
+ * @param name
+ * the name to locate
+ * @return entity value associated with the specified name
+ */
int value(String name);
}
static class PrimitiveEntityMap implements EntityMap {
- private Map mapNameToValue = new HashMap();
- private IntHashMap mapValueToName = new IntHashMap();
+ private final Map mapNameToValue = new HashMap();
+ private final IntHashMap mapValueToName = new IntHashMap();
+
+ /**
+ * {@inheritDoc}
+ */
+ // TODO not thread-safe as there is a window between changing the two maps
public void add(String name, int value) {
mapNameToValue.put(name, new Integer(value));
mapValueToName.put(value, name);
}
+ /**
+ * {@inheritDoc}
+ */
public String name(int value) {
return (String) mapValueToName.get(value);
}
+ /**
+ * {@inheritDoc}
+ */
public int value(String name) {
Object value = mapNameToValue.get(name);
- if (value == null)
+ if (value == null) {
return -1;
+ }
return ((Integer) value).intValue();
}
}
-
static abstract class MapIntMap implements Entities.EntityMap {
- protected Map mapNameToValue;
- protected Map mapValueToName;
+ protected final Map mapNameToValue;
+ protected final Map mapValueToName;
+
+ /**
+ * Construct a new instance with specified maps.
+ *
+ * @param nameToValue name to value map
+ * @param valueToName value to namee map
+ */
+ MapIntMap(Map nameToValue, Map valueToName){
+ mapNameToValue = nameToValue;
+ mapValueToName = valueToName;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
public void add(String name, int value) {
mapNameToValue.put(name, new Integer(value));
mapValueToName.put(new Integer(value), name);
}
+ /**
+ * {@inheritDoc}
+ */
public String name(int value) {
return (String) mapValueToName.get(new Integer(value));
}
+ /**
+ * {@inheritDoc}
+ */
public int value(String name) {
Object value = mapNameToValue.get(name);
- if (value == null)
+ if (value == null) {
return -1;
+ }
return ((Integer) value).intValue();
}
}
static class HashEntityMap extends MapIntMap {
+ /**
+ * Constructs a new instance of HashEntityMap
.
+ */
public HashEntityMap() {
- mapNameToValue = new HashMap();
- mapValueToName = new HashMap();
+ super(new HashMap(), new HashMap());
}
}
static class TreeEntityMap extends MapIntMap {
+ /**
+ * Constructs a new instance of TreeEntityMap
.
+ */
public TreeEntityMap() {
- mapNameToValue = new TreeMap();
- mapValueToName = new TreeMap();
+ super(new TreeMap(), new TreeMap());
}
}
static class LookupEntityMap extends PrimitiveEntityMap {
+ // TODO this class is not thread-safe
private String[] lookupTable;
- private int LOOKUP_TABLE_SIZE = 256;
+ private static final int LOOKUP_TABLE_SIZE = 256;
+
+ /**
+ * {@inheritDoc}
+ */
public String name(int value) {
if (value < LOOKUP_TABLE_SIZE) {
return lookupTable()[value];
}
return super.name(value);
}
+ /**
+ *
+ * Returns the lookup table for this entity map. The lookup table is created if it has not been previously.
+ *
+ *
+ * @return the lookup table
+ */
private String[] lookupTable() {
if (lookupTable == null) {
createLookupTable();
}
return lookupTable;
}
+ /**
+ *
+ * Creates an entity lookup table of LOOKUP_TABLE_SIZE elements, initialized with entity names.
+ *
+ */
private void createLookupTable() {
lookupTable = new String[LOOKUP_TABLE_SIZE];
for (int i = 0; i < LOOKUP_TABLE_SIZE; ++i) {
@@ -500,29 +578,53 @@
}
static class ArrayEntityMap implements EntityMap {
- protected int growBy = 100;
+ // TODO this class is not thread-safe
+ protected final int growBy;
+
protected int size = 0;
+
protected String[] names;
+
protected int[] values;
+ /**
+ * Constructs a new instance of ArrayEntityMap
.
+ */
public ArrayEntityMap() {
+ this.growBy = 100;
names = new String[growBy];
values = new int[growBy];
}
+ /**
+ * Constructs a new instance of ArrayEntityMap
specifying the size by which the array should
+ * grow.
+ *
+ * @param growBy
+ * array will be initialized to and will grow by this amount
+ */
public ArrayEntityMap(int growBy) {
this.growBy = growBy;
names = new String[growBy];
values = new int[growBy];
}
+ /**
+ * {@inheritDoc}
+ */
public void add(String name, int value) {
ensureCapacity(size + 1);
names[size] = name;
values[size] = value;
size++;
}
+ /**
+ * Verifies the capacity of the entity array, adjusting the size if necessary.
+ *
+ * @param capacity
+ * size the array should be
+ */
protected void ensureCapacity(int capacity) {
if (capacity > names.length) {
int newSize = Math.max(capacity, size + growBy);
@@ -535,6 +637,9 @@
}
}
+ /**
+ * {@inheritDoc}
+ */
public String name(int value) {
for (int i = 0; i < size; ++i) {
if (values[i] == value) {
@@ -544,6 +649,9 @@
return null;
}
+ /**
+ * {@inheritDoc}
+ */
public int value(String name) {
for (int i = 0; i < size; ++i) {
if (names[i].equals(name)) {
@@ -556,147 +664,360 @@
static class BinaryEntityMap extends ArrayEntityMap {
+ // TODO - not thread-safe, because parent is not. Also references size.
+
+ /**
+ * Constructs a new instance of BinaryEntityMap
.
+ */
public BinaryEntityMap() {
+ super();
}
+ /**
+ * Constructs a new instance of ArrayEntityMap
specifying the size by which the underlying array
+ * should grow.
+ *
+ * @param growBy
+ * array will be initialized to and will grow by this amount
+ */
public BinaryEntityMap(int growBy) {
super(growBy);
}
- // based on code in java.util.Arrays
+ /**
+ * Performs a binary search of the entity array for the specified key. This method is based on code in
+ * {@link java.util.Arrays}.
+ *
+ * @param key
+ * the key to be found
+ * @return the index of the entity array matching the specified key
+ */
private int binarySearch(int key) {
int low = 0;
int high = size - 1;
while (low <= high) {
- int mid = (low + high) >> 1;
+ int mid = (low + high) >>> 1;
int midVal = values[mid];
- if (midVal < key)
+ if (midVal < key) {
low = mid + 1;
- else if (midVal > key)
+ } else if (midVal > key) {
high = mid - 1;
- else
+ } else {
return mid; // key found
+ }
}
- return -(low + 1); // key not found.
+ return -(low + 1); // key not found.
}
+ /**
+ * {@inheritDoc}
+ */
public void add(String name, int value) {
ensureCapacity(size + 1);
int insertAt = binarySearch(value);
- if (insertAt > 0) return; // note: this means you can't insert the same value twice
- insertAt = -(insertAt + 1); // binarySearch returns it negative and off-by-one
+ if (insertAt > 0) {
+ return; // note: this means you can't insert the same value twice
+ }
+ insertAt = -(insertAt + 1); // binarySearch returns it negative and off-by-one
System.arraycopy(values, insertAt, values, insertAt + 1, size - insertAt);
values[insertAt] = value;
System.arraycopy(names, insertAt, names, insertAt + 1, size - insertAt);
names[insertAt] = name;
size++;
}
+ /**
+ * {@inheritDoc}
+ */
public String name(int value) {
int index = binarySearch(value);
- if (index < 0) return null;
+ if (index < 0) {
+ return null;
+ }
return names[index];
}
}
- // package scoped for testing
- EntityMap map = new Entities.LookupEntityMap();
+ private final EntityMap map;
+ /**
+ * Default constructor.
+ */
+ public Entities(){
+ map = new Entities.LookupEntityMap();
+ }
+
+ /**
+ * package scoped constructor for testing.
+ *
+ * @param emap entity map.
+ */
+ Entities(EntityMap emap){
+ map = emap;
+ }
+
+ /**
+ *
+ * Adds entities to this entity.
+ *
+ *
+ * @param entityArray
+ * array of entities to be added
+ */
public void addEntities(String[][] entityArray) {
for (int i = 0; i < entityArray.length; ++i) {
addEntity(entityArray[i][0], Integer.parseInt(entityArray[i][1]));
}
}
+ /**
+ *
+ * Add an entity to this entity.
+ *
+ *
+ * @param name
+ * name of the entity
+ * @param value
+ * vale of the entity
+ */
public void addEntity(String name, int value) {
map.add(name, value);
}
+ /**
+ *
+ * Returns the name of the entity identified by the specified value.
+ *
+ *
+ * @param value
+ * the value to locate
+ * @return entity name associated with the specified value
+ */
public String entityName(int value) {
return map.name(value);
}
-
+ /**
+ *
+ * Returns the value of the entity identified by the specified name.
+ *
+ *
+ * @param name
+ * the name to locate
+ * @return entity value associated with the specified name
+ */
public int entityValue(String name) {
return map.value(name);
}
/**
- * Escapes the characters in a String
.
- *
- * For example, if you have called addEntity("foo", 0xA1),
- * escape("\u00A1") will return "&foo;"
- *
- * @param str The String
to escape.
+ *
+ * Escapes the characters in a String
.
+ *
+ *
+ *
+ * For example, if you have called addEntity("foo", 0xA1), escape("\u00A1") will return
+ * "&foo;"
+ *
+ *
+ * @param str
+ * The String
to escape.
* @return A new escaped String
.
*/
public String escape(String str) {
- //todo: rewrite to use a Writer
- StringBuffer buf = new StringBuffer(str.length() * 2);
- int i;
- for (i = 0; i < str.length(); ++i) {
- char ch = str.charAt(i);
- String entityName = this.entityName(ch);
+ StringWriter stringWriter = createStringWriter(str);
+ try {
+ this.escape(stringWriter, str);
+ } catch (IOException e) {
+ // This should never happen because ALL the StringWriter methods called by #escape(Writer, String) do not
+ // throw IOExceptions.
+ throw new UnhandledException(e);
+ }
+ return stringWriter.toString();
+ }
+
+ /**
+ *
+ * Escapes the characters in the String
passed and writes the result to the Writer
+ * passed.
+ *
+ *
+ * @param writer
+ * The Writer
to write the results of the escaping to. Assumed to be a non-null value.
+ * @param str
+ * The String
to escape. Assumed to be a non-null value.
+ * @throws IOException
+ * when Writer
passed throws the exception from calls to the {@link Writer#write(int)}
+ * methods.
+ *
+ * @see #escape(String)
+ * @see Writer
+ */
+ public void escape(Writer writer, String str) throws IOException {
+ int len = str.length();
+ for (int i = 0; i < len; i++) {
+ char c = str.charAt(i);
+ String entityName = this.entityName(c);
if (entityName == null) {
- if (ch > 0x7F) {
- int intValue = ch;
- buf.append("");
- buf.append(intValue);
- buf.append(';');
+ if (c > 0x7F) {
+ writer.write("");
+ writer.write(Integer.toString(c, 10));
+ writer.write(';');
} else {
- buf.append(ch);
+ writer.write(c);
}
} else {
- buf.append('&');
- buf.append(entityName);
- buf.append(';');
+ writer.write('&');
+ writer.write(entityName);
+ writer.write(';');
}
}
- return buf.toString();
}
/**
- * Unescapes the entities in a String
.
- *
- * For example, if you have called addEntity("foo", 0xA1),
- * unescape("&foo;") will return "\u00A1"
- *
- * @param str The String
to escape.
+ *
+ * Unescapes the entities in a String
.
+ *
+ *
+ *
+ * For example, if you have called addEntity("foo", 0xA1), unescape("&foo;") will return
+ * "\u00A1"
+ *
+ *
+ * @param str
+ * The String
to escape.
* @return A new escaped String
.
*/
public String unescape(String str) {
- StringBuffer buf = new StringBuffer(str.length());
- int i;
- for (i = 0; i < str.length(); ++i) {
- char ch = str.charAt(i);
- if (ch == '&') {
- int semi = str.indexOf(';', i + 1);
- if (semi == -1) {
- buf.append(ch);
+ int firstAmp = str.indexOf('&');
+ if (firstAmp < 0) {
+ return str;
+ } else {
+ StringWriter stringWriter = createStringWriter(str);
+ try {
+ this.doUnescape(stringWriter, str, firstAmp);
+ } catch (IOException e) {
+ // This should never happen because ALL the StringWriter methods called by #escape(Writer, String)
+ // do not throw IOExceptions.
+ throw new UnhandledException(e);
+ }
+ return stringWriter.toString();
+ }
+ }
+
+ /**
+ * Make the StringWriter 10% larger than the source String to avoid growing the writer
+ *
+ * @param str The source string
+ * @return A newly created StringWriter
+ */
+ private StringWriter createStringWriter(String str) {
+ return new StringWriter((int) (str.length() + (str.length() * 0.1)));
+ }
+
+ /**
+ *
+ * Unescapes the escaped entities in the String
passed and writes the result to the
+ * Writer
passed.
+ *
+ *
+ * @param writer
+ * The Writer
to write the results to; assumed to be non-null.
+ * @param str
+ * The source String
to unescape; assumed to be non-null.
+ * @throws IOException
+ * when Writer
passed throws the exception from calls to the {@link Writer#write(int)}
+ * methods.
+ *
+ * @see #escape(String)
+ * @see Writer
+ */
+ public void unescape(Writer writer, String str) throws IOException {
+ int firstAmp = str.indexOf('&');
+ if (firstAmp < 0) {
+ writer.write(str);
+ return;
+ } else {
+ doUnescape(writer, str, firstAmp);
+ }
+ }
+
+ /**
+ * Underlying unescape method that allows the optimisation of not starting from the 0 index again.
+ *
+ * @param writer
+ * The Writer
to write the results to; assumed to be non-null.
+ * @param str
+ * The source String
to unescape; assumed to be non-null.
+ * @param firstAmp
+ * The int
index of the first ampersand in the source String.
+ * @throws IOException
+ * when Writer
passed throws the exception from calls to the {@link Writer#write(int)}
+ * methods.
+ */
+ private void doUnescape(Writer writer, String str, int firstAmp) throws IOException {
+ writer.write(str, 0, firstAmp);
+ int len = str.length();
+ for (int i = firstAmp; i < len; i++) {
+ char c = str.charAt(i);
+ if (c == '&') {
+ int nextIdx = i + 1;
+ int semiColonIdx = str.indexOf(';', nextIdx);
+ if (semiColonIdx == -1) {
+ writer.write(c);
continue;
}
- String entityName = str.substring(i + 1, semi);
- int entityValue;
- if (entityName.charAt(0) == '#') {
- entityValue = Integer.parseInt(entityName.substring(1));
- } else {
- entityValue = this.entityValue(entityName);
+ int amphersandIdx = str.indexOf('&', i + 1);
+ if (amphersandIdx != -1 && amphersandIdx < semiColonIdx) {
+ // Then the text looks like &...&...;
+ writer.write(c);
+ continue;
}
+ String entityContent = str.substring(nextIdx, semiColonIdx);
+ int entityValue = -1;
+ int entityContentLen = entityContent.length();
+ if (entityContentLen > 0) {
+ if (entityContent.charAt(0) == '#') { // escaped value content is an integer (decimal or
+ // hexidecimal)
+ if (entityContentLen > 1) {
+ char isHexChar = entityContent.charAt(1);
+ try {
+ switch (isHexChar) {
+ case 'X' :
+ case 'x' : {
+ entityValue = Integer.parseInt(entityContent.substring(2), 16);
+ break;
+ }
+ default : {
+ entityValue = Integer.parseInt(entityContent.substring(1), 10);
+ }
+ }
+ if (entityValue > 0xFFFF) {
+ entityValue = -1;
+ }
+ } catch (NumberFormatException e) {
+ entityValue = -1;
+ }
+ }
+ } else { // escaped value content is an entity name
+ entityValue = this.entityValue(entityContent);
+ }
+ }
+
if (entityValue == -1) {
- buf.append('&');
- buf.append(entityName);
- buf.append(';');
+ writer.write('&');
+ writer.write(entityContent);
+ writer.write(';');
} else {
- buf.append((char) (entityValue));
+ writer.write(entityValue);
}
- i = semi;
+ i = semiColonIdx; // move index up to the semi-colon
} else {
- buf.append(ch);
+ writer.write(c);
}
}
- return buf.toString();
}
}
Index: 3rdParty_sources/commons-lang/org/apache/commons/lang/IllegalClassException.java
===================================================================
RCS file: /usr/local/cvsroot/3rdParty_sources/commons-lang/org/apache/commons/lang/IllegalClassException.java,v
diff -u -r1.1 -r1.2
--- 3rdParty_sources/commons-lang/org/apache/commons/lang/IllegalClassException.java 30 Aug 2012 16:24:42 -0000 1.1
+++ 3rdParty_sources/commons-lang/org/apache/commons/lang/IllegalClassException.java 15 Mar 2013 09:52:49 -0000 1.2
@@ -1,61 +1,42 @@
-/* ====================================================================
- * The Apache Software License, Version 1.1
- *
- * Copyright (c) 2002-2003 The Apache Software Foundation. All rights
- * reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in
- * the documentation and/or other materials provided with the
- * distribution.
- *
- * 3. The end-user documentation included with the redistribution, if
- * any, must include the following acknowledgement:
- * "This product includes software developed by the
- * Apache Software Foundation (http://www.apache.org/)."
- * Alternately, this acknowledgement may appear in the software itself,
- * if and wherever such third-party acknowledgements normally appear.
- *
- * 4. The names "The Jakarta Project", "Commons", and "Apache Software
- * Foundation" must not be used to endorse or promote products derived
- * from this software without prior written permission. For written
- * permission, please contact apache@apache.org.
- *
- * 5. Products derived from this software may not be called "Apache"
- * nor may "Apache" appear in their names without prior written
- * permission of the Apache Software Foundation.
- *
- * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
- * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
- * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
- * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- * ====================================================================
- *
- * This software consists of voluntary contributions made by many
- * individuals on behalf of the Apache Software Foundation. For more
- * information on the Apache Software Foundation, please see
- * .
+/*
+ * 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.lang;
/**
- * Thrown when an object is an instance of an unexpected type (a class or interface).
+ * Thrown when an object is an instance of an unexpected type (a class or interface).
+ * This exception supplements the standard IllegalArgumentException
+ * by providing a more semantically rich description of the problem.
*
+ * IllegalClassException
represents the case where a method takes
+ * in a genericly typed parameter like Object (typically because it has to due to some
+ * other interface it implements), but this implementation only actually accepts a specific
+ * type, for example String. This exception would be used in place of
+ * IllegalArgumentException
, yet it still extends it.
+ *
+ *
+ * public void foo(Object obj) {
+ * if (obj instanceof String == false) {
+ * throw new IllegalClassException(String.class, obj);
+ * }
+ * // do something with the string
+ * }
+ *
+ *
+ * @author Apache Software Foundation
* @author Matthew Hawthorne
* @author Gary Gregory
* @since 2.0
@@ -64,9 +45,31 @@
public class IllegalClassException extends IllegalArgumentException {
/**
- * Instantiates with the specified types (classes or interfaces).
+ * Required for serialization support.
*
+ * @see java.io.Serializable
+ */
+ private static final long serialVersionUID = 8063272569377254819L;
+
+ /**
+ * Instantiates with the expected type, and actual object.
+ *
* @param expected the expected type
+ * @param actual the actual object
+ * @since 2.1
+ */
+ public IllegalClassException(Class expected, Object actual) {
+ super(
+ "Expected: "
+ + safeGetClassName(expected)
+ + ", actual: "
+ + (actual == null ? "null" : actual.getClass().getName()));
+ }
+
+ /**
+ * Instantiates with the expected and actual types.
+ *
+ * @param expected the expected type
* @param actual the actual type
*/
public IllegalClassException(Class expected, Class actual) {
Index: 3rdParty_sources/commons-lang/org/apache/commons/lang/IncompleteArgumentException.java
===================================================================
RCS file: /usr/local/cvsroot/3rdParty_sources/commons-lang/org/apache/commons/lang/IncompleteArgumentException.java,v
diff -u -r1.1 -r1.2
--- 3rdParty_sources/commons-lang/org/apache/commons/lang/IncompleteArgumentException.java 30 Aug 2012 16:24:42 -0000 1.1
+++ 3rdParty_sources/commons-lang/org/apache/commons/lang/IncompleteArgumentException.java 15 Mar 2013 09:52:49 -0000 1.2
@@ -1,70 +1,60 @@
-/* ====================================================================
- * The Apache Software License, Version 1.1
- *
- * Copyright (c) 2002-2003 The Apache Software Foundation. All rights
- * reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in
- * the documentation and/or other materials provided with the
- * distribution.
- *
- * 3. The end-user documentation included with the redistribution, if
- * any, must include the following acknowledgement:
- * "This product includes software developed by the
- * Apache Software Foundation (http://www.apache.org/)."
- * Alternately, this acknowledgement may appear in the software itself,
- * if and wherever such third-party acknowledgements normally appear.
- *
- * 4. The names "The Jakarta Project", "Commons", and "Apache Software
- * Foundation" must not be used to endorse or promote products derived
- * from this software without prior written permission. For written
- * permission, please contact apache@apache.org.
- *
- * 5. Products derived from this software may not be called "Apache"
- * nor may "Apache" appear in their names without prior written
- * permission of the Apache Software Foundation.
- *
- * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
- * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
- * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
- * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- * ====================================================================
- *
- * This software consists of voluntary contributions made by many
- * individuals on behalf of the Apache Software Foundation. For more
- * information on the Apache Software Foundation, please see
- * .
+/*
+ * 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.lang;
import java.util.Arrays;
/**
- * Thrown to indicate an incomplete argument to a method.
+ * Thrown to indicate an incomplete argument to a method.
+ * This exception supplements the standard IllegalArgumentException
+ * by providing a more semantically rich description of the problem.
*
+ * IncompleteArgumentException
represents the case where a method takes
+ * in a parameter that has a number of properties, some of which have not been set.
+ * A case might be a search requirements bean that must have three properties set
+ * in order for the method to run, but only one is actually set.
+ * This exception would be used in place of
+ * IllegalArgumentException
, yet it still extends it.
+ *
+ *
+ * public void foo(PersonSearcher search) {
+ * if (search.getSurname() == null ||
+ * search.getForename() == null ||
+ * search.getSex() == null) {
+ * throw new IncompleteArgumentException("search");
+ * }
+ * // do something with the searcher
+ * }
+ *
+ *
* @author Matthew Hawthorne
* @since 2.0
* @version $Id$
*/
public class IncompleteArgumentException extends IllegalArgumentException {
/**
+ * Required for serialization support.
+ *
+ * @see java.io.Serializable
+ */
+ private static final long serialVersionUID = 4954193403612068178L;
+
+ /**
* Instantiates with the specified description.
*
* @param argName a description of the incomplete argument
@@ -87,7 +77,7 @@
}
/**
- * 7Converts an array to a string without throwing an exception.
+ * Converts an array to a string without throwing an exception.
*
* @param array an array
* @return the array as a string
Index: 3rdParty_sources/commons-lang/org/apache/commons/lang/IntHashMap.java
===================================================================
RCS file: /usr/local/cvsroot/3rdParty_sources/commons-lang/org/apache/commons/lang/IntHashMap.java,v
diff -u -r1.1 -r1.2
--- 3rdParty_sources/commons-lang/org/apache/commons/lang/IntHashMap.java 30 Aug 2012 16:24:42 -0000 1.1
+++ 3rdParty_sources/commons-lang/org/apache/commons/lang/IntHashMap.java 15 Mar 2013 09:52:48 -0000 1.2
@@ -1,55 +1,18 @@
-/* ====================================================================
- * The Apache Software License, Version 1.1
- *
- * Copyright (c) 2002-2003 The Apache Software Foundation. All rights
- * reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in
- * the documentation and/or other materials provided with the
- * distribution.
- *
- * 3. The end-user documentation included with the redistribution, if
- * any, must include the following acknowledgement:
- * "This product includes software developed by the
- * Apache Software Foundation (http://www.apache.org/)."
- * Alternately, this acknowledgement may appear in the software itself,
- * if and wherever such third-party acknowledgements normally appear.
- *
- * 4. The names "The Jakarta Project", "Commons", and "Apache Software
- * Foundation" must not be used to endorse or promote products derived
- * from this software without prior written permission. For written
- * permission, please contact apache@apache.org.
- *
- * 5. Products derived from this software may not be called "Apache"
- * nor may "Apache" appear in their names without prior written
- * permission of the Apache Software Foundation.
- *
- * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
- * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
- * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
- * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- * ====================================================================
- *
- * This software consists of voluntary contributions made by many
- * individuals on behalf of the Apache Software Foundation. For more
- * information on the Apache Software Foundation, please see
- * .
+/*
+ * 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.
*/
/*
@@ -62,12 +25,12 @@
* A hash map that uses primitive ints for the key rather than objects.
*
* Note that this class is for internal optimization purposes only, and may
- * not be supported in future releases of Jakarta Commons Lang. Utilities of
- * this sort may be included in future releases of Jakarta Commons Collections.
+ * not be supported in future releases of Apache Commons Lang. Utilities of
+ * this sort may be included in future releases of Apache Commons Collections.
*
+ * @author Apache Software Foundation
* @author Justin Couch
* @author Alex Chaffee (alex@apache.org)
- * @author Stephen Colebourne
* @since 2.0
* @version $Revision$
* @see java.util.HashMap
@@ -97,15 +60,15 @@
*
* @serial
*/
- private float loadFactor;
+ private final float loadFactor;
/**
* Innerclass that acts as a datastructure to create a new entry in the
* table.
*/
private static class Entry {
- int hash;
- int key;
+ final int hash;
+ final int key; // TODO not read; seems to be always same as hash
Object value;
Entry next;
@@ -232,6 +195,7 @@
* (which predates the Map interface).
*
* @param value value whose presence in this HashMap is to be tested.
+ * @return boolean true
if the value is contained
* @see java.util.Map
* @since JDK1.2
*/
Index: 3rdParty_sources/commons-lang/org/apache/commons/lang/LocaleUtils.java
===================================================================
RCS file: /usr/local/cvsroot/3rdParty_sources/commons-lang/org/apache/commons/lang/LocaleUtils.java,v
diff -u
--- /dev/null 1 Jan 1970 00:00:00 -0000
+++ 3rdParty_sources/commons-lang/org/apache/commons/lang/LocaleUtils.java 15 Mar 2013 09:52:48 -0000 1.1
@@ -0,0 +1,316 @@
+/*
+ * 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.lang;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * Operations to assist when working with a {@link Locale}.
+ *
+ * This class tries to handle null
input gracefully.
+ * An exception will not be thrown for a null
input.
+ * Each method documents its behaviour in more detail.
+ *
+ * @author Apache Software Foundation
+ * @since 2.2
+ * @version $Id: LocaleUtils.java,v 1.1 2013/03/15 09:52:48 andreyb Exp $
+ */
+public class LocaleUtils {
+
+ /** Unmodifiable list of available locales. */
+ private static List cAvailableLocaleList; // lazily created by availableLocaleList()
+
+ /** Unmodifiable set of available locales. */
+ private static Set cAvailableLocaleSet; // lazily created by availableLocaleSet()
+
+ /** Unmodifiable map of language locales by country. */
+ private static final Map cLanguagesByCountry = Collections.synchronizedMap(new HashMap());
+
+ /** Unmodifiable map of country locales by language. */
+ private static final Map cCountriesByLanguage = Collections.synchronizedMap(new HashMap());
+
+ /**
+ * LocaleUtils
instances should NOT be constructed in standard programming.
+ * Instead, the class should be used as LocaleUtils.toLocale("en_GB");
.
+ *
+ * This constructor is public to permit tools that require a JavaBean instance
+ * to operate.
+ */
+ public LocaleUtils() {
+ super();
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Converts a String to a Locale.
+ *
+ * This method takes the string format of a locale and creates the
+ * locale object from it.
+ *
+ *
+ * LocaleUtils.toLocale("en") = new Locale("en", "")
+ * LocaleUtils.toLocale("en_GB") = new Locale("en", "GB")
+ * LocaleUtils.toLocale("en_GB_xxx") = new Locale("en", "GB", "xxx") (#)
+ *
+ *
+ * (#) The behaviour 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.
+ *
+ * This method validates the input strictly.
+ * The language code must be lowercase.
+ * The country code must be uppercase.
+ * The separator must be an underscore.
+ * The length must be correct.
+ *
+ *
+ * @param str the locale String to convert, null returns null
+ * @return a Locale, null if null input
+ * @throws IllegalArgumentException if the string is an invalid format
+ */
+ public static Locale toLocale(String str) {
+ if (str == null) {
+ return null;
+ }
+ int len = str.length();
+ if (len != 2 && len != 5 && len < 7) {
+ throw new IllegalArgumentException("Invalid locale format: " + str);
+ }
+ char ch0 = str.charAt(0);
+ char ch1 = str.charAt(1);
+ if (ch0 < 'a' || ch0 > 'z' || ch1 < 'a' || ch1 > 'z') {
+ throw new IllegalArgumentException("Invalid locale format: " + str);
+ }
+ if (len == 2) {
+ return new Locale(str, "");
+ } else {
+ if (str.charAt(2) != '_') {
+ throw new IllegalArgumentException("Invalid locale format: " + str);
+ }
+ char ch3 = str.charAt(3);
+ if (ch3 == '_') {
+ return new Locale(str.substring(0, 2), "", str.substring(4));
+ }
+ char ch4 = str.charAt(4);
+ if (ch3 < 'A' || ch3 > 'Z' || ch4 < 'A' || ch4 > 'Z') {
+ throw new IllegalArgumentException("Invalid locale format: " + str);
+ }
+ if (len == 5) {
+ return new Locale(str.substring(0, 2), str.substring(3, 5));
+ } else {
+ if (str.charAt(5) != '_') {
+ throw new IllegalArgumentException("Invalid locale format: " + str);
+ }
+ return new Locale(str.substring(0, 2), str.substring(3, 5), str.substring(6));
+ }
+ }
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Obtains the list of locales to search through when performing
+ * a locale search.
+ *
+ *
+ * localeLookupList(Locale("fr","CA","xxx"))
+ * = [Locale("fr","CA","xxx"), Locale("fr","CA"), Locale("fr")]
+ *
+ *
+ * @param locale the locale to start from
+ * @return the unmodifiable list of Locale objects, 0 being locale, never null
+ */
+ public static List localeLookupList(Locale locale) {
+ return localeLookupList(locale, locale);
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Obtains the list of locales to search through when performing
+ * a locale search.
+ *
+ *
+ * localeLookupList(Locale("fr", "CA", "xxx"), Locale("en"))
+ * = [Locale("fr","CA","xxx"), Locale("fr","CA"), Locale("fr"), Locale("en"]
+ *
+ *
+ * The result list begins with the most specific locale, then the
+ * next more general and so on, finishing with the default locale.
+ * The list will never contain the same locale twice.
+ *
+ * @param locale the locale to start from, null returns empty list
+ * @param defaultLocale the default locale to use if no other is found
+ * @return the unmodifiable list of Locale objects, 0 being locale, never null
+ */
+ public static List localeLookupList(Locale locale, Locale defaultLocale) {
+ List list = new ArrayList(4);
+ if (locale != null) {
+ list.add(locale);
+ if (locale.getVariant().length() > 0) {
+ list.add(new Locale(locale.getLanguage(), locale.getCountry()));
+ }
+ if (locale.getCountry().length() > 0) {
+ list.add(new Locale(locale.getLanguage(), ""));
+ }
+ if (list.contains(defaultLocale) == false) {
+ list.add(defaultLocale);
+ }
+ }
+ return Collections.unmodifiableList(list);
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Obtains an unmodifiable list of installed locales.
+ *
+ * This method is a wrapper around {@link Locale#getAvailableLocales()}.
+ * It is more efficient, as the JDK method must create a new array each
+ * time it is called.
+ *
+ * @return the unmodifiable list of available locales
+ */
+ public static List availableLocaleList() {
+ if(cAvailableLocaleList == null) {
+ initAvailableLocaleList();
+ }
+ return cAvailableLocaleList;
+ }
+
+ /**
+ * Initializes the availableLocaleList. It is separate from availableLocaleList()
+ * to avoid the synchronized block affecting normal use, yet synchronized and
+ * lazy loading to avoid a static block affecting other methods in this class.
+ */
+ private static synchronized void initAvailableLocaleList() {
+ if(cAvailableLocaleList == null) {
+ List list = Arrays.asList(Locale.getAvailableLocales());
+ cAvailableLocaleList = Collections.unmodifiableList(list);
+ }
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Obtains an unmodifiable set of installed locales.
+ *
+ * This method is a wrapper around {@link Locale#getAvailableLocales()}.
+ * It is more efficient, as the JDK method must create a new array each
+ * time it is called.
+ *
+ * @return the unmodifiable set of available locales
+ */
+ public static Set availableLocaleSet() {
+ if(cAvailableLocaleSet == null) {
+ initAvailableLocaleSet();
+ }
+ return cAvailableLocaleSet;
+ }
+
+ /**
+ * Initializes the availableLocaleSet. It is separate from availableLocaleSet()
+ * to avoid the synchronized block affecting normal use, yet synchronized and
+ * lazy loading to avoid a static block affecting other methods in this class.
+ */
+ private static synchronized void initAvailableLocaleSet() {
+ if(cAvailableLocaleSet == null) {
+ cAvailableLocaleSet = Collections.unmodifiableSet( new HashSet(availableLocaleList()) );
+ }
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Checks if the locale specified is in the list of available locales.
+ *
+ * @param locale the Locale object to check if it is available
+ * @return true if the locale is a known locale
+ */
+ public static boolean isAvailableLocale(Locale locale) {
+ return availableLocaleList().contains(locale);
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Obtains the list of languages supported for a given country.
+ *
+ * This method takes a country code and searches to find the
+ * languages available for that country. Variant locales are removed.
+ *
+ * @param countryCode the 2 letter country code, null returns empty
+ * @return an unmodifiable List of Locale objects, never null
+ */
+ public static List languagesByCountry(String countryCode) {
+ List langs = (List) cLanguagesByCountry.get(countryCode); //syncd
+ if (langs == null) {
+ if (countryCode != null) {
+ langs = new ArrayList();
+ List locales = availableLocaleList();
+ for (int i = 0; i < locales.size(); i++) {
+ Locale locale = (Locale) locales.get(i);
+ if (countryCode.equals(locale.getCountry()) &&
+ locale.getVariant().length() == 0) {
+ langs.add(locale);
+ }
+ }
+ langs = Collections.unmodifiableList(langs);
+ } else {
+ langs = Collections.EMPTY_LIST;
+ }
+ cLanguagesByCountry.put(countryCode, langs); //syncd
+ }
+ return langs;
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Obtains the list of countries supported for a given language.
+ *
+ * This method takes a language code and searches to find the
+ * countries available for that language. Variant locales are removed.
+ *
+ * @param languageCode the 2 letter language code, null returns empty
+ * @return an unmodifiable List of Locale objects, never null
+ */
+ public static List countriesByLanguage(String languageCode) {
+ List countries = (List) cCountriesByLanguage.get(languageCode); //syncd
+ if (countries == null) {
+ if (languageCode != null) {
+ countries = new ArrayList();
+ List locales = availableLocaleList();
+ for (int i = 0; i < locales.size(); i++) {
+ Locale locale = (Locale) locales.get(i);
+ if (languageCode.equals(locale.getLanguage()) &&
+ locale.getCountry().length() != 0 &&
+ locale.getVariant().length() == 0) {
+ countries.add(locale);
+ }
+ }
+ countries = Collections.unmodifiableList(countries);
+ } else {
+ countries = Collections.EMPTY_LIST;
+ }
+ cCountriesByLanguage.put(languageCode, countries); //syncd
+ }
+ return countries;
+ }
+
+}
Index: 3rdParty_sources/commons-lang/org/apache/commons/lang/NotImplementedException.java
===================================================================
RCS file: /usr/local/cvsroot/3rdParty_sources/commons-lang/org/apache/commons/lang/NotImplementedException.java,v
diff -u -r1.1 -r1.2
--- 3rdParty_sources/commons-lang/org/apache/commons/lang/NotImplementedException.java 30 Aug 2012 16:24:42 -0000 1.1
+++ 3rdParty_sources/commons-lang/org/apache/commons/lang/NotImplementedException.java 15 Mar 2013 09:52:48 -0000 1.2
@@ -1,85 +1,295 @@
-/* ====================================================================
- * The Apache Software License, Version 1.1
- *
- * Copyright (c) 2002-2003 The Apache Software Foundation. All rights
- * reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in
- * the documentation and/or other materials provided with the
- * distribution.
- *
- * 3. The end-user documentation included with the redistribution, if
- * any, must include the following acknowledgement:
- * "This product includes software developed by the
- * Apache Software Foundation (http://www.apache.org/)."
- * Alternately, this acknowledgement may appear in the software itself,
- * if and wherever such third-party acknowledgements normally appear.
- *
- * 4. The names "The Jakarta Project", "Commons", and "Apache Software
- * Foundation" must not be used to endorse or promote products derived
- * from this software without prior written permission. For written
- * permission, please contact apache@apache.org.
- *
- * 5. Products derived from this software may not be called "Apache"
- * nor may "Apache" appear in their names without prior written
- * permission of the Apache Software Foundation.
- *
- * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
- * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
- * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
- * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- * ====================================================================
- *
- * This software consists of voluntary contributions made by many
- * individuals on behalf of the Apache Software Foundation. For more
- * information on the Apache Software Foundation, please see
- * .
+/*
+ * 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.lang;
+import java.io.PrintStream;
+import java.io.PrintWriter;
+
+import org.apache.commons.lang.exception.Nestable;
+import org.apache.commons.lang.exception.NestableDelegate;
+
/**
- * Thrown to indicate that a method has not been implemented.
+ * Thrown to indicate that a block of code has not been implemented.
+ * This exception supplements UnsupportedOperationException
+ * by providing a more semantically rich description of the problem.
*
+ * NotImplementedException
represents the case where the
+ * author has yet to implement the logic at this point in the program.
+ * This can act as an exception based TODO tag.
+ * Because this logic might be within a catch block, this exception
+ * suports exception chaining.
+ *
+ *
+ * public void foo() {
+ * try {
+ * // do something that throws an Exception
+ * } catch (Exception ex) {
+ * // don't know what to do here yet
+ * throw new NotImplementedException("TODO", ex);
+ * }
+ * }
+ *
+ *
+ * @author Apache Software Foundation
* @author Matthew Hawthorne
* @since 2.0
* @version $Id$
*/
-public class NotImplementedException extends UnsupportedOperationException {
+public class NotImplementedException
+ extends UnsupportedOperationException implements Nestable {
+ private static final String DEFAULT_MESSAGE = "Code is not implemented";
+
/**
- * Constructes the exception with the specified class.
+ * Required for serialization support.
*
- * @param clazz the Class
that has not implemented the method
+ * @see java.io.Serializable
*/
+ private static final long serialVersionUID = -6894122266938754088L;
+
+ /**
+ * The exception helper to delegate nested exception handling to.
+ */
+ private NestableDelegate delegate = new NestableDelegate(this);
+
+ /**
+ * Holds the reference to the exception or error that caused
+ * this exception to be thrown.
+ */
+ private Throwable cause;
+
+ //-----------------------------------------------------------------------
+ /**
+ * Constructs a new NotImplementedException
with default message.
+ *
+ * @since 2.1
+ */
+ public NotImplementedException() {
+ super(DEFAULT_MESSAGE);
+ }
+
+ /**
+ * Constructs a new NotImplementedException
with specified
+ * detail message.
+ *
+ * @param msg the error message.
+ */
+ public NotImplementedException(String msg) {
+ super(msg == null ? DEFAULT_MESSAGE : msg);
+ }
+
+ /**
+ * Constructs a new NotImplementedException
with specified
+ * nested Throwable
and default message.
+ *
+ * @param cause the exception that caused this exception to be thrown
+ * @since 2.1
+ */
+ public NotImplementedException(Throwable cause) {
+ super(DEFAULT_MESSAGE);
+ this.cause = cause;
+ }
+
+ /**
+ * Constructs a new NotImplementedException
with specified
+ * detail message and nested Throwable
.
+ *
+ * @param msg the error message
+ * @param cause the exception that caused this exception to be thrown
+ * @since 2.1
+ */
+ public NotImplementedException(String msg, Throwable cause) {
+ super(msg == null ? DEFAULT_MESSAGE : msg);
+ this.cause = cause;
+ }
+
+ /**
+ * Constructs a new NotImplementedException
referencing the specified class.
+ *
+ * @param clazz
+ * the Class
that has not implemented the method
+ */
public NotImplementedException(Class clazz) {
- super(
- "Method is not implemented in class "
- + ((clazz == null) ? null : clazz.getName()));
+ super(clazz == null ? DEFAULT_MESSAGE : DEFAULT_MESSAGE + " in " + clazz);
}
+ // -----------------------------------------------------------------------
/**
- * Constructs the exception with the specified message.
+ * Gets the root cause of this exception.
+ * @return the root cause of this exception.
*
- * @param msg the exception message.
+ * @since 2.1
*/
- public NotImplementedException(String msg) {
- super(msg);
+ public Throwable getCause() {
+ return cause;
}
+ /**
+ * Gets the combined the error message of this and any nested errors.
+ *
+ * @return the error message
+ * @since 2.1
+ */
+ public String getMessage() {
+ if (super.getMessage() != null) {
+ return super.getMessage();
+ } else if (cause != null) {
+ return cause.toString();
+ } else {
+ return null;
+ }
+ }
+
+ /**
+ * Returns the error message of the Throwable
in the chain
+ * of Throwable
s at the specified index, numbered from 0.
+ *
+ * @param index the index of the Throwable
in the chain
+ * @return the error message, or null if the Throwable
at the
+ * specified index in the chain does not contain a message
+ * @throws IndexOutOfBoundsException if the index
argument is
+ * negative or not less than the count of Throwable
s in the chain
+ * @since 2.1
+ */
+ public String getMessage(int index) {
+ if (index == 0) {
+ return super.getMessage();
+ }
+ return delegate.getMessage(index);
+ }
+
+ /**
+ * Returns the error message of this and any nested Throwable
objects.
+ * Each throwable returns a message, a null string is included in the array if
+ * there is no message for a particular Throwable
.
+ *
+ * @return the error messages
+ * @since 2.1
+ */
+ public String[] getMessages() {
+ return delegate.getMessages();
+ }
+
+ /**
+ * Returns the Throwable
in the chain by index.
+ *
+ * @param index the index to retrieve
+ * @return the Throwable
+ * @throws IndexOutOfBoundsException if the index
argument is
+ * negative or not less than the count of Throwable
s in the chain
+ * @since 2.1
+ */
+ public Throwable getThrowable(int index) {
+ return delegate.getThrowable(index);
+ }
+
+ /**
+ * Returns the number of nested Throwable
s represented by
+ * this Nestable
, including this Nestable
.
+ *
+ * @return the throwable count
+ * @since 2.1
+ */
+ public int getThrowableCount() {
+ return delegate.getThrowableCount();
+ }
+
+ /**
+ * Returns this Nestable
and any nested Throwable
s
+ * in an array of Throwable
s, one element for each
+ * Throwable
.
+ *
+ * @return the Throwable
s
+ * @since 2.1
+ */
+ public Throwable[] getThrowables() {
+ return delegate.getThrowables();
+ }
+
+ /**
+ * Returns the index of the first occurrence of the specified type.
+ * If there is no match, -1
is returned.
+ *
+ * @param type the type to search for
+ * @return index of the first occurrence of the type in the chain, or -1 if
+ * the type is not found
+ * @since 2.1
+ */
+ public int indexOfThrowable(Class type) {
+ return delegate.indexOfThrowable(type, 0);
+ }
+
+ /**
+ * Returns the index of the first occurrence of the specified type starting
+ * from the specified index. If there is no match, -1
is returned.
+ *
+ * @param type the type to search for
+ * @param fromIndex the index of the starting position in the chain to be searched
+ * @return index of the first occurrence of the type in the chain, or -1 if
+ * the type is not found
+ * @throws IndexOutOfBoundsException if the fromIndex
argument
+ * is negative or not less than the count of Throwable
s in the chain
+ * @since 2.1
+ */
+ public int indexOfThrowable(Class type, int fromIndex) {
+ return delegate.indexOfThrowable(type, fromIndex);
+ }
+
+ /**
+ * Prints the stack trace of this exception.
+ * Includes information from the exception, if any, which caused this exception.
+ *
+ * @since 2.1
+ */
+ public void printStackTrace() {
+ delegate.printStackTrace();
+ }
+
+ /**
+ * Prints the stack trace of this exception to the specified stream.
+ * Includes information from the exception, if any, which caused this exception.
+ *
+ * @param out the stream to write to
+ * @since 2.1
+ */
+ public void printStackTrace(PrintStream out) {
+ delegate.printStackTrace(out);
+ }
+
+ /**
+ * Prints the stack trace of this exception to the specified writer.
+ * Includes information from the exception, if any, which caused this exception.
+ *
+ * @param out the writer to write to
+ * @since 2.1
+ */
+ public void printStackTrace(PrintWriter out) {
+ delegate.printStackTrace(out);
+ }
+
+ /**
+ * Prints the stack trace for this exception only (root cause not included)
+ * using the specified writer.
+ *
+ * @param out the writer to write to
+ * @since 2.1
+ */
+ public final void printPartialStackTrace(PrintWriter out) {
+ super.printStackTrace(out);
+ }
+
}
Index: 3rdParty_sources/commons-lang/org/apache/commons/lang/NullArgumentException.java
===================================================================
RCS file: /usr/local/cvsroot/3rdParty_sources/commons-lang/org/apache/commons/lang/NullArgumentException.java,v
diff -u -r1.1 -r1.2
--- 3rdParty_sources/commons-lang/org/apache/commons/lang/NullArgumentException.java 30 Aug 2012 16:24:42 -0000 1.1
+++ 3rdParty_sources/commons-lang/org/apache/commons/lang/NullArgumentException.java 15 Mar 2013 09:52:48 -0000 1.2
@@ -1,76 +1,64 @@
-/* ====================================================================
- * The Apache Software License, Version 1.1
- *
- * Copyright (c) 2002-2003 The Apache Software Foundation. All rights
- * reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in
- * the documentation and/or other materials provided with the
- * distribution.
- *
- * 3. The end-user documentation included with the redistribution, if
- * any, must include the following acknowledgement:
- * "This product includes software developed by the
- * Apache Software Foundation (http://www.apache.org/)."
- * Alternately, this acknowledgement may appear in the software itself,
- * if and wherever such third-party acknowledgements normally appear.
- *
- * 4. The names "The Jakarta Project", "Commons", and "Apache Software
- * Foundation" must not be used to endorse or promote products derived
- * from this software without prior written permission. For written
- * permission, please contact apache@apache.org.
- *
- * 5. Products derived from this software may not be called "Apache"
- * nor may "Apache" appear in their names without prior written
- * permission of the Apache Software Foundation.
- *
- * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
- * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
- * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
- * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- * ====================================================================
- *
- * This software consists of voluntary contributions made by many
- * individuals on behalf of the Apache Software Foundation. For more
- * information on the Apache Software Foundation, please see
- * .
+/*
+ * 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.lang;
/**
* Thrown to indicate that an argument was null
and should
- * not have been.
+ * not have been.
+ * This exception supplements the standard IllegalArgumentException
+ * by providing a more semantically rich description of the problem.
*
+ * NullArgumentException
represents the case where a method takes
+ * in a parameter that must not be null
.
+ * Some coding standards would use NullPointerException
for this case,
+ * others will use IllegalArgumentException
.
+ * Thus this exception would be used in place of
+ * IllegalArgumentException
, yet it still extends it.
+ *
+ *
+ * public void foo(String str) {
+ * if (str == null) {
+ * throw new NullArgumentException("str");
+ * }
+ * // do something with the string
+ * }
+ *
+ *
+ * @author Apache Software Foundation
* @author Matthew Hawthorne
- * @author Stephen Colebourne
* @since 2.0
* @version $Id$
*/
public class NullArgumentException extends IllegalArgumentException {
- /**
- * Instantiates with the given argument name.
+ /**
+ * Required for serialization support.
*
- * @param argName the name of the argument that was null
.
- */
- public NullArgumentException(String argName) {
- super(argName + " must not be null.");
- }
+ * @see java.io.Serializable
+ */
+ private static final long serialVersionUID = 1174360235354917591L;
+ /**
+ * Instantiates with the given argument name.
+ *
+ * @param argName the name of the argument that was null
.
+ */
+ public NullArgumentException(String argName) {
+ super((argName == null ? "Argument" : argName) + " must not be null.");
+ }
+
}
Index: 3rdParty_sources/commons-lang/org/apache/commons/lang/NumberRange.java
===================================================================
RCS file: /usr/local/cvsroot/3rdParty_sources/commons-lang/org/apache/commons/lang/NumberRange.java,v
diff -u -r1.1 -r1.2
--- 3rdParty_sources/commons-lang/org/apache/commons/lang/NumberRange.java 30 Aug 2012 16:24:42 -0000 1.1
+++ 3rdParty_sources/commons-lang/org/apache/commons/lang/NumberRange.java 15 Mar 2013 09:52:49 -0000 1.2
@@ -1,67 +1,32 @@
-/* ====================================================================
- * The Apache Software License, Version 1.1
- *
- * Copyright (c) 2002-2003 The Apache Software Foundation. All rights
- * reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in
- * the documentation and/or other materials provided with the
- * distribution.
- *
- * 3. The end-user documentation included with the redistribution, if
- * any, must include the following acknowledgement:
- * "This product includes software developed by the
- * Apache Software Foundation (http://www.apache.org/)."
- * Alternately, this acknowledgement may appear in the software itself,
- * if and wherever such third-party acknowledgements normally appear.
- *
- * 4. The names "The Jakarta Project", "Commons", and "Apache Software
- * Foundation" must not be used to endorse or promote products derived
- * from this software without prior written permission. For written
- * permission, please contact apache@apache.org.
- *
- * 5. Products derived from this software may not be called "Apache"
- * nor may "Apache" appear in their names without prior written
- * permission of the Apache Software Foundation.
- *
- * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
- * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
- * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
- * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- * ====================================================================
- *
- * This software consists of voluntary contributions made by many
- * individuals on behalf of the Apache Software Foundation. For more
- * information on the Apache Software Foundation, please see
- * .
+/*
+ * 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.lang;
+import org.apache.commons.lang.text.StrBuilder;
+
/**
* Represents a range of {@link Number} objects.
*
* This class uses double
comparisons. This means that it
* is unsuitable for dealing with large Long
, BigDecimal
* or BigInteger
numbers.
*
+ * @author Apache Software Foundation
* @author Christopher Elkins
- * @author Stephen Colebourne
* @since 1.0
* @version $Revision$ $Date$
*
@@ -231,7 +196,7 @@
* @return the string representation of this range
*/
public String toString() {
- StringBuffer sb = new StringBuffer();
+ StrBuilder sb = new StrBuilder();
if (min.doubleValue() < 0) {
sb.append('(')
Index: 3rdParty_sources/commons-lang/org/apache/commons/lang/NumberUtils.java
===================================================================
RCS file: /usr/local/cvsroot/3rdParty_sources/commons-lang/org/apache/commons/lang/NumberUtils.java,v
diff -u -r1.1 -r1.2
--- 3rdParty_sources/commons-lang/org/apache/commons/lang/NumberUtils.java 30 Aug 2012 16:24:42 -0000 1.1
+++ 3rdParty_sources/commons-lang/org/apache/commons/lang/NumberUtils.java 15 Mar 2013 09:52:49 -0000 1.2
@@ -1,55 +1,18 @@
-/* ====================================================================
- * The Apache Software License, Version 1.1
- *
- * Copyright (c) 2002-2003 The Apache Software Foundation. All rights
- * reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in
- * the documentation and/or other materials provided with the
- * distribution.
- *
- * 3. The end-user documentation included with the redistribution, if
- * any, must include the following acknowledgement:
- * "This product includes software developed by the
- * Apache Software Foundation (http://www.apache.org/)."
- * Alternately, this acknowledgement may appear in the software itself,
- * if and wherever such third-party acknowledgements normally appear.
- *
- * 4. The names "The Jakarta Project", "Commons", and "Apache Software
- * Foundation" must not be used to endorse or promote products derived
- * from this software without prior written permission. For written
- * permission, please contact apache@apache.org.
- *
- * 5. Products derived from this software may not be called "Apache"
- * nor may "Apache" appear in their names without prior written
- * permission of the Apache Software Foundation.
- *
- * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
- * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
- * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
- * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- * ====================================================================
- *
- * This software consists of voluntary contributions made by many
- * individuals on behalf of the Apache Software Foundation. For more
- * information on the Apache Software Foundation, please see
- * .
+/*
+ * 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.lang;
@@ -59,9 +22,8 @@
/**
* Provides extra functionality for Java Number classes.
*
- * @author Henri Yandell
+ * @author Apache Software Foundation
* @author Rand McNeely
- * @author Stephen Colebourne
* @author Steve Downey
* @author Eric Pugh
* @author Phil Steitz
@@ -82,6 +44,7 @@
* to operate.
*/
public NumberUtils() {
+ super();
}
//--------------------------------------------------------------------
@@ -156,7 +119,7 @@
*
* First, the value is examined for a type qualifier on the end
* ('f','F','d','D','l','L'
). If it is found, it starts
- * trying to create succissively larger types from the type specified
+ * trying to create successively larger types from the type specified
* until one is found that can hold the value.
*
* If a type specifier is not found, it will check for a decimal point
@@ -179,6 +142,9 @@
if (val.length() == 0) {
throw new NumberFormatException("\"\" is not a valid number.");
}
+ if (val.length() == 1 && !Character.isDigit(val.charAt(0))) {
+ throw new NumberFormatException(val + " is not a valid number.");
+ }
if (val.startsWith("--")) {
// this is protection for poorness in java.lang.BigDecimal.
// it accepts this as a legal value, but it does not appear
@@ -229,8 +195,7 @@
case 'L' :
if (dec == null
&& exp == null
- && isDigits(numeric.substring(1))
- && (numeric.charAt(0) == '-' || Character.isDigit(numeric.charAt(0)))) {
+ && (numeric.charAt(0) == '-' && isDigits(numeric.substring(1)) || isDigits(numeric))) {
try {
return createLong(numeric);
} catch (NumberFormatException nfe) {
@@ -246,13 +211,14 @@
Float f = NumberUtils.createFloat(numeric);
if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) {
//If it's too big for a float or the float value = 0 and the string
- //has non-zeros in it, then float doens't have the presision we want
+ //has non-zeros in it, then float does not have the precision we want
return f;
}
- } catch (NumberFormatException nfe) {
+ } catch (NumberFormatException e) {
+ // ignore the bad number
}
- //Fall through
+ //$FALL-THROUGH$
case 'd' :
case 'D' :
try {
@@ -261,12 +227,14 @@
return d;
}
} catch (NumberFormatException nfe) {
+ // empty catch
}
try {
return createBigDecimal(numeric);
} catch (NumberFormatException e) {
+ // empty catch
}
- //Fall through
+ //$FALL-THROUGH$
default :
throw new NumberFormatException(val + " is not a valid number.");
@@ -284,10 +252,12 @@
try {
return createInteger(val);
} catch (NumberFormatException nfe) {
+ // empty catch
}
try {
return createLong(val);
} catch (NumberFormatException nfe) {
+ // empty catch
}
return createBigInteger(val);
@@ -300,13 +270,15 @@
return f;
}
} catch (NumberFormatException nfe) {
+ // empty catch
}
try {
Double d = createDouble(val);
if (!(d.isInfinite() || (d.doubleValue() == 0.0D && !allZeros))) {
return d;
}
} catch (NumberFormatException nfe) {
+ // empty catch
}
return createBigDecimal(val);
@@ -501,7 +473,7 @@
*
NaN
* Positive infinity
* Maximum double
- * Normal positve numbers
+ * Normal positive numbers
* +0.0
* -0.0
* Normal negative numbers
@@ -550,7 +522,7 @@
/**
* Compares two floats for order.
*
- * This method is more comprhensive than the standard Java greater than,
+ *
This method is more comprehensive than the standard Java greater than,
* less than and equals operators.
*
* - It returns
-1
if the first value is less than the second.
@@ -563,7 +535,7 @@
* - NaN
*
- Positive infinity
*
- Maximum float
- *
- Normal positve numbers
+ *
- Normal positive numbers
*
- +0.0
*
- -0.0
*
- Normal negative numbers
@@ -646,7 +618,7 @@
* @return
true
if the string is a correctly formatted number
*/
public static boolean isNumber(String str) {
- if ((str == null) || (str.length() == 0)) {
+ if (StringUtils.isEmpty(str)) {
return false;
}
char[] chars = str.toCharArray();
@@ -730,7 +702,7 @@
}
if (chars[i] == 'l'
|| chars[i] == 'L') {
- // not allowing L with an exponoent
+ // not allowing L with an exponent
return foundDigit && !hasExp;
}
// last character is illegal
Index: 3rdParty_sources/commons-lang/org/apache/commons/lang/ObjectUtils.java
===================================================================
RCS file: /usr/local/cvsroot/3rdParty_sources/commons-lang/org/apache/commons/lang/ObjectUtils.java,v
diff -u -r1.1 -r1.2
--- 3rdParty_sources/commons-lang/org/apache/commons/lang/ObjectUtils.java 30 Aug 2012 16:24:42 -0000 1.1
+++ 3rdParty_sources/commons-lang/org/apache/commons/lang/ObjectUtils.java 15 Mar 2013 09:52:49 -0000 1.2
@@ -1,77 +1,49 @@
-/* ====================================================================
- * The Apache Software License, Version 1.1
- *
- * Copyright (c) 2002-2003 The Apache Software Foundation. All rights
- * reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in
- * the documentation and/or other materials provided with the
- * distribution.
- *
- * 3. The end-user documentation included with the redistribution, if
- * any, must include the following acknowledgement:
- * "This product includes software developed by the
- * Apache Software Foundation (http://www.apache.org/)."
- * Alternately, this acknowledgement may appear in the software itself,
- * if and wherever such third-party acknowledgements normally appear.
- *
- * 4. The names "The Jakarta Project", "Commons", and "Apache Software
- * Foundation" must not be used to endorse or promote products derived
- * from this software without prior written permission. For written
- * permission, please contact apache@apache.org.
- *
- * 5. Products derived from this software may not be called "Apache"
- * nor may "Apache" appear in their names without prior written
- * permission of the Apache Software Foundation.
- *
- * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
- * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
- * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
- * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- * ====================================================================
- *
- * This software consists of voluntary contributions made by many
- * individuals on behalf of the Apache Software Foundation. For more
- * information on the Apache Software Foundation, please see
- * .
+/*
+ * 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.lang;
import java.io.Serializable;
+import java.lang.reflect.Array;
+import java.lang.reflect.InvocationTargetException;
+import org.apache.commons.lang.exception.CloneFailedException;
+import org.apache.commons.lang.reflect.MethodUtils;
+
/**
* Operations on Object
.
*
* This class tries to handle null
input gracefully.
* An exception will generally not be thrown for a null
input.
* Each method documents its behaviour in more detail.
*
+ * #ThreadSafe#
+ * @author Apache Software Foundation
* @author Nissim Karpenstein
* @author Janek Bogucki
- * @author Daniel Rall
- * @author Stephen Colebourne
+ * @author Daniel L. Rall
* @author Gary Gregory
+ * @author Mario Winterer
+ * @author David J. M. Karlsen
* @since 1.0
* @version $Id$
*/
+//@Immutable
public class ObjectUtils {
-
+
/**
* Singleton used as a null
placeholder where
* null
has another meaning.
@@ -99,6 +71,7 @@
* to operate.
*/
public ObjectUtils() {
+ super();
}
// Defaulting
@@ -120,7 +93,7 @@
* @return object
if it is not null
, defaultValue otherwise
*/
public static Object defaultIfNull(Object object, Object defaultValue) {
- return (object != null ? object : defaultValue);
+ return object != null ? object : defaultValue;
}
/**
@@ -151,7 +124,48 @@
}
return object1.equals(object2);
}
-
+
+ /**
+ * Compares two objects for inequality, where either one or both
+ * objects may be null
.
+ *
+ *
+ * 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
+ *
+ *
+ * @param object1 the first object, may be null
+ * @param object2 the second object, may be null
+ * @return false
if the values of both objects are the same
+ * @since 2.6
+ */
+ public static boolean notEqual(Object object1, Object object2) {
+ return ObjectUtils.equals(object1, object2) == false;
+ }
+
+ /**
+ * Gets the hash code of an object returning zero when the
+ * object is null
.
+ *
+ *
+ * ObjectUtils.hashCode(null) = 0
+ * ObjectUtils.hashCode(obj) = obj.hashCode()
+ *
+ *
+ * @param obj the object to obtain the hash code of, may be null
+ * @return the hash code of the object, or zero if null
+ * @since 2.1
+ */
+ public static int hashCode(Object obj) {
+ return (obj == null) ? 0 : obj.hashCode();
+ }
+
// Identity ToString
//-----------------------------------------------------------------------
/**
@@ -174,12 +188,38 @@
if (object == null) {
return null;
}
- return appendIdentityToString(null, object).toString();
+ StringBuffer buffer = new StringBuffer();
+ identityToString(buffer, object);
+ return buffer.toString();
}
/**
* Appends the toString that would be produced by Object
* if a class did not override toString itself. null
+ * will throw a NullPointerException for either of the two parameters.
+ *
+ *
+ * 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 buffer the buffer to append to
+ * @param object the object to create a toString for
+ * @since 2.4
+ */
+ public static void identityToString(StringBuffer buffer, Object object) {
+ if (object == null) {
+ throw new NullPointerException("Cannot get the toString of a null identity");
+ }
+ buffer.append(object.getClass().getName())
+ .append('@')
+ .append(Integer.toHexString(System.identityHashCode(object)));
+ }
+
+ /**
+ * Appends the toString that would be produced by Object
+ * if a class did not override toString itself. null
* will return null
.
*
*
@@ -194,6 +234,7 @@
* @return the default toString text, or null
if
* null
passed in
* @since 2.0
+ * @deprecated The design of this method is bad - see LANG-360. Instead, use identityToString(StringBuffer, Object).
*/
public static StringBuffer appendIdentityToString(StringBuffer buffer, Object object) {
if (object == null) {
@@ -228,7 +269,7 @@
* @since 2.0
*/
public static String toString(Object obj) {
- return (obj == null ? "" : obj.toString());
+ return obj == null ? "" : obj.toString();
}
/**
@@ -251,9 +292,144 @@
* @since 2.0
*/
public static String toString(Object obj, String nullStr) {
- return (obj == null ? nullStr : obj.toString());
+ return obj == null ? nullStr : obj.toString();
}
+ // Min/Max
+ //-----------------------------------------------------------------------
+ /**
+ * Null safe comparison of Comparables.
+ *
+ * @param c1 the first comparable, may be null
+ * @param c2 the second comparable, may be null
+ * @return
+ *
+ * - If both objects are non-null and unequal, the lesser object.
+ *
- If both objects are non-null and equal, c1.
+ *
- If one of the comparables is null, the non-null object.
+ *
- If both the comparables are null, null is returned.
+ *
+ */
+ public static Object min(Comparable c1, Comparable c2) {
+ return (compare(c1, c2, true) <= 0 ? c1 : c2);
+ }
+
+ /**
+ * Null safe comparison of Comparables.
+ *
+ * @param c1 the first comparable, may be null
+ * @param c2 the second comparable, may be null
+ * @return
+ *
+ * - If both objects are non-null and unequal, the greater object.
+ *
- If both objects are non-null and equal, c1.
+ *
- If one of the comparables is null, the non-null object.
+ *
- If both the comparables are null, null is returned.
+ *
+ */
+ public static Object max(Comparable c1, Comparable c2) {
+ return (compare(c1, c2, false) >= 0 ? c1 : c2);
+ }
+
+ /**
+ * Null safe comparison of Comparables.
+ * {@code null} is assumed to be less than a non-{@code null} value.
+ *
+ * @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
+ * @since 2.6
+ */
+ public static int compare(Comparable c1, Comparable c2) {
+ return compare(c1, c2, false);
+ }
+
+ /**
+ * Null safe comparison of Comparables.
+ *
+ * @param c1 the first comparable, may be null
+ * @param c2 the second comparable, may be null
+ * @param nullGreater if true null
is considered greater
+ * than a Non-null
value or if false null
is
+ * considered less than a Non-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)
+ * @since 2.6
+ */
+ public static int compare(Comparable c1, Comparable c2, 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);
+ }
+
+ /**
+ * Clone an object.
+ *
+ * @param o the object to clone
+ * @return the clone if the object implements {@link Cloneable} otherwise null
+ * @throws CloneFailedException if the object is cloneable and the clone operation fails
+ * @since 2.6
+ */
+ public static Object clone(final Object o) {
+ if (o instanceof Cloneable) {
+ final Object result;
+ if (o.getClass().isArray()) {
+ final Class componentType = o.getClass().getComponentType();
+ if (!componentType.isPrimitive()) {
+ result = ((Object[])o).clone();
+ } else {
+ int length = Array.getLength(o);
+ result = Array.newInstance(componentType, length);
+ while (length-- > 0) {
+ Array.set(result, length, Array.get(o, length));
+ }
+ }
+ } else {
+ try {
+ result = MethodUtils.invokeMethod(o, "clone", null);
+ } catch (final NoSuchMethodException e) {
+ throw new CloneFailedException("Cloneable type "
+ + o.getClass().getName()
+ + " has no clone method", e);
+ } catch (final IllegalAccessException e) {
+ throw new CloneFailedException("Cannot clone Cloneable type "
+ + o.getClass().getName(), e);
+ } catch (final InvocationTargetException e) {
+ throw new CloneFailedException("Exception cloning Cloneable type "
+ + o.getClass().getName(), e.getTargetException());
+ }
+ }
+ return result;
+ }
+
+ return null;
+ }
+
+ /**
+ * Clone an object if possible. This method is similar to {@link #clone(Object)}, but will
+ * return the provided instance as the return value instead of 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 o the object to clone
+ * @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 2.6
+ */
+ public static Object cloneIfPossible(final Object o) {
+ final Object clone = clone(o);
+ return clone == null ? o : clone;
+ }
+
// Null
//-----------------------------------------------------------------------
/**
@@ -271,13 +447,18 @@
* cannot be stored.
*/
public static class Null implements Serializable {
- // declare serialization compatability with Commons Lang 1.0
+ /**
+ * 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();
}
/**
@@ -289,5 +470,5 @@
return ObjectUtils.NULL;
}
}
-
+
}
Index: 3rdParty_sources/commons-lang/org/apache/commons/lang/RandomStringUtils.java
===================================================================
RCS file: /usr/local/cvsroot/3rdParty_sources/commons-lang/org/apache/commons/lang/RandomStringUtils.java,v
diff -u -r1.1 -r1.2
--- 3rdParty_sources/commons-lang/org/apache/commons/lang/RandomStringUtils.java 30 Aug 2012 16:24:42 -0000 1.1
+++ 3rdParty_sources/commons-lang/org/apache/commons/lang/RandomStringUtils.java 15 Mar 2013 09:52:49 -0000 1.2
@@ -1,66 +1,36 @@
-/* ====================================================================
- * The Apache Software License, Version 1.1
- *
- * Copyright (c) 2002-2003 The Apache Software Foundation. All rights
- * reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in
- * the documentation and/or other materials provided with the
- * distribution.
- *
- * 3. The end-user documentation included with the redistribution, if
- * any, must include the following acknowledgement:
- * "This product includes software developed by the
- * Apache Software Foundation (http://www.apache.org/)."
- * Alternately, this acknowledgement may appear in the software itself,
- * if and wherever such third-party acknowledgements normally appear.
- *
- * 4. The names "The Jakarta Project", "Commons", and "Apache Software
- * Foundation" must not be used to endorse or promote products derived
- * from this software without prior written permission. For written
- * permission, please contact apache@apache.org.
- *
- * 5. Products derived from this software may not be called "Apache"
- * nor may "Apache" appear in their names without prior written
- * permission of the Apache Software Foundation.
- *
- * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
- * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
- * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
- * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- * ====================================================================
- *
- * This software consists of voluntary contributions made by many
- * individuals on behalf of the Apache Software Foundation. For more
- * information on the Apache Software Foundation, please see
- * .
+/*
+ * 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.lang;
import java.util.Random;
/**
* Operations for random String
s.
+ * Currently private high surrogate characters are ignored.
+ * These are unicode characters that fall between the values 56192 (db80)
+ * and 56319 (dbff) as we don't know how to handle them.
+ * High and low surrogates are correctly dealt with - that is if a
+ * high surrogate is randomly chosen, 55296 (d800) to 56191 (db7f)
+ * then it is followed by a low surrogate. If a low surrogate is chosen,
+ * 56320 (dc00) to 57343 (dfff) then it is placed after a randomly
+ * chosen high surrogate.
*
- * @author GenerationJava Core library
- * @author Henri Yandell
+ * #ThreadSafe#
+ * @author Apache Software Foundation
* @author Steven Caswell
- * @author Stephen Colebourne
* @author Gary Gregory
* @author Phil Steitz
* @since 1.0
@@ -84,6 +54,7 @@
* to operate.
*/
public RandomStringUtils() {
+ super();
}
// Random
@@ -167,7 +138,7 @@
* @param count the length of random string to create
* @param letters if true
, generated string will include
* alphabetic characters
- * @param numbers if true
, generatd string will include
+ * @param numbers if true
, generated string will include
* numeric characters
* @return the random string
*/
@@ -252,7 +223,8 @@
* @throws IllegalArgumentException if count
< 0.
* @since 2.0
*/
- public static String random(int count, int start, int end, boolean letters, boolean numbers, char[] chars, Random random) {
+ public static String random(int count, int start, int end, boolean letters, boolean numbers,
+ char[] chars, Random random) {
if (count == 0) {
return "";
} else if (count < 0) {
@@ -267,7 +239,7 @@
}
}
- StringBuffer buffer = new StringBuffer();
+ char[] buffer = new char[count];
int gap = end - start;
while (count-- != 0) {
@@ -277,16 +249,39 @@
} else {
ch = chars[random.nextInt(gap) + start];
}
- if ((letters && numbers && Character.isLetterOrDigit(ch))
- || (letters && Character.isLetter(ch))
+ if ((letters && Character.isLetter(ch))
|| (numbers && Character.isDigit(ch))
- || (!letters && !numbers)) {
- buffer.append(ch);
+ || (!letters && !numbers))
+ {
+ if(ch >= 56320 && ch <= 57343) {
+ if(count == 0) {
+ count++;
+ } else {
+ // low surrogate, insert high surrogate after putting it in
+ buffer[count] = ch;
+ count--;
+ buffer[count] = (char) (55296 + random.nextInt(128));
+ }
+ } else if(ch >= 55296 && ch <= 56191) {
+ if(count == 0) {
+ count++;
+ } else {
+ // high surrogate, insert low surrogate before putting it in
+ buffer[count] = (char) (56320 + random.nextInt(128));
+ count--;
+ buffer[count] = ch;
+ }
+ } else if(ch >= 56192 && ch <= 56319) {
+ // private high surrogate, no effing clue, so skip it
+ count++;
+ } else {
+ buffer[count] = ch;
+ }
} else {
count++;
}
}
- return buffer.toString();
+ return new String(buffer);
}
/**
Index: 3rdParty_sources/commons-lang/org/apache/commons/lang/SerializationException.java
===================================================================
RCS file: /usr/local/cvsroot/3rdParty_sources/commons-lang/org/apache/commons/lang/SerializationException.java,v
diff -u -r1.1 -r1.2
--- 3rdParty_sources/commons-lang/org/apache/commons/lang/SerializationException.java 30 Aug 2012 16:24:42 -0000 1.1
+++ 3rdParty_sources/commons-lang/org/apache/commons/lang/SerializationException.java 15 Mar 2013 09:52:49 -0000 1.2
@@ -1,55 +1,18 @@
-/* ====================================================================
- * The Apache Software License, Version 1.1
- *
- * Copyright (c) 2002-2003 The Apache Software Foundation. All rights
- * reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in
- * the documentation and/or other materials provided with the
- * distribution.
- *
- * 3. The end-user documentation included with the redistribution, if
- * any, must include the following acknowledgement:
- * "This product includes software developed by the
- * Apache Software Foundation (http://www.apache.org/)."
- * Alternately, this acknowledgement may appear in the software itself,
- * if and wherever such third-party acknowledgements normally appear.
- *
- * 4. The names "The Jakarta Project", "Commons", and "Apache Software
- * Foundation" must not be used to endorse or promote products derived
- * from this software without prior written permission. For written
- * permission, please contact apache@apache.org.
- *
- * 5. Products derived from this software may not be called "Apache"
- * nor may "Apache" appear in their names without prior written
- * permission of the Apache Software Foundation.
- *
- * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
- * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
- * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
- * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- * ====================================================================
- *
- * This software consists of voluntary contributions made by many
- * individuals on behalf of the Apache Software Foundation. For more
- * information on the Apache Software Foundation, please see
- * .
+/*
+ * 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.lang;
@@ -60,13 +23,20 @@
*
* The original error is wrapped within this one.
*
- * @author Stephen Colebourne
+ * @author Apache Software Foundation
* @since 1.0
* @version $Id$
*/
public class SerializationException extends NestableRuntimeException {
/**
+ * Required for serialization support.
+ *
+ * @see java.io.Serializable
+ */
+ private static final long serialVersionUID = 4029025366392702726L;
+
+ /**
* Constructs a new SerializationException
without specified
* detail message.
*/
Index: 3rdParty_sources/commons-lang/org/apache/commons/lang/SerializationUtils.java
===================================================================
RCS file: /usr/local/cvsroot/3rdParty_sources/commons-lang/org/apache/commons/lang/SerializationUtils.java,v
diff -u -r1.1 -r1.2
--- 3rdParty_sources/commons-lang/org/apache/commons/lang/SerializationUtils.java 30 Aug 2012 16:24:42 -0000 1.1
+++ 3rdParty_sources/commons-lang/org/apache/commons/lang/SerializationUtils.java 15 Mar 2013 09:52:49 -0000 1.2
@@ -1,55 +1,18 @@
-/* ====================================================================
- * The Apache Software License, Version 1.1
- *
- * Copyright (c) 2002-2003 The Apache Software Foundation. All rights
- * reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in
- * the documentation and/or other materials provided with the
- * distribution.
- *
- * 3. The end-user documentation included with the redistribution, if
- * any, must include the following acknowledgement:
- * "This product includes software developed by the
- * Apache Software Foundation (http://www.apache.org/)."
- * Alternately, this acknowledgement may appear in the software itself,
- * if and wherever such third-party acknowledgements normally appear.
- *
- * 4. The names "The Jakarta Project", "Commons", and "Apache Software
- * Foundation" must not be used to endorse or promote products derived
- * from this software without prior written permission. For written
- * permission, please contact apache@apache.org.
- *
- * 5. Products derived from this software may not be called "Apache"
- * nor may "Apache" appear in their names without prior written
- * permission of the Apache Software Foundation.
- *
- * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
- * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
- * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
- * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- * ====================================================================
- *
- * This software consists of voluntary contributions made by many
- * individuals on behalf of the Apache Software Foundation. For more
- * information on the Apache Software Foundation, please see
- * .
+/*
+ * 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.lang;
@@ -75,10 +38,11 @@
* This class throws exceptions for invalid null
inputs.
* Each method documents its behaviour in more detail.
*
+ * #ThreadSafe#
+ * @author Apache Software Foundation
* @author Nissim Karpenstein
* @author Janek Bogucki
- * @author Daniel Rall
- * @author Stephen Colebourne
+ * @author Daniel L. Rall
* @author Jeff Varszegi
* @author Gary Gregory
* @since 1.0
@@ -152,7 +116,7 @@
out.close();
}
} catch (IOException ex) {
- // ignore;
+ // ignore close exception
}
}
}
@@ -208,7 +172,7 @@
in.close();
}
} catch (IOException ex) {
- // ignore
+ // ignore close exception
}
}
}
Index: 3rdParty_sources/commons-lang/org/apache/commons/lang/StringEscapeUtils.java
===================================================================
RCS file: /usr/local/cvsroot/3rdParty_sources/commons-lang/org/apache/commons/lang/StringEscapeUtils.java,v
diff -u -r1.1 -r1.2
--- 3rdParty_sources/commons-lang/org/apache/commons/lang/StringEscapeUtils.java 30 Aug 2012 16:24:42 -0000 1.1
+++ 3rdParty_sources/commons-lang/org/apache/commons/lang/StringEscapeUtils.java 15 Mar 2013 09:52:49 -0000 1.2
@@ -1,73 +1,39 @@
-/* ====================================================================
- * The Apache Software License, Version 1.1
- *
- * Copyright (c) 2002-2003 The Apache Software Foundation. All rights
- * reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in
- * the documentation and/or other materials provided with the
- * distribution.
- *
- * 3. The end-user documentation included with the redistribution, if
- * any, must include the following acknowledgement:
- * "This product includes software developed by the
- * Apache Software Foundation (http://www.apache.org/)."
- * Alternately, this acknowledgement may appear in the software itself,
- * if and wherever such third-party acknowledgements normally appear.
- *
- * 4. The names "The Jakarta Project", "Commons", and "Apache Software
- * Foundation" must not be used to endorse or promote products derived
- * from this software without prior written permission. For written
- * permission, please contact apache@apache.org.
- *
- * 5. Products derived from this software may not be called "Apache"
- * nor may "Apache" appear in their names without prior written
- * permission of the Apache Software Foundation.
- *
- * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
- * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
- * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
- * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- * ====================================================================
- *
- * This software consists of voluntary contributions made by many
- * individuals on behalf of the Apache Software Foundation. For more
- * information on the Apache Software Foundation, please see
- * .
+/*
+ * 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.lang;
import java.io.IOException;
+import java.io.StringWriter;
import java.io.Writer;
+import java.util.Locale;
import org.apache.commons.lang.exception.NestableRuntimeException;
+import org.apache.commons.lang.text.StrBuilder;
/**
* Escapes and unescapes String
s for
* Java, Java Script, HTML, XML, and SQL.
*
+ * #ThreadSafe#
+ * @author Apache Software Foundation
* @author Apache Jakarta Turbine
- * @author GenerationJavaCore library
* @author Purple Technology
- * @author Henri Yandell
* @author Alexander Day Chaffee
- * @author Antony Riley
+ * @author Antony Riley
* @author Helge Tesgaard
* @author Sean Brown
* @author Gary Gregory
@@ -78,6 +44,11 @@
*/
public class StringEscapeUtils {
+ private static final char CSV_DELIMITER = ',';
+ private static final char CSV_QUOTE = '"';
+ private static final String CSV_QUOTE_STR = String.valueOf(CSV_QUOTE);
+ private static final char[] CSV_SEARCH_CHARS = new char[] {CSV_DELIMITER, CSV_QUOTE, CharUtils.CR, CharUtils.LF};
+
/**
* StringEscapeUtils
instances should NOT be constructed in
* standard programming.
@@ -89,6 +60,7 @@
* instance to operate.
*/
public StringEscapeUtils() {
+ super();
}
// Java and JavaScript
@@ -115,7 +87,7 @@
* @return String with escaped values, null
if null string input
*/
public static String escapeJava(String str) {
- return escapeJavaStyleString(str, false);
+ return escapeJavaStyleString(str, false, false);
}
/**
@@ -128,10 +100,10 @@
* @param out Writer to write escaped string into
* @param str String to escape values in, may be null
* @throws IllegalArgumentException if the Writer is null
- * @throws IOException if error occurs on undelying Writer
+ * @throws IOException if error occurs on underlying Writer
*/
public static void escapeJava(Writer out, String str) throws IOException {
- escapeJavaStyleString(out, str, false);
+ escapeJavaStyleString(out, str, false, false);
}
/**
@@ -156,7 +128,7 @@
* @return String with escaped values, null
if null string input
*/
public static String escapeJavaScript(String str) {
- return escapeJavaStyleString(str, true);
+ return escapeJavaStyleString(str, true, true);
}
/**
@@ -169,28 +141,45 @@
* @param out Writer to write escaped string into
* @param str String to escape values in, may be null
* @throws IllegalArgumentException if the Writer is null
- * @throws IOException if error occurs on undelying Writer
+ * @throws IOException if error occurs on underlying Writer
**/
public static void escapeJavaScript(Writer out, String str) throws IOException {
- escapeJavaStyleString(out, str, true);
+ escapeJavaStyleString(out, str, true, true);
}
- private static String escapeJavaStyleString(String str, boolean escapeSingleQuotes) {
+ /**
+ * Worker method for the {@link #escapeJavaScript(String)} method.
+ *
+ * @param str String to escape values in, may be null
+ * @param escapeSingleQuotes escapes single quotes if true
+ * @param escapeForwardSlash TODO
+ * @return the escaped string
+ */
+ private static String escapeJavaStyleString(String str, boolean escapeSingleQuotes, boolean escapeForwardSlash) {
if (str == null) {
return null;
}
try {
- StringPrintWriter writer = new StringPrintWriter(str.length() * 2);
- escapeJavaStyleString(writer, str, escapeSingleQuotes);
- return writer.getString();
+ StringWriter writer = new StringWriter(str.length() * 2);
+ escapeJavaStyleString(writer, str, escapeSingleQuotes, escapeForwardSlash);
+ return writer.toString();
} catch (IOException ioe) {
// this should never ever happen while writing to a StringWriter
- ioe.printStackTrace();
- return null;
+ throw new UnhandledException(ioe);
}
}
- private static void escapeJavaStyleString(Writer out, String str, boolean escapeSingleQuote) throws IOException {
+ /**
+ * Worker method for the {@link #escapeJavaScript(String)} method.
+ *
+ * @param out write to receieve the escaped string
+ * @param str String to escape values in, may be null
+ * @param escapeSingleQuote escapes single quotes if true
+ * @param escapeForwardSlash TODO
+ * @throws IOException if an IOException occurs
+ */
+ private static void escapeJavaStyleString(Writer out, String str, boolean escapeSingleQuote,
+ boolean escapeForwardSlash) throws IOException {
if (out == null) {
throw new IllegalArgumentException("The Writer must not be null");
}
@@ -211,23 +200,23 @@
out.write("\\u00" + hex(ch));
} else if (ch < 32) {
switch (ch) {
- case '\b':
+ case '\b' :
out.write('\\');
out.write('b');
break;
- case '\n':
+ case '\n' :
out.write('\\');
out.write('n');
break;
- case '\t':
+ case '\t' :
out.write('\\');
out.write('t');
break;
- case '\f':
+ case '\f' :
out.write('\\');
out.write('f');
break;
- case '\r':
+ case '\r' :
out.write('\\');
out.write('r');
break;
@@ -241,18 +230,26 @@
}
} else {
switch (ch) {
- case '\'':
- if (escapeSingleQuote) out.write('\\');
+ case '\'' :
+ if (escapeSingleQuote) {
+ out.write('\\');
+ }
out.write('\'');
break;
- case '"':
+ case '"' :
out.write('\\');
out.write('"');
break;
- case '\\':
+ case '\\' :
out.write('\\');
out.write('\\');
break;
+ case '/' :
+ if (escapeForwardSlash) {
+ out.write('\\');
+ }
+ out.write('/');
+ break;
default :
out.write(ch);
break;
@@ -269,7 +266,7 @@
* @return An upper case hexadecimal String
*/
private static String hex(char ch) {
- return Integer.toHexString(ch).toUpperCase();
+ return Integer.toHexString(ch).toUpperCase(Locale.ENGLISH);
}
/**
@@ -286,13 +283,12 @@
return null;
}
try {
- StringPrintWriter writer = new StringPrintWriter(str.length());
+ StringWriter writer = new StringWriter(str.length());
unescapeJava(writer, str);
- return writer.getString();
+ return writer.toString();
} catch (IOException ioe) {
// this should never ever happen while writing to a StringWriter
- ioe.printStackTrace();
- return null;
+ throw new UnhandledException(ioe);
}
}
@@ -309,7 +305,7 @@
* @param out the Writer
used to output unescaped characters
* @param str the String
to unescape, may be null
* @throws IllegalArgumentException if the Writer is null
- * @throws IOException if error occurs on undelying Writer
+ * @throws IOException if error occurs on underlying Writer
*/
public static void unescapeJava(Writer out, String str) throws IOException {
if (out == null) {
@@ -319,7 +315,7 @@
return;
}
int sz = str.length();
- StringBuffer unicode = new StringBuffer(4);
+ StrBuilder unicode = new StrBuilder(4);
boolean hadSlash = false;
boolean inUnicode = false;
for (int i = 0; i < sz; i++) {
@@ -330,7 +326,7 @@
unicode.append(ch);
if (unicode.length() == 4) {
// unicode now contains the four hex digits
- // which represents our unicode chacater
+ // which represents our unicode character
try {
int value = Integer.parseInt(unicode.toString(), 16);
out.write((char) value);
@@ -424,7 +420,7 @@
* @param out the Writer
used to output unescaped characters
* @param str the String
to unescape, may be null
* @throws IllegalArgumentException if the Writer is null
- * @throws IOException if error occurs on undelying Writer
+ * @throws IOException if error occurs on underlying Writer
*/
public static void unescapeJavaScript(Writer out, String str) throws IOException {
unescapeJava(out, str);
@@ -436,31 +432,83 @@
* Escapes the characters in a String
using HTML entities.
*
*
- * For example: "bread" & "butter" => "bread" & "butter".
+ * For example:
+ *
+ * "bread" & "butter"
+ * becomes:
+ *
+ * "bread" & "butter"
.
*
*
- * Supports all known HTML 4.0 entities, including funky accents.
- *
+ * Supports all known HTML 4.0 entities, including funky accents.
+ * Note that the commonly used apostrophe escape character (')
+ * is not a legal entity and so is not supported).
+ *
* @param str the String
to escape, may be null
* @return a new escaped String
, null
if null string input
*
* @see #unescapeHtml(String)
- * @see ISO Entities
- * @see HTML 3.2 Character Entities for ISO Latin-1
- * @see HTML 4.0 Character entity references
- * @see HTML 4.01 Character References
- * @see HTML 4.01 Code positions
- **/
+ * @see ISO Entities
+ * @see HTML 3.2 Character Entities for ISO Latin-1
+ * @see HTML 4.0 Character entity references
+ * @see HTML 4.01 Character References
+ * @see HTML 4.01 Code positions
+ */
public static String escapeHtml(String str) {
if (str == null) {
return null;
}
- //todo: add a version that takes a Writer
- //todo: rewrite underlying method to use a Writer instead of a StringBuffer
- return Entities.HTML40.escape(str);
+ try {
+ StringWriter writer = new StringWriter ((int)(str.length() * 1.5));
+ escapeHtml(writer, str);
+ return writer.toString();
+ } catch (IOException ioe) {
+ //should be impossible
+ throw new UnhandledException(ioe);
+ }
}
/**
+ * Escapes the characters in a String
using HTML entities and writes
+ * them to a Writer
.
+ *
+ *
+ * For example:
+ *
+ * "bread" & "butter"
+ * becomes:
+ * "bread" & "butter"
.
+ *
+ * Supports all known HTML 4.0 entities, including funky accents.
+ * Note that the commonly used apostrophe escape character (')
+ * is not a legal entity and so is not supported).
+ *
+ * @param writer the writer receiving the escaped string, not null
+ * @param string the String
to escape, may be null
+ * @throws IllegalArgumentException if the writer is null
+ * @throws IOException when Writer
passed throws the exception from
+ * calls to the {@link Writer#write(int)} methods.
+ *
+ * @see #escapeHtml(String)
+ * @see #unescapeHtml(String)
+ * @see ISO Entities
+ * @see HTML 3.2 Character Entities for ISO Latin-1
+ * @see HTML 4.0 Character entity references
+ * @see HTML 4.01 Character References
+ * @see HTML 4.01 Code positions
+ */
+ public static void escapeHtml(Writer writer, String string) throws IOException {
+ if (writer == null ) {
+ throw new IllegalArgumentException ("The Writer must not be null.");
+ }
+ if (string == null) {
+ return;
+ }
+ Entities.HTML40.escape(writer, string);
+ }
+
+ //-----------------------------------------------------------------------
+ /**
* Unescapes a string containing entity escapes to a string
* containing the actual Unicode characters corresponding to the
* escapes. Supports HTML 4.0 entities.
@@ -474,55 +522,155 @@
*
* @param str the String
to unescape, may be null
* @return a new unescaped String
, null
if null string input
- * @see #escapeHtml(String)
- **/
+ * @see #escapeHtml(Writer, String)
+ */
public static String unescapeHtml(String str) {
if (str == null) {
return null;
}
- return Entities.HTML40.unescape(str);
+ try {
+ StringWriter writer = new StringWriter ((int)(str.length() * 1.5));
+ unescapeHtml(writer, str);
+ return writer.toString();
+ } catch (IOException ioe) {
+ //should be impossible
+ throw new UnhandledException(ioe);
+ }
}
/**
+ * Unescapes a string containing entity escapes to a string
+ * containing the actual Unicode characters corresponding to the
+ * escapes. Supports HTML 4.0 entities.
+ *
+ * For example, the string "<Français>"
+ * will become "<Français>"
+ *
+ * If an entity is unrecognized, it is left alone, and inserted
+ * verbatim into the result string. e.g. ">&zzzz;x" will
+ * become ">&zzzz;x".
+ *
+ * @param writer the writer receiving the unescaped string, not null
+ * @param string the String
to unescape, may be null
+ * @throws IllegalArgumentException if the writer is null
+ * @throws IOException if an IOException occurs
+ * @see #escapeHtml(String)
+ */
+ public static void unescapeHtml(Writer writer, String string) throws IOException {
+ if (writer == null ) {
+ throw new IllegalArgumentException ("The Writer must not be null.");
+ }
+ if (string == null) {
+ return;
+ }
+ Entities.HTML40.unescape(writer, string);
+ }
+
+ //-----------------------------------------------------------------------
+ /**
* Escapes the characters in a String
using XML entities.
*
* For example: "bread" & "butter" =>
* "bread" & "butter".
*
*
- * Supports only the four basic XML entities (gt, lt, quot, amp).
+ *
Supports only the five basic XML entities (gt, lt, quot, amp, apos).
* Does not support DTDs or external entities.
*
+ * Note that unicode characters greater than 0x7f are currently escaped to
+ * their numerical \\u equivalent. This may change in future releases.
+ *
+ * @param writer the writer receiving the unescaped string, not null
* @param str the String
to escape, may be null
+ * @throws IllegalArgumentException if the writer is null
+ * @throws IOException if there is a problem writing
+ * @see #unescapeXml(java.lang.String)
+ */
+ public static void escapeXml(Writer writer, String str) throws IOException {
+ if (writer == null ) {
+ throw new IllegalArgumentException ("The Writer must not be null.");
+ }
+ if (str == null) {
+ return;
+ }
+ Entities.XML.escape(writer, str);
+ }
+
+ /**
+ * Escapes the characters in a String
using XML entities.
+ *
+ * For example: "bread" & "butter" =>
+ * "bread" & "butter".
+ *
+ *
+ * Supports only the five basic XML entities (gt, lt, quot, amp, apos).
+ * Does not support DTDs or external entities.
+ *
+ * Note that unicode characters greater than 0x7f are currently escaped to
+ * their numerical \\u equivalent. This may change in future releases.
+ *
+ * @param str the String
to escape, may be null
* @return a new escaped String
, null
if null string input
* @see #unescapeXml(java.lang.String)
- **/
+ */
public static String escapeXml(String str) {
if (str == null) {
return null;
}
return Entities.XML.escape(str);
}
+ //-----------------------------------------------------------------------
/**
* Unescapes a string containing XML entity escapes to a string
* containing the actual Unicode characters corresponding to the
* escapes.
*
- * Supports only the four basic XML entities (gt, lt, quot, amp).
+ *
Supports only the five basic XML entities (gt, lt, quot, amp, apos).
* Does not support DTDs or external entities.
*
+ * Note that numerical \\u unicode codes are unescaped to their respective
+ * unicode characters. This may change in future releases.
+ *
+ * @param writer the writer receiving the unescaped string, not null
* @param str the String
to unescape, may be null
+ * @throws IllegalArgumentException if the writer is null
+ * @throws IOException if there is a problem writing
+ * @see #escapeXml(String)
+ */
+ public static void unescapeXml(Writer writer, String str) throws IOException {
+ if (writer == null ) {
+ throw new IllegalArgumentException ("The Writer must not be null.");
+ }
+ if (str == null) {
+ return;
+ }
+ Entities.XML.unescape(writer, str);
+ }
+
+ /**
+ * Unescapes a string containing XML entity escapes to a string
+ * containing the actual Unicode characters corresponding to the
+ * escapes.
+ *
+ * Supports only the five basic XML entities (gt, lt, quot, amp, apos).
+ * Does not support DTDs or external entities.
+ *
+ * Note that numerical \\u unicode codes are unescaped to their respective
+ * unicode characters. This may change in future releases.
+ *
+ * @param str the String
to unescape, may be null
* @return a new unescaped String
, null
if null string input
* @see #escapeXml(String)
- **/
+ */
public static String unescapeXml(String str) {
if (str == null) {
return null;
}
return Entities.XML.unescape(str);
}
+ //-----------------------------------------------------------------------
/**
* Escapes the characters in a String
to be suitable to pass to
* an SQL query.
@@ -548,5 +696,166 @@
return StringUtils.replace(str, "'", "''");
}
-}
+ //-----------------------------------------------------------------------
+ /**
+ * Returns a String
value for a CSV column enclosed in double quotes,
+ * if required.
+ *
+ * If the value contains a comma, newline or double quote, then the
+ * String value is returned enclosed in double quotes.
+ *
+ *
+ * Any double quote characters in the value are escaped with another double quote.
+ *
+ * If the value does not contain a comma, newline or double quote, then the
+ * String value is returned unchanged.
+ *
+ *
+ * see Wikipedia and
+ * RFC 4180.
+ *
+ * @param str the input CSV column String, may be null
+ * @return the input String, enclosed in double quotes if the value contains a comma,
+ * newline or double quote, null
if null string input
+ * @since 2.4
+ */
+ public static String escapeCsv(String str) {
+ if (StringUtils.containsNone(str, CSV_SEARCH_CHARS)) {
+ return str;
+ }
+ try {
+ StringWriter writer = new StringWriter();
+ escapeCsv(writer, str);
+ return writer.toString();
+ } catch (IOException ioe) {
+ // this should never ever happen while writing to a StringWriter
+ throw new UnhandledException(ioe);
+ }
+ }
+
+ /**
+ * Writes a String
value for a CSV column enclosed in double quotes,
+ * if required.
+ *
+ * If the value contains a comma, newline or double quote, then the
+ * String value is written enclosed in double quotes.
+ *
+ *
+ * Any double quote characters in the value are escaped with another double quote.
+ *
+ * If the value does not contain a comma, newline or double quote, then the
+ * String value is written unchanged (null values are ignored).
+ *
+ *
+ * see Wikipedia and
+ * RFC 4180.
+ *
+ * @param str the input CSV column String, may be null
+ * @param out Writer to write input string to, enclosed in double quotes if it contains
+ * a comma, newline or double quote
+ * @throws IOException if error occurs on underlying Writer
+ * @since 2.4
+ */
+ public static void escapeCsv(Writer out, String str) throws IOException {
+ if (StringUtils.containsNone(str, CSV_SEARCH_CHARS)) {
+ if (str != null) {
+ out.write(str);
+ }
+ return;
+ }
+ out.write(CSV_QUOTE);
+ for (int i = 0; i < str.length(); i++) {
+ char c = str.charAt(i);
+ if (c == CSV_QUOTE) {
+ out.write(CSV_QUOTE); // escape double quote
+ }
+ out.write(c);
+ }
+ out.write(CSV_QUOTE);
+ }
+
+ /**
+ * Returns a String
value for an unescaped CSV column.
+ *
+ * If the value is enclosed in double quotes, and contains a comma, newline
+ * or double quote, then quotes are removed.
+ *
+ *
+ * Any double quote escaped characters (a pair of double quotes) are unescaped
+ * to just one double quote.
+ *
+ * If the value is not enclosed in double quotes, or is and does not contain a
+ * comma, newline or double quote, then the String value is returned unchanged.
+ *
+ *
+ * see Wikipedia and
+ * RFC 4180.
+ *
+ * @param str the input CSV column String, may be null
+ * @return the input String, with enclosing double quotes removed and embedded double
+ * quotes unescaped, null
if null string input
+ * @since 2.4
+ */
+ public static String unescapeCsv(String str) {
+ if (str == null) {
+ return null;
+ }
+ try {
+ StringWriter writer = new StringWriter();
+ unescapeCsv(writer, str);
+ return writer.toString();
+ } catch (IOException ioe) {
+ // this should never ever happen while writing to a StringWriter
+ throw new UnhandledException(ioe);
+ }
+ }
+
+ /**
+ * Returns a String
value for an unescaped CSV column.
+ *
+ * If the value is enclosed in double quotes, and contains a comma, newline
+ * or double quote, then quotes are removed.
+ *
+ *
+ * Any double quote escaped characters (a pair of double quotes) are unescaped
+ * to just one double quote.
+ *
+ * If the value is not enclosed in double quotes, or is and does not contain a
+ * comma, newline or double quote, then the String value is returned unchanged.
+ *
+ *
+ * see Wikipedia and
+ * RFC 4180.
+ *
+ * @param str the input CSV column String, may be null
+ * @param out Writer to write the input String to, with enclosing double quotes
+ * removed and embedded double quotes unescaped, null
if null string input
+ * @throws IOException if error occurs on underlying Writer
+ * @since 2.4
+ */
+ public static void unescapeCsv(Writer out, String str) throws IOException {
+ if (str == null) {
+ return;
+ }
+ if (str.length() < 2) {
+ out.write(str);
+ return;
+ }
+ if ( str.charAt(0) != CSV_QUOTE || str.charAt(str.length() - 1) != CSV_QUOTE ) {
+ out.write(str);
+ return;
+ }
+
+ // strip quotes
+ String quoteless = str.substring(1, str.length() - 1);
+
+ if ( StringUtils.containsAny(quoteless, CSV_SEARCH_CHARS) ) {
+ // deal with escaped quotes; ie) ""
+ str = StringUtils.replace(quoteless, CSV_QUOTE_STR + CSV_QUOTE_STR, CSV_QUOTE_STR);
+ }
+
+ out.write(str);
+ }
+
+}
Fisheye: Tag 1.2 refers to a dead (removed) revision in file `3rdParty_sources/commons-lang/org/apache/commons/lang/StringPrintWriter.java'.
Fisheye: No comparison available. Pass `N' to diff?
Index: 3rdParty_sources/commons-lang/org/apache/commons/lang/StringUtils.java
===================================================================
RCS file: /usr/local/cvsroot/3rdParty_sources/commons-lang/org/apache/commons/lang/StringUtils.java,v
diff -u -r1.1 -r1.2
--- 3rdParty_sources/commons-lang/org/apache/commons/lang/StringUtils.java 30 Aug 2012 16:24:42 -0000 1.1
+++ 3rdParty_sources/commons-lang/org/apache/commons/lang/StringUtils.java 15 Mar 2013 09:52:48 -0000 1.2
@@ -1,86 +1,59 @@
-/* ====================================================================
- * The Apache Software License, Version 1.1
- *
- * Copyright (c) 2002-2003 The Apache Software Foundation. All rights
- * reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in
- * the documentation and/or other materials provided with the
- * distribution.
- *
- * 3. The end-user documentation included with the redistribution, if
- * any, must include the following acknowledgement:
- * "This product includes software developed by the
- * Apache Software Foundation (http://www.apache.org/)."
- * Alternately, this acknowledgement may appear in the software itself,
- * if and wherever such third-party acknowledgements normally appear.
- *
- * 4. The names "The Jakarta Project", "Commons", and "Apache Software
- * Foundation" must not be used to endorse or promote products derived
- * from this software without prior written permission. For written
- * permission, please contact apache@apache.org.
- *
- * 5. Products derived from this software may not be called "Apache"
- * nor may "Apache" appear in their names without prior written
- * permission of the Apache Software Foundation.
- *
- * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
- * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
- * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
- * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- * ====================================================================
- *
- * This software consists of voluntary contributions made by many
- * individuals on behalf of the Apache Software Foundation. For more
- * information on the Apache Software Foundation, please see
- * .
+/*
+ * 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.lang;
import java.util.ArrayList;
+import java.util.Collection;
import java.util.Iterator;
import java.util.List;
+import java.util.Locale;
+import org.apache.commons.lang.text.StrBuilder;
+
/**
- * Operations on {@link java.lang.String} that are
+ *
Operations on {@link java.lang.String} that are
* null
safe.
- *
+ *
*
* - IsEmpty/IsBlank
* - checks if a String contains text
* - Trim/Strip
* - removes leading and trailing whitespace
* - Equals
* - compares two strings null-safe
+ * - startsWith
+ * - check if a String starts with a prefix null-safe
+ * - endsWith
+ * - check if a String ends with a suffix null-safe
* - IndexOf/LastIndexOf/Contains
* - null-safe index-of checks
*
- IndexOfAny/LastIndexOfAny/IndexOfAnyBut/LastIndexOfAnyBut
* - index-of any of a set of Strings
- * - ContainsOnly/ContainsNone
- * - does String contains only/none of these characters
+ * - ContainsOnly/ContainsNone/ContainsAny
+ * - does String contains only/none/any of these characters
* - Substring/Left/Right/Mid
* - null-safe substring extractions
* - SubstringBefore/SubstringAfter/SubstringBetween
* - substring extraction relative to other strings
* - Split/Join
* - splits a String into an array of substrings and vice versa
- * - Replace/Delete/Overlay
+ *
- Remove/Delete
+ * - removes part of a String
+ * - Replace/Overlay
* - Searches a String and replaces one String with another
* - Chomp/Chop
* - removes the last part of a String
@@ -89,8 +62,8 @@
* - UpperCase/LowerCase/SwapCase/Capitalize/Uncapitalize
* - changes the case of a String
* - CountMatches
- * - counts the number of occurrances of one String in another
- * - IsAlpha/IsNumeric/IsWhitespace
+ * - counts the number of occurrences of one String in another
+ * - IsAlpha/IsNumeric/IsWhitespace/IsAsciiPrintable
* - checks the characters in a String
* - DefaultString
* - protects against a null input String
@@ -99,60 +72,65 @@
* - Abbreviate
* - abbreviates a string using ellipsis
* - Difference
- * - compares two Strings and reports on their differences
+ * - compares Strings and reports on their differences
* - LevensteinDistance
* - the number of changes needed to change one String into another
*
*
* The StringUtils
class defines certain words related to
* String handling.
- *
+ *
*
* - null -
null
* - empty - a zero-length string (
""
)
* - space - the space character (
' '
, char 32)
* - whitespace - the characters defined by {@link Character#isWhitespace(char)}
* - trim - the characters <= 32 as in {@link String#trim()}
*
- *
+ *
* StringUtils
handles null
input Strings quietly.
* That is to say that a null
input will return null
.
* Where a boolean
or int
is being returned
* details vary by method.
- *
- * A side effect of the null
handling is that a
+ *
+ *
A side effect of the null
handling is that a
* NullPointerException
should be considered a bug in
* StringUtils
(except for deprecated methods).
- *
+ *
* Methods in this class give sample code to explain their operation.
* The symbol *
is used to indicate any input including null
.
*
+ * #ThreadSafe#
* @see java.lang.String
+ * @author Apache Software Foundation
* @author Apache Jakarta Turbine
- * @author GenerationJavaCore
* @author Jon S. Stevens
- * @author Daniel Rall
+ * @author Daniel L. Rall
* @author Greg Coladonato
- * @author Henri Yandell
* @author Ed Korthof
* @author Rand McNeely
- * @author Stephen Colebourne
* @author Fredrik Westermarck
* @author Holger Krauth
* @author Alexander Day Chaffee
* @author Henning P. Schmiedehausen
* @author Arun Mammen Thomas
* @author Gary Gregory
* @author Phil Steitz
+ * @author Al Chou
+ * @author Michael Davey
+ * @author Reuben Sivan
+ * @author Chris Hyzer
+ * @author Scott Johnson
* @since 1.0
* @version $Id$
*/
+//@Immutable
public class StringUtils {
// Performance testing notes (JDK 1.4, Jul03, scolebourne)
// Whitespace:
// Character.isWhitespace() is faster than WHITESPACE.indexOf()
// where WHITESPACE is a string of all whitespace characters
- //
+ //
// Character access:
// String.charAt(n) versus toCharArray(), then array[n]
// String.charAt(n) is about 15% worse for a 10K string
@@ -163,29 +141,23 @@
// Append:
// String.concat about twice as fast as StringBuffer.append
// (not sure who tested this)
-
+
/**
* The empty String ""
.
* @since 2.0
*/
public static final String EMPTY = "";
-
+
/**
- * The maximum size to which the padding constant(s) can expand.
+ * Represents a failed index search.
+ * @since 2.1
*/
- private static final int PAD_LIMIT = 8192;
+ public static final int INDEX_NOT_FOUND = -1;
/**
- * An array of String
s used for padding.
- *
- * Used for efficient space padding. The length of each String expands as needed.
+ * The maximum size to which the padding constant(s) can expand.
*/
- private static final String[] PADDING = new String[Character.MAX_VALUE];
-
- static {
- // space padding is most common, start with 64 chars
- PADDING[32] = " ";
- }
+ private static final int PAD_LIMIT = 8192;
/**
* StringUtils
instances should NOT be constructed in
@@ -196,13 +168,14 @@
* instance to operate.
*/
public StringUtils() {
+ super();
}
// Empty checks
//-----------------------------------------------------------------------
/**
* Checks if a String is empty ("") or null.
- *
+ *
*
* StringUtils.isEmpty(null) = true
* StringUtils.isEmpty("") = true
@@ -214,17 +187,17 @@
* NOTE: This method changed in Lang version 2.0.
* It no longer trims the String.
* That functionality is available in isBlank().
- *
+ *
* @param str the String to check, may be null
* @return true
if the String is empty or null
*/
public static boolean isEmpty(String str) {
- return (str == null || str.length() == 0);
+ return str == null || str.length() == 0;
}
/**
* Checks if a String is not empty ("") and not null.
- *
+ *
*
* StringUtils.isNotEmpty(null) = false
* StringUtils.isNotEmpty("") = false
@@ -237,12 +210,12 @@
* @return true
if the String is not empty and not null
*/
public static boolean isNotEmpty(String str) {
- return (str != null && str.length() > 0);
+ return !StringUtils.isEmpty(str);
}
/**
* Checks if a String is whitespace, empty ("") or null.
- *
+ *
*
* StringUtils.isBlank(null) = true
* StringUtils.isBlank("") = true
@@ -261,7 +234,7 @@
return true;
}
for (int i = 0; i < strLen; i++) {
- if ((Character.isWhitespace(str.charAt(i)) == false) ) {
+ if ((Character.isWhitespace(str.charAt(i)) == false)) {
return false;
}
}
@@ -270,7 +243,7 @@
/**
* Checks if a String is not empty (""), not null and not whitespace only.
- *
+ *
*
* StringUtils.isNotBlank(null) = false
* StringUtils.isNotBlank("") = false
@@ -280,21 +253,12 @@
*
*
* @param str the String to check, may be null
- * @return true
if the String is
+ * @return true
if the String is
* not empty and not null and not whitespace
* @since 2.0
*/
public static boolean isNotBlank(String str) {
- int strLen;
- if (str == null || (strLen = str.length()) == 0) {
- return false;
- }
- for (int i = 0; i < strLen; i++) {
- if ((Character.isWhitespace(str.charAt(i)) == false) ) {
- return true;
- }
- }
- return false;
+ return !StringUtils.isBlank(str);
}
// Trim
@@ -303,7 +267,7 @@
* Removes control characters (char <= 32) from both
* ends of this String, handling null
by returning
* an empty String ("").
- *
+ *
*
* StringUtils.clean(null) = ""
* StringUtils.clean("") = ""
@@ -319,21 +283,21 @@
* Method will be removed in Commons Lang 3.0.
*/
public static String clean(String str) {
- return (str == null ? EMPTY : str.trim());
+ return str == null ? EMPTY : str.trim();
}
/**
* Removes control characters (char <= 32) from both
* ends of this String, handling null
by returning
* null
.
- *
+ *
* The String is trimmed using {@link String#trim()}.
* Trim removes start and end characters <= 32.
* To strip whitespace use {@link #strip(String)}.
- *
+ *
* To trim your choice of characters, use the
* {@link #strip(String, String)} methods.
- *
+ *
*
* StringUtils.trim(null) = null
* StringUtils.trim("") = ""
@@ -346,71 +310,71 @@
* @return the trimmed string, null
if null String input
*/
public static String trim(String str) {
- return (str == null ? null : str.trim());
+ return str == null ? null : str.trim();
}
- /**
- * Removes control characters (char <= 32) from both
- * ends of this String returning null
if the String is
+ /**
+ *
Removes control characters (char <= 32) from both
+ * ends of this String returning null
if the String is
* empty ("") after the trim or if it is null
.
- *
+ *
*
The String is trimmed using {@link String#trim()}.
* Trim removes start and end characters <= 32.
* To strip whitespace use {@link #stripToNull(String)}.
- *
+ *
*
* StringUtils.trimToNull(null) = null
* StringUtils.trimToNull("") = null
* StringUtils.trimToNull(" ") = null
* StringUtils.trimToNull("abc") = "abc"
* StringUtils.trimToNull(" abc ") = "abc"
*
- *
+ *
* @param str the String to be trimmed, may be null
- * @return the trimmed String,
+ * @return the trimmed String,
* null
if only chars <= 32, empty or null String input
* @since 2.0
*/
public static String trimToNull(String str) {
String ts = trim(str);
- return (ts == null || ts.length() == 0 ? null : ts);
+ return isEmpty(ts) ? null : ts;
}
- /**
- * Removes control characters (char <= 32) from both
+ /**
+ *
Removes control characters (char <= 32) from both
* ends of this String returning an empty String ("") if the String
* is empty ("") after the trim or if it is null
.
- *
+ *
*
The String is trimmed using {@link String#trim()}.
* Trim removes start and end characters <= 32.
* To strip whitespace use {@link #stripToEmpty(String)}.
- *
+ *
*
* StringUtils.trimToEmpty(null) = ""
* StringUtils.trimToEmpty("") = ""
* StringUtils.trimToEmpty(" ") = ""
* StringUtils.trimToEmpty("abc") = "abc"
* StringUtils.trimToEmpty(" abc ") = "abc"
*
- *
+ *
* @param str the String to be trimmed, may be null
* @return the trimmed String, or an empty String if null
input
* @since 2.0
*/
public static String trimToEmpty(String str) {
- return (str == null ? EMPTY : str.trim());
+ return str == null ? EMPTY : str.trim();
}
-
+
// Stripping
//-----------------------------------------------------------------------
/**
* Strips whitespace from the start and end of a String.
- *
+ *
* This is similar to {@link #trim(String)} but removes whitespace.
* Whitespace is defined by {@link Character#isWhitespace(char)}.
- *
+ *
* A null
input String returns null
.
- *
+ *
*
* StringUtils.strip(null) = null
* StringUtils.strip("") = ""
@@ -421,34 +385,34 @@
* StringUtils.strip(" abc ") = "abc"
* StringUtils.strip(" ab c ") = "ab c"
*
- *
+ *
* @param str the String to remove whitespace from, may be null
* @return the stripped String, null
if null String input
*/
public static String strip(String str) {
return strip(str, null);
}
-
- /**
+
+ /**
* Strips whitespace from the start and end of a String returning
* null
if the String is empty ("") after the strip.
- *
+ *
* This is similar to {@link #trimToNull(String)} but removes whitespace.
* Whitespace is defined by {@link Character#isWhitespace(char)}.
- *
+ *
*
- * StringUtils.strip(null) = null
- * StringUtils.strip("") = null
- * StringUtils.strip(" ") = null
- * StringUtils.strip("abc") = "abc"
- * StringUtils.strip(" abc") = "abc"
- * StringUtils.strip("abc ") = "abc"
- * StringUtils.strip(" abc ") = "abc"
- * StringUtils.strip(" ab c ") = "ab c"
+ * StringUtils.stripToNull(null) = null
+ * StringUtils.stripToNull("") = null
+ * StringUtils.stripToNull(" ") = null
+ * StringUtils.stripToNull("abc") = "abc"
+ * StringUtils.stripToNull(" abc") = "abc"
+ * StringUtils.stripToNull("abc ") = "abc"
+ * StringUtils.stripToNull(" abc ") = "abc"
+ * StringUtils.stripToNull(" ab c ") = "ab c"
*
- *
+ *
* @param str the String to be stripped, may be null
- * @return the stripped String,
+ * @return the stripped String,
* null
if whitespace, empty or null String input
* @since 2.0
*/
@@ -457,47 +421,47 @@
return null;
}
str = strip(str, null);
- return (str.length() == 0 ? null : str);
+ return str.length() == 0 ? null : str;
}
- /**
+ /**
* Strips whitespace from the start and end of a String returning
* an empty String if null
input.
- *
+ *
* This is similar to {@link #trimToEmpty(String)} but removes whitespace.
* Whitespace is defined by {@link Character#isWhitespace(char)}.
- *
+ *
*
- * StringUtils.strip(null) = ""
- * StringUtils.strip("") = ""
- * StringUtils.strip(" ") = ""
- * StringUtils.strip("abc") = "abc"
- * StringUtils.strip(" abc") = "abc"
- * StringUtils.strip("abc ") = "abc"
- * StringUtils.strip(" abc ") = "abc"
- * StringUtils.strip(" ab c ") = "ab c"
+ * StringUtils.stripToEmpty(null) = ""
+ * StringUtils.stripToEmpty("") = ""
+ * StringUtils.stripToEmpty(" ") = ""
+ * StringUtils.stripToEmpty("abc") = "abc"
+ * StringUtils.stripToEmpty(" abc") = "abc"
+ * StringUtils.stripToEmpty("abc ") = "abc"
+ * StringUtils.stripToEmpty(" abc ") = "abc"
+ * StringUtils.stripToEmpty(" ab c ") = "ab c"
*
- *
+ *
* @param str the String to be stripped, may be null
* @return the trimmed String, or an empty String if null
input
* @since 2.0
*/
public static String stripToEmpty(String str) {
- return (str == null ? EMPTY : strip(str, null));
+ return str == null ? EMPTY : strip(str, null);
}
-
+
/**
* Strips any of a set of characters from the start and end of a String.
* This is similar to {@link String#trim()} but allows the characters
* to be stripped to be controlled.
*
* A null
input String returns null
.
* An empty string ("") input returns the empty string.
- *
+ *
* If the stripChars String is null
, whitespace is
* stripped as defined by {@link Character#isWhitespace(char)}.
* Alternatively use {@link #strip(String)}.
- *
+ *
*
* StringUtils.strip(null, *) = null
* StringUtils.strip("", *) = ""
@@ -507,13 +471,13 @@
* StringUtils.strip(" abc ", null) = "abc"
* StringUtils.strip(" abcyx", "xyz") = " abc"
*
- *
+ *
* @param str the String to remove characters from, may be null
* @param stripChars the characters to remove, null treated as whitespace
* @return the stripped String, null
if null String input
*/
public static String strip(String str, String stripChars) {
- if (str == null || str.length() == 0) {
+ if (isEmpty(str)) {
return str;
}
str = stripStart(str, stripChars);
@@ -525,10 +489,10 @@
*
* A null
input String returns null
.
* An empty string ("") input returns the empty string.
- *
+ *
* If the stripChars String is null
, whitespace is
* stripped as defined by {@link Character#isWhitespace(char)}.
- *
+ *
*
* StringUtils.stripStart(null, *) = null
* StringUtils.stripStart("", *) = ""
@@ -539,7 +503,7 @@
* StringUtils.stripStart(" abc ", null) = "abc "
* StringUtils.stripStart("yxabc ", "xyz") = "abc "
*
- *
+ *
* @param str the String to remove characters from, may be null
* @param stripChars the characters to remove, null treated as whitespace
* @return the stripped String, null
if null String input
@@ -557,7 +521,7 @@
} else if (stripChars.length() == 0) {
return str;
} else {
- while ((start != strLen) && (stripChars.indexOf(str.charAt(start)) != -1)) {
+ while ((start != strLen) && (stripChars.indexOf(str.charAt(start)) != INDEX_NOT_FOUND)) {
start++;
}
}
@@ -569,10 +533,10 @@
*
* A null
input String returns null
.
* An empty string ("") input returns the empty string.
- *
+ *
* If the stripChars String is null
, whitespace is
* stripped as defined by {@link Character#isWhitespace(char)}.
- *
+ *
*
* StringUtils.stripEnd(null, *) = null
* StringUtils.stripEnd("", *) = ""
@@ -582,26 +546,27 @@
* StringUtils.stripEnd("abc ", null) = "abc"
* StringUtils.stripEnd(" abc ", null) = " abc"
* StringUtils.stripEnd(" abcyx", "xyz") = " abc"
+ * StringUtils.stripEnd("120.00", ".0") = "12"
*
- *
+ *
* @param str the String to remove characters from, may be null
- * @param stripChars the characters to remove, null treated as whitespace
+ * @param stripChars the set of characters to remove, null treated as whitespace
* @return the stripped String, null
if null String input
*/
public static String stripEnd(String str, String stripChars) {
int end;
if (str == null || (end = str.length()) == 0) {
return str;
}
-
+
if (stripChars == null) {
while ((end != 0) && Character.isWhitespace(str.charAt(end - 1))) {
end--;
}
} else if (stripChars.length() == 0) {
return str;
} else {
- while ((end != 0) && (stripChars.indexOf(str.charAt(end - 1)) != -1)) {
+ while ((end != 0) && (stripChars.indexOf(str.charAt(end - 1)) != INDEX_NOT_FOUND)) {
end--;
}
}
@@ -618,21 +583,21 @@
* A null
array will return null
.
* An empty array will return itself.
* A null
array entry will be ignored.
- *
+ *
*
* StringUtils.stripAll(null) = null
* StringUtils.stripAll([]) = []
* StringUtils.stripAll(["abc", " abc"]) = ["abc", "abc"]
* StringUtils.stripAll(["abc ", null]) = ["abc", null]
*
- *
+ *
* @param strs the array to remove whitespace from, may be null
* @return the stripped Strings, null
if null array input
*/
public static String[] stripAll(String[] strs) {
return stripAll(strs, null);
}
-
+
/**
* Strips any of a set of characters from the start and end of every
* String in an array.
@@ -644,7 +609,7 @@
* A null
array entry will be ignored.
* A null
stripChars will strip whitespace as defined by
* {@link Character#isWhitespace(char)}.
- *
+ *
*
* StringUtils.stripAll(null, *) = null
* StringUtils.stripAll([], *) = []
@@ -653,7 +618,7 @@
* StringUtils.stripAll(["abc ", null], "yz") = ["abc ", null]
* StringUtils.stripAll(["yabcz", null], "yz") = ["abc", null]
*
- *
+ *
* @param strs the array to remove characters from, may be null
* @param stripChars the characters to remove, null treated as whitespace
* @return the stripped Strings, null
if null array input
@@ -668,7 +633,7 @@
newArr[i] = strip(strs[i], stripChars);
}
return newArr;
- }
+ }
// Equals
//-----------------------------------------------------------------------
@@ -685,15 +650,15 @@
* StringUtils.equals("abc", "abc") = true
* StringUtils.equals("abc", "ABC") = false
*
- *
+ *
* @see java.lang.String#equals(Object)
* @param str1 the first String, may be null
* @param str2 the second String, may be null
* @return true
if the Strings are equal, case sensitive, or
* both null
*/
public static boolean equals(String str1, String str2) {
- return (str1 == null ? str2 == null : str1.equals(str2));
+ return str1 == null ? str2 == null : str1.equals(str2);
}
/**
@@ -710,15 +675,15 @@
* StringUtils.equalsIgnoreCase("abc", "abc") = true
* StringUtils.equalsIgnoreCase("abc", "ABC") = true
*
- *
+ *
* @see java.lang.String#equalsIgnoreCase(String)
* @param str1 the first String, may be null
* @param str2 the second String, may be null
* @return true
if the Strings are equal, case insensitive, or
* both null
*/
public static boolean equalsIgnoreCase(String str1, String str2) {
- return (str1 == null ? str2 == null : str1.equalsIgnoreCase(str2));
+ return str1 == null ? str2 == null : str1.equalsIgnoreCase(str2);
}
// IndexOf
@@ -727,37 +692,37 @@
* Finds the first index within a String, handling null
.
* This method uses {@link String#indexOf(int)}.
*
- * A null
or empty ("") String will return -1
.
- *
+ * A null
or empty ("") String will return INDEX_NOT_FOUND (-1)
.
+ *
*
* StringUtils.indexOf(null, *) = -1
* StringUtils.indexOf("", *) = -1
* StringUtils.indexOf("aabaabaa", 'a') = 0
* StringUtils.indexOf("aabaabaa", 'b') = 2
*
- *
+ *
* @param str the String to check, may be null
* @param searchChar the character to find
- * @return the first index of the search character,
+ * @return the first index of the search character,
* -1 if no match or null
string input
* @since 2.0
*/
public static int indexOf(String str, char searchChar) {
- if (str == null || str.length() == 0) {
- return -1;
+ if (isEmpty(str)) {
+ return INDEX_NOT_FOUND;
}
return str.indexOf(searchChar);
}
-
+
/**
* Finds the first index within a String from a start position,
* handling null
.
* This method uses {@link String#indexOf(int, int)}.
*
- * A null
or empty ("") String will return -1
.
+ *
A null
or empty ("") String will return (INDEX_NOT_FOUND) -1
.
* A negative start position is treated as zero.
* A start position greater than the string length returns -1
.
- *
+ *
*
* StringUtils.indexOf(null, *, *) = -1
* StringUtils.indexOf("", *, *) = -1
@@ -766,37 +731,38 @@
* StringUtils.indexOf("aabaabaa", 'b', 9) = -1
* StringUtils.indexOf("aabaabaa", 'b', -1) = 2
*
- *
+ *
* @param str the String to check, may be null
* @param searchChar the character to find
* @param startPos the start position, negative treated as zero
- * @return the first index of the search character,
+ * @return the first index of the search character,
* -1 if no match or null
string input
* @since 2.0
*/
public static int indexOf(String str, char searchChar, int startPos) {
- if (str == null || str.length() == 0) {
- return -1;
+ if (isEmpty(str)) {
+ return INDEX_NOT_FOUND;
}
return str.indexOf(searchChar, startPos);
}
-
+
/**
* Finds the first index within a String, handling null
.
* This method uses {@link String#indexOf(String)}.
*
* A null
String will return -1
.
- *
+ *
*
* StringUtils.indexOf(null, *) = -1
* StringUtils.indexOf(*, null) = -1
* StringUtils.indexOf("", "") = 0
+ * StringUtils.indexOf("", *) = -1 (except when * = "")
* StringUtils.indexOf("aabaabaa", "a") = 0
* StringUtils.indexOf("aabaabaa", "b") = 2
* StringUtils.indexOf("aabaabaa", "ab") = 1
* StringUtils.indexOf("aabaabaa", "") = 0
*
- *
+ *
* @param str the String to check, may be null
* @param searchStr the String to find, may be null
* @return the first index of the search String,
@@ -805,12 +771,86 @@
*/
public static int indexOf(String str, String searchStr) {
if (str == null || searchStr == null) {
- return -1;
+ return INDEX_NOT_FOUND;
}
return str.indexOf(searchStr);
}
-
+
/**
+ * Finds the n-th index within a String, handling null
.
+ * This method uses {@link String#indexOf(String)}.
+ *
+ * A null
String will return -1
.
+ *
+ *
+ * StringUtils.ordinalIndexOf(null, *, *) = -1
+ * StringUtils.ordinalIndexOf(*, null, *) = -1
+ * StringUtils.ordinalIndexOf("", "", *) = 0
+ * StringUtils.ordinalIndexOf("aabaabaa", "a", 1) = 0
+ * StringUtils.ordinalIndexOf("aabaabaa", "a", 2) = 1
+ * StringUtils.ordinalIndexOf("aabaabaa", "b", 1) = 2
+ * StringUtils.ordinalIndexOf("aabaabaa", "b", 2) = 5
+ * StringUtils.ordinalIndexOf("aabaabaa", "ab", 1) = 1
+ * StringUtils.ordinalIndexOf("aabaabaa", "ab", 2) = 4
+ * StringUtils.ordinalIndexOf("aabaabaa", "", 1) = 0
+ * StringUtils.ordinalIndexOf("aabaabaa", "", 2) = 0
+ *
+ *
+ * Note that 'head(String str, int n)' may be implemented as:
+ *
+ *
+ * str.substring(0, lastOrdinalIndexOf(str, "\n", n))
+ *
+ *
+ * @param str the String to check, may be null
+ * @param searchStr the String to find, may be null
+ * @param ordinal the n-th searchStr
to find
+ * @return the n-th index of the search String,
+ * -1
(INDEX_NOT_FOUND
) if no match or null
string input
+ * @since 2.1
+ */
+ public static int ordinalIndexOf(String str, String searchStr, int ordinal) {
+ return ordinalIndexOf(str, searchStr, ordinal, false);
+ }
+
+ /**
+ * Finds the n-th index within a String, handling null
.
+ * This method uses {@link String#indexOf(String)}.
+ *
+ * A null
String will return -1
.
+ *
+ * @param str the String to check, may be null
+ * @param searchStr the String to find, may be null
+ * @param ordinal the n-th searchStr
to find
+ * @param lastIndex true if lastOrdinalIndexOf() otherwise false if ordinalIndexOf()
+ * @return the n-th index of the search String,
+ * -1
(INDEX_NOT_FOUND
) if no match or null
string input
+ */
+ // Shared code between ordinalIndexOf(String,String,int) and lastOrdinalIndexOf(String,String,int)
+ private static int ordinalIndexOf(String str, String searchStr, int ordinal, boolean lastIndex) {
+ if (str == null || searchStr == null || ordinal <= 0) {
+ return INDEX_NOT_FOUND;
+ }
+ if (searchStr.length() == 0) {
+ return lastIndex ? str.length() : 0;
+ }
+ int found = 0;
+ int index = lastIndex ? str.length() : INDEX_NOT_FOUND;
+ do {
+ if(lastIndex) {
+ index = str.lastIndexOf(searchStr, index - 1);
+ } else {
+ index = str.indexOf(searchStr, index + 1);
+ }
+ if (index < 0) {
+ return index;
+ }
+ found++;
+ } while (found < ordinal);
+ return index;
+ }
+
+ /**
* Finds the first index within a String, handling null
.
* This method uses {@link String#indexOf(String, int)}.
*
@@ -819,11 +859,12 @@
* An empty ("") search String always matches.
* A start position greater than the string length only matches
* an empty search String.
- *
+ *
*
* StringUtils.indexOf(null, *, *) = -1
* StringUtils.indexOf(*, null, *) = -1
* StringUtils.indexOf("", "", 0) = 0
+ * StringUtils.indexOf("", *, 0) = -1 (except when * = "")
* StringUtils.indexOf("aabaabaa", "a", 0) = 0
* StringUtils.indexOf("aabaabaa", "b", 0) = 2
* StringUtils.indexOf("aabaabaa", "ab", 0) = 1
@@ -833,7 +874,7 @@
* StringUtils.indexOf("aabaabaa", "", 2) = 2
* StringUtils.indexOf("abc", "", 9) = 3
*
- *
+ *
* @param str the String to check, may be null
* @param searchStr the String to find, may be null
* @param startPos the start position, negative treated as zero
@@ -843,43 +884,124 @@
*/
public static int indexOf(String str, String searchStr, int startPos) {
if (str == null || searchStr == null) {
- return -1;
+ return INDEX_NOT_FOUND;
}
// JDK1.2/JDK1.3 have a bug, when startPos > str.length for "", hence
if (searchStr.length() == 0 && startPos >= str.length()) {
return str.length();
}
return str.indexOf(searchStr, startPos);
}
-
+
+ /**
+ * Case in-sensitive find of the first index within a String.
+ *
+ * A null
String will return -1
.
+ * A negative start position is treated as zero.
+ * An empty ("") search String always matches.
+ * A start position greater than the string length only matches
+ * an empty search String.
+ *
+ *
+ * StringUtils.indexOfIgnoreCase(null, *) = -1
+ * StringUtils.indexOfIgnoreCase(*, null) = -1
+ * StringUtils.indexOfIgnoreCase("", "") = 0
+ * StringUtils.indexOfIgnoreCase("aabaabaa", "a") = 0
+ * StringUtils.indexOfIgnoreCase("aabaabaa", "b") = 2
+ * StringUtils.indexOfIgnoreCase("aabaabaa", "ab") = 1
+ *
+ *
+ * @param str the String to check, may be null
+ * @param searchStr the String to find, may be null
+ * @return the first index of the search String,
+ * -1 if no match or null
string input
+ * @since 2.5
+ */
+ public static int indexOfIgnoreCase(String str, String searchStr) {
+ return indexOfIgnoreCase(str, searchStr, 0);
+ }
+
+ /**
+ * Case in-sensitive find of the first index within a String
+ * from the specified position.
+ *
+ * A null
String will return -1
.
+ * A negative start position is treated as zero.
+ * An empty ("") search String always matches.
+ * A start position greater than the string length only matches
+ * an empty search String.
+ *
+ *
+ * StringUtils.indexOfIgnoreCase(null, *, *) = -1
+ * StringUtils.indexOfIgnoreCase(*, null, *) = -1
+ * StringUtils.indexOfIgnoreCase("", "", 0) = 0
+ * StringUtils.indexOfIgnoreCase("aabaabaa", "A", 0) = 0
+ * StringUtils.indexOfIgnoreCase("aabaabaa", "B", 0) = 2
+ * StringUtils.indexOfIgnoreCase("aabaabaa", "AB", 0) = 1
+ * StringUtils.indexOfIgnoreCase("aabaabaa", "B", 3) = 5
+ * StringUtils.indexOfIgnoreCase("aabaabaa", "B", 9) = -1
+ * StringUtils.indexOfIgnoreCase("aabaabaa", "B", -1) = 2
+ * StringUtils.indexOfIgnoreCase("aabaabaa", "", 2) = 2
+ * StringUtils.indexOfIgnoreCase("abc", "", 9) = 3
+ *
+ *
+ * @param str the String to check, may be null
+ * @param searchStr the String to find, may be null
+ * @param startPos the start position, negative treated as zero
+ * @return the first index of the search String,
+ * -1 if no match or null
string input
+ * @since 2.5
+ */
+ public static int indexOfIgnoreCase(String str, String searchStr, int startPos) {
+ if (str == null || searchStr == null) {
+ return INDEX_NOT_FOUND;
+ }
+ if (startPos < 0) {
+ startPos = 0;
+ }
+ int endLimit = (str.length() - searchStr.length()) + 1;
+ if (startPos > endLimit) {
+ return INDEX_NOT_FOUND;
+ }
+ if (searchStr.length() == 0) {
+ return startPos;
+ }
+ for (int i = startPos; i < endLimit; i++) {
+ if (str.regionMatches(true, i, searchStr, 0, searchStr.length())) {
+ return i;
+ }
+ }
+ return INDEX_NOT_FOUND;
+ }
+
// LastIndexOf
//-----------------------------------------------------------------------
/**
* Finds the last index within a String, handling null
.
* This method uses {@link String#lastIndexOf(int)}.
*
* A null
or empty ("") String will return -1
.
- *
+ *
*
* StringUtils.lastIndexOf(null, *) = -1
* StringUtils.lastIndexOf("", *) = -1
* StringUtils.lastIndexOf("aabaabaa", 'a') = 7
* StringUtils.lastIndexOf("aabaabaa", 'b') = 5
*
- *
+ *
* @param str the String to check, may be null
* @param searchChar the character to find
- * @return the last index of the search character,
+ * @return the last index of the search character,
* -1 if no match or null
string input
* @since 2.0
*/
public static int lastIndexOf(String str, char searchChar) {
- if (str == null || str.length() == 0) {
- return -1;
+ if (isEmpty(str)) {
+ return INDEX_NOT_FOUND;
}
return str.lastIndexOf(searchChar);
}
-
+
/**
* Finds the last index within a String from a start position,
* handling null
.
@@ -888,7 +1010,7 @@
*
A null
or empty ("") String will return -1
.
* A negative start position returns -1
.
* A start position greater than the string length searches the whole string.
- *
+ *
*
* StringUtils.lastIndexOf(null, *, *) = -1
* StringUtils.lastIndexOf("", *, *) = -1
@@ -899,37 +1021,37 @@
* StringUtils.lastIndexOf("aabaabaa", 'b', -1) = -1
* StringUtils.lastIndexOf("aabaabaa", 'a', 0) = 0
*
- *
+ *
* @param str the String to check, may be null
* @param searchChar the character to find
* @param startPos the start position
- * @return the last index of the search character,
+ * @return the last index of the search character,
* -1 if no match or null
string input
* @since 2.0
*/
public static int lastIndexOf(String str, char searchChar, int startPos) {
- if (str == null || str.length() == 0) {
- return -1;
+ if (isEmpty(str)) {
+ return INDEX_NOT_FOUND;
}
return str.lastIndexOf(searchChar, startPos);
}
-
+
/**
* Finds the last index within a String, handling null
.
* This method uses {@link String#lastIndexOf(String)}.
*
* A null
String will return -1
.
- *
+ *
*
* StringUtils.lastIndexOf(null, *) = -1
* StringUtils.lastIndexOf(*, null) = -1
* StringUtils.lastIndexOf("", "") = 0
- * StringUtils.lastIndexOf("aabaabaa", "a") = 0
- * StringUtils.lastIndexOf("aabaabaa", "b") = 2
- * StringUtils.lastIndexOf("aabaabaa", "ab") = 1
+ * StringUtils.lastIndexOf("aabaabaa", "a") = 7
+ * StringUtils.lastIndexOf("aabaabaa", "b") = 5
+ * StringUtils.lastIndexOf("aabaabaa", "ab") = 4
* StringUtils.lastIndexOf("aabaabaa", "") = 8
*
- *
+ *
* @param str the String to check, may be null
* @param searchStr the String to find, may be null
* @return the last index of the search String,
@@ -938,20 +1060,57 @@
*/
public static int lastIndexOf(String str, String searchStr) {
if (str == null || searchStr == null) {
- return -1;
+ return INDEX_NOT_FOUND;
}
return str.lastIndexOf(searchStr);
}
-
+
/**
+ * Finds the n-th last index within a String, handling null
.
+ * This method uses {@link String#lastIndexOf(String)}.
+ *
+ * A null
String will return -1
.
+ *
+ *
+ * StringUtils.lastOrdinalIndexOf(null, *, *) = -1
+ * StringUtils.lastOrdinalIndexOf(*, null, *) = -1
+ * StringUtils.lastOrdinalIndexOf("", "", *) = 0
+ * StringUtils.lastOrdinalIndexOf("aabaabaa", "a", 1) = 7
+ * StringUtils.lastOrdinalIndexOf("aabaabaa", "a", 2) = 6
+ * StringUtils.lastOrdinalIndexOf("aabaabaa", "b", 1) = 5
+ * StringUtils.lastOrdinalIndexOf("aabaabaa", "b", 2) = 2
+ * StringUtils.lastOrdinalIndexOf("aabaabaa", "ab", 1) = 4
+ * StringUtils.lastOrdinalIndexOf("aabaabaa", "ab", 2) = 1
+ * StringUtils.lastOrdinalIndexOf("aabaabaa", "", 1) = 8
+ * StringUtils.lastOrdinalIndexOf("aabaabaa", "", 2) = 8
+ *
+ *
+ * Note that 'tail(String str, int n)' may be implemented as:
+ *
+ *
+ * str.substring(lastOrdinalIndexOf(str, "\n", n) + 1)
+ *
+ *
+ * @param str the String to check, may be null
+ * @param searchStr the String to find, may be null
+ * @param ordinal the n-th last searchStr
to find
+ * @return the n-th last index of the search String,
+ * -1
(INDEX_NOT_FOUND
) if no match or null
string input
+ * @since 2.5
+ */
+ public static int lastOrdinalIndexOf(String str, String searchStr, int ordinal) {
+ return ordinalIndexOf(str, searchStr, ordinal, true);
+ }
+
+ /**
* Finds the first index within a String, handling null
.
* This method uses {@link String#lastIndexOf(String, int)}.
*
* A null
String will return -1
.
* A negative start position returns -1
.
* An empty ("") search String always matches unless the start position is negative.
* A start position greater than the string length searches the whole string.
- *
+ *
*
* StringUtils.lastIndexOf(null, *, *) = -1
* StringUtils.lastIndexOf(*, null, *) = -1
@@ -963,7 +1122,7 @@
* StringUtils.lastIndexOf("aabaabaa", "a", 0) = 0
* StringUtils.lastIndexOf("aabaabaa", "b", 0) = -1
*
- *
+ *
* @param str the String to check, may be null
* @param searchStr the String to find, may be null
* @param startPos the start position, negative treated as zero
@@ -973,45 +1132,124 @@
*/
public static int lastIndexOf(String str, String searchStr, int startPos) {
if (str == null || searchStr == null) {
- return -1;
+ return INDEX_NOT_FOUND;
}
return str.lastIndexOf(searchStr, startPos);
}
-
+
+ /**
+ * Case in-sensitive find of the last index within a String.
+ *
+ * A null
String will return -1
.
+ * A negative start position returns -1
.
+ * An empty ("") search String always matches unless the start position is negative.
+ * A start position greater than the string length searches the whole string.
+ *
+ *
+ * StringUtils.lastIndexOfIgnoreCase(null, *) = -1
+ * StringUtils.lastIndexOfIgnoreCase(*, null) = -1
+ * StringUtils.lastIndexOfIgnoreCase("aabaabaa", "A") = 7
+ * StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B") = 5
+ * StringUtils.lastIndexOfIgnoreCase("aabaabaa", "AB") = 4
+ *
+ *
+ * @param str the String to check, may be null
+ * @param searchStr the String to find, may be null
+ * @return the first index of the search String,
+ * -1 if no match or null
string input
+ * @since 2.5
+ */
+ public static int lastIndexOfIgnoreCase(String str, String searchStr) {
+ if (str == null || searchStr == null) {
+ return INDEX_NOT_FOUND;
+ }
+ return lastIndexOfIgnoreCase(str, searchStr, str.length());
+ }
+
+ /**
+ * Case in-sensitive find of the last index within a String
+ * from the specified position.
+ *
+ * A null
String will return -1
.
+ * A negative start position returns -1
.
+ * An empty ("") search String always matches unless the start position is negative.
+ * A start position greater than the string length searches the whole string.
+ *
+ *
+ * StringUtils.lastIndexOfIgnoreCase(null, *, *) = -1
+ * StringUtils.lastIndexOfIgnoreCase(*, null, *) = -1
+ * StringUtils.lastIndexOfIgnoreCase("aabaabaa", "A", 8) = 7
+ * StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B", 8) = 5
+ * StringUtils.lastIndexOfIgnoreCase("aabaabaa", "AB", 8) = 4
+ * StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B", 9) = 5
+ * StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B", -1) = -1
+ * StringUtils.lastIndexOfIgnoreCase("aabaabaa", "A", 0) = 0
+ * StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B", 0) = -1
+ *
+ *
+ * @param str the String to check, may be null
+ * @param searchStr the String to find, may be null
+ * @param startPos the start position
+ * @return the first index of the search String,
+ * -1 if no match or null
string input
+ * @since 2.5
+ */
+ public static int lastIndexOfIgnoreCase(String str, String searchStr, int startPos) {
+ if (str == null || searchStr == null) {
+ return INDEX_NOT_FOUND;
+ }
+ if (startPos > (str.length() - searchStr.length())) {
+ startPos = str.length() - searchStr.length();
+ }
+ if (startPos < 0) {
+ return INDEX_NOT_FOUND;
+ }
+ if (searchStr.length() == 0) {
+ return startPos;
+ }
+
+ for (int i = startPos; i >= 0; i--) {
+ if (str.regionMatches(true, i, searchStr, 0, searchStr.length())) {
+ return i;
+ }
+ }
+ return INDEX_NOT_FOUND;
+ }
+
// Contains
//-----------------------------------------------------------------------
/**
* Checks if String contains a search character, handling null
.
* This method uses {@link String#indexOf(int)}.
*
* A null
or empty ("") String will return false
.
- *
+ *
*
* StringUtils.contains(null, *) = false
* StringUtils.contains("", *) = false
* StringUtils.contains("abc", 'a') = true
* StringUtils.contains("abc", 'z') = false
*
- *
+ *
* @param str the String to check, may be null
* @param searchChar the character to find
- * @return true if the String contains the search character,
+ * @return true if the String contains the search character,
* false if not or null
string input
* @since 2.0
*/
public static boolean contains(String str, char searchChar) {
- if (str == null || str.length() == 0) {
+ if (isEmpty(str)) {
return false;
}
- return (str.indexOf(searchChar) >= 0);
+ return str.indexOf(searchChar) >= 0;
}
-
+
/**
- * Find the first index within a String, handling null
.
- * This method uses {@link String#indexOf(int)}.
+ * Checks if String contains a search String, handling null
.
+ * This method uses {@link String#indexOf(String)}.
*
* A null
String will return false
.
- *
+ *
*
* StringUtils.contains(null, *) = false
* StringUtils.contains(*, null) = false
@@ -1020,20 +1258,57 @@
* StringUtils.contains("abc", "a") = true
* StringUtils.contains("abc", "z") = false
*
- *
+ *
* @param str the String to check, may be null
* @param searchStr the String to find, may be null
- * @return true if the String contains the search character,
+ * @return true if the String contains the search String,
* false if not or null
string input
* @since 2.0
*/
public static boolean contains(String str, String searchStr) {
if (str == null || searchStr == null) {
return false;
}
- return (str.indexOf(searchStr) >= 0);
+ return str.indexOf(searchStr) >= 0;
}
-
+
+ /**
+ * Checks if String contains a search String irrespective of case,
+ * handling null
. Case-insensitivity is defined as by
+ * {@link String#equalsIgnoreCase(String)}.
+ *
+ *
A null
String will return false
.
+ *
+ *
+ * StringUtils.contains(null, *) = false
+ * StringUtils.contains(*, null) = false
+ * StringUtils.contains("", "") = true
+ * StringUtils.contains("abc", "") = true
+ * StringUtils.contains("abc", "a") = true
+ * StringUtils.contains("abc", "z") = false
+ * StringUtils.contains("abc", "A") = true
+ * StringUtils.contains("abc", "Z") = false
+ *
+ *
+ * @param str the String to check, may be null
+ * @param searchStr the String to find, may be null
+ * @return true if the String contains the search String irrespective of
+ * case or false if not or null
string input
+ */
+ public static boolean containsIgnoreCase(String str, String searchStr) {
+ if (str == null || searchStr == null) {
+ return false;
+ }
+ int len = searchStr.length();
+ int max = str.length() - len;
+ for (int i = 0; i <= max; i++) {
+ if (str.regionMatches(true, i, searchStr, 0, len)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
// IndexOfAny chars
//-----------------------------------------------------------------------
/**
@@ -1042,7 +1317,7 @@
*
* A null
String will return -1
.
* A null
or zero length search array will return -1
.
- *
+ *
*
* StringUtils.indexOfAny(null, *) = -1
* StringUtils.indexOfAny("", *) = -1
@@ -1052,34 +1327,45 @@
* StringUtils.indexOfAny("zzabyycdxx",['b','y']) = 3
* StringUtils.indexOfAny("aba", ['z']) = -1
*
- *
+ *
* @param str the String to check, may be null
* @param searchChars the chars to search for, may be null
* @return the index of any of the chars, -1 if no match or null input
* @since 2.0
*/
- public static int indexOfAny(String str, char[] searchChars) {
- if (str == null || str.length() == 0 || searchChars == null || searchChars.length == 0) {
- return -1;
- }
- for (int i = 0; i < str.length(); i ++) {
- char ch = str.charAt(i);
- for (int j = 0; j < searchChars.length; j++) {
- if (searchChars[j] == ch) {
- return i;
- }
- }
- }
- return -1;
- }
+ public static int indexOfAny(String str, char[] searchChars) {
+ if (isEmpty(str) || ArrayUtils.isEmpty(searchChars)) {
+ return INDEX_NOT_FOUND;
+ }
+ int csLen = str.length();
+ int csLast = csLen - 1;
+ int searchLen = searchChars.length;
+ int searchLast = searchLen - 1;
+ for (int i = 0; i < csLen; i++) {
+ char ch = str.charAt(i);
+ for (int j = 0; j < searchLen; j++) {
+ if (searchChars[j] == ch) {
+ if (i < csLast && j < searchLast && CharUtils.isHighSurrogate(ch)) {
+ // ch is a supplementary character
+ if (searchChars[j + 1] == str.charAt(i + 1)) {
+ return i;
+ }
+ } else {
+ return i;
+ }
+ }
+ }
+ }
+ return INDEX_NOT_FOUND;
+ }
/**
* Search a String to find the first index of any
* character in the given set of characters.
*
* A null
String will return -1
.
* A null
search string will return -1
.
- *
+ *
*
* StringUtils.indexOfAny(null, *) = -1
* StringUtils.indexOfAny("", *) = -1
@@ -1089,19 +1375,108 @@
* StringUtils.indexOfAny("zzabyycdxx", "by") = 3
* StringUtils.indexOfAny("aba","z") = -1
*
- *
+ *
* @param str the String to check, may be null
* @param searchChars the chars to search for, may be null
* @return the index of any of the chars, -1 if no match or null input
* @since 2.0
*/
public static int indexOfAny(String str, String searchChars) {
- if (str == null || str.length() == 0 || searchChars == null || searchChars.length() == 0) {
- return -1;
+ if (isEmpty(str) || isEmpty(searchChars)) {
+ return INDEX_NOT_FOUND;
}
return indexOfAny(str, searchChars.toCharArray());
}
+ // ContainsAny
+ //-----------------------------------------------------------------------
+ /**
+ * Checks if the String contains any character in the given
+ * set of characters.
+ *
+ * A null
String will return false
.
+ * A null
or zero length search array will return false
.
+ *
+ *
+ * StringUtils.containsAny(null, *) = false
+ * StringUtils.containsAny("", *) = false
+ * StringUtils.containsAny(*, null) = false
+ * StringUtils.containsAny(*, []) = false
+ * StringUtils.containsAny("zzabyycdxx",['z','a']) = true
+ * StringUtils.containsAny("zzabyycdxx",['b','y']) = true
+ * StringUtils.containsAny("aba", ['z']) = false
+ *
+ *
+ * @param str the String to check, may be null
+ * @param searchChars the chars to search for, may be null
+ * @return the true
if any of the chars are found,
+ * false
if no match or null input
+ * @since 2.4
+ */
+ public static boolean containsAny(String str, char[] searchChars) {
+ if (isEmpty(str) || ArrayUtils.isEmpty(searchChars)) {
+ return false;
+ }
+ int csLength = str.length();
+ int searchLength = searchChars.length;
+ int csLast = csLength - 1;
+ int searchLast = searchLength - 1;
+ for (int i = 0; i < csLength; i++) {
+ char ch = str.charAt(i);
+ for (int j = 0; j < searchLength; j++) {
+ if (searchChars[j] == ch) {
+ if (CharUtils.isHighSurrogate(ch)) {
+ if (j == searchLast) {
+ // missing low surrogate, fine, like String.indexOf(String)
+ return true;
+ }
+ if (i < csLast && searchChars[j + 1] == str.charAt(i + 1)) {
+ return true;
+ }
+ } else {
+ // ch is in the Basic Multilingual Plane
+ return true;
+ }
+ }
+ }
+ }
+ return false;
+ }
+
+ /**
+ *
+ * Checks if the String contains any character in the given set of characters.
+ *
+ *
+ *
+ * A null
String will return false
. A null
search string will return
+ * false
.
+ *
+ *
+ *
+ * StringUtils.containsAny(null, *) = false
+ * StringUtils.containsAny("", *) = false
+ * StringUtils.containsAny(*, null) = false
+ * StringUtils.containsAny(*, "") = false
+ * StringUtils.containsAny("zzabyycdxx", "za") = true
+ * StringUtils.containsAny("zzabyycdxx", "by") = true
+ * StringUtils.containsAny("aba","z") = false
+ *
+ *
+ * @param str
+ * the String to check, may be null
+ * @param searchChars
+ * the chars to search for, may be null
+ * @return the true
if any of the chars are found, false
if no match or null input
+ * @since 2.4
+ */
+ public static boolean containsAny(String str, String searchChars) {
+ if (searchChars == null) {
+ return false;
+ }
+ return containsAny(str, searchChars.toCharArray());
+ }
+
// IndexOfAnyBut chars
//-----------------------------------------------------------------------
/**
@@ -1110,70 +1485,91 @@
*
* A null
String will return -1
.
* A null
or zero length search array will return -1
.
- *
+ *
*
- * StringUtils.indexOfAnyBut(null, *) = -1
- * StringUtils.indexOfAnyBut("", *) = -1
- * StringUtils.indexOfAnyBut(*, null) = -1
- * StringUtils.indexOfAnyBut(*, []) = -1
- * StringUtils.indexOfAnyBut("zzabyycdxx",'za') = 3
- * StringUtils.indexOfAnyBut("zzabyycdxx", '') = 0
- * StringUtils.indexOfAnyBut("aba", 'ab') = -1
+ * StringUtils.indexOfAnyBut(null, *) = -1
+ * StringUtils.indexOfAnyBut("", *) = -1
+ * StringUtils.indexOfAnyBut(*, null) = -1
+ * StringUtils.indexOfAnyBut(*, []) = -1
+ * StringUtils.indexOfAnyBut("zzabyycdxx", new char[] {'z', 'a'} ) = 3
+ * StringUtils.indexOfAnyBut("aba", new char[] {'z'} ) = 0
+ * StringUtils.indexOfAnyBut("aba", new char[] {'a', 'b'} ) = -1
*
- *
+ *
* @param str the String to check, may be null
* @param searchChars the chars to search for, may be null
* @return the index of any of the chars, -1 if no match or null input
* @since 2.0
*/
- public static int indexOfAnyBut(String str, char[] searchChars) {
- if (str == null || str.length() == 0 || searchChars == null || searchChars.length == 0) {
- return -1;
- }
- outer: for (int i = 0; i < str.length(); i ++) {
- char ch = str.charAt(i);
- for (int j = 0; j < searchChars.length; j++) {
- if (searchChars[j] == ch) {
- continue outer;
- }
- }
- return i;
- }
- return -1;
- }
+ public static int indexOfAnyBut(String str, char[] searchChars) {
+ if (isEmpty(str) || ArrayUtils.isEmpty(searchChars)) {
+ return INDEX_NOT_FOUND;
+ }
+ int csLen = str.length();
+ int csLast = csLen - 1;
+ int searchLen = searchChars.length;
+ int searchLast = searchLen - 1;
+ outer:
+ for (int i = 0; i < csLen; i++) {
+ char ch = str.charAt(i);
+ for (int j = 0; j < searchLen; j++) {
+ if (searchChars[j] == ch) {
+ if (i < csLast && j < searchLast && CharUtils.isHighSurrogate(ch)) {
+ if (searchChars[j + 1] == str.charAt(i + 1)) {
+ continue outer;
+ }
+ } else {
+ continue outer;
+ }
+ }
+ }
+ return i;
+ }
+ return INDEX_NOT_FOUND;
+ }
/**
* Search a String to find the first index of any
* character not in the given set of characters.
*
* A null
String will return -1
.
- * A null
search string will return -1
.
- *
+ * A null
or empty search string will return -1
.
+ *
*
* StringUtils.indexOfAnyBut(null, *) = -1
* StringUtils.indexOfAnyBut("", *) = -1
* StringUtils.indexOfAnyBut(*, null) = -1
* StringUtils.indexOfAnyBut(*, "") = -1
* StringUtils.indexOfAnyBut("zzabyycdxx", "za") = 3
- * StringUtils.indexOfAnyBut("zzabyycdxx", "") = 0
+ * StringUtils.indexOfAnyBut("zzabyycdxx", "") = -1
* StringUtils.indexOfAnyBut("aba","ab") = -1
*
- *
+ *
* @param str the String to check, may be null
* @param searchChars the chars to search for, may be null
* @return the index of any of the chars, -1 if no match or null input
* @since 2.0
*/
public static int indexOfAnyBut(String str, String searchChars) {
- if (str == null || str.length() == 0 || searchChars == null || searchChars.length() == 0) {
- return -1;
+ if (isEmpty(str) || isEmpty(searchChars)) {
+ return INDEX_NOT_FOUND;
}
- for (int i = 0; i < str.length(); i++) {
- if (searchChars.indexOf(str.charAt(i)) < 0) {
- return i;
+ int strLen = str.length();
+ for (int i = 0; i < strLen; i++) {
+ char ch = str.charAt(i);
+ boolean chFound = searchChars.indexOf(ch) >= 0;
+ if (i + 1 < strLen && CharUtils.isHighSurrogate(ch)) {
+ char ch2 = str.charAt(i + 1);
+ if (chFound && searchChars.indexOf(ch2) < 0) {
+ return i;
+ }
+ } else {
+ if (!chFound) {
+ return i;
+ }
}
}
- return -1;
+ return INDEX_NOT_FOUND;
}
// ContainsOnly
@@ -1183,7 +1579,7 @@
*
* A null
String will return false
.
* A null
valid character array will return false
.
- * An empty String ("") always returns true
.
+ * An empty String (length()=0) always returns true
.
*
*
* StringUtils.containsOnly(null, *) = false
@@ -1194,14 +1590,14 @@
* StringUtils.containsOnly("ab1", 'abc') = false
* StringUtils.containsOnly("abz", 'abc') = false
*
- *
+ *
* @param str the String to check, may be null
* @param valid an array of valid chars, may be null
* @return true if it only contains valid chars and is non-null
*/
public static boolean containsOnly(String str, char[] valid) {
// All these pre-checks are to maintain API with an older version
- if ( (valid == null) || (str == null) ) {
+ if ((valid == null) || (str == null)) {
return false;
}
if (str.length() == 0) {
@@ -1210,15 +1606,15 @@
if (valid.length == 0) {
return false;
}
- return indexOfAnyBut(str, valid) == -1;
+ return indexOfAnyBut(str, valid) == INDEX_NOT_FOUND;
}
/**
* Checks if the String contains only certain characters.
*
* A null
String will return false
.
* A null
valid character String will return false
.
- * An empty String ("") always returns true
.
+ * An empty String (length()=0) always returns true
.
*
*
* StringUtils.containsOnly(null, *) = false
@@ -1229,7 +1625,7 @@
* StringUtils.containsOnly("ab1", "abc") = false
* StringUtils.containsOnly("abz", "abc") = false
*
- *
+ *
* @param str the String to check, may be null
* @param validChars a String of valid chars, may be null
* @return true if it only contains valid chars and is non-null
@@ -1241,15 +1637,15 @@
}
return containsOnly(str, validChars.toCharArray());
}
-
+
// ContainsNone
//-----------------------------------------------------------------------
/**
* Checks that the String does not contain certain characters.
*
* A null
String will return true
.
* A null
invalid character array will return true
.
- * An empty String ("") always returns true.
+ * An empty String (length()=0) always returns true.
*
*
* StringUtils.containsNone(null, *) = true
@@ -1260,23 +1656,36 @@
* StringUtils.containsNone("ab1", 'xyz') = true
* StringUtils.containsNone("abz", 'xyz') = false
*
- *
+ *
* @param str the String to check, may be null
- * @param invalidChars an array of invalid chars, may be null
+ * @param searchChars an array of invalid chars, may be null
* @return true if it contains none of the invalid chars, or is null
* @since 2.0
*/
- public static boolean containsNone(String str, char[] invalidChars) {
- if (str == null || invalidChars == null) {
+ public static boolean containsNone(String str, char[] searchChars) {
+ if (str == null || searchChars == null) {
return true;
}
- int strSize = str.length();
- int validSize = invalidChars.length;
- for (int i = 0; i < strSize; i++) {
+ int csLen = str.length();
+ int csLast = csLen - 1;
+ int searchLen = searchChars.length;
+ int searchLast = searchLen - 1;
+ for (int i = 0; i < csLen; i++) {
char ch = str.charAt(i);
- for (int j = 0; j < validSize; j++) {
- if (invalidChars[j] == ch) {
- return false;
+ for (int j = 0; j < searchLen; j++) {
+ if (searchChars[j] == ch) {
+ if (CharUtils.isHighSurrogate(ch)) {
+ if (j == searchLast) {
+ // missing low surrogate, fine, like String.indexOf(String)
+ return false;
+ }
+ if (i < csLast && searchChars[j + 1] == str.charAt(i + 1)) {
+ return false;
+ }
+ } else {
+ // ch is in the Basic Multilingual Plane
+ return false;
+ }
}
}
}
@@ -1299,7 +1708,7 @@
* StringUtils.containsNone("ab1", "xyz") = true
* StringUtils.containsNone("abz", "xyz") = false
*
- *
+ *
* @param str the String to check, may be null
* @param invalidChars a String of invalid chars, may be null
* @return true if it contains none of the invalid chars, or is null
@@ -1311,7 +1720,7 @@
}
return containsNone(str, invalidChars.toCharArray());
}
-
+
// IndexOfAny strings
//-----------------------------------------------------------------------
/**
@@ -1322,7 +1731,7 @@
* A null
search array entry will be ignored, but a search
* array containing "" will return 0
if str
is not
* null. This method uses {@link String#indexOf(String)}.
- *
+ *
*
* StringUtils.indexOfAny(null, *) = -1
* StringUtils.indexOfAny(*, null) = -1
@@ -1335,14 +1744,14 @@
* StringUtils.indexOfAny("", [""]) = 0
* StringUtils.indexOfAny("", ["a"]) = -1
*
- *
+ *
* @param str the String to check, may be null
* @param searchStrs the Strings to search for, may be null
* @return the first index of any of the searchStrs in str, -1 if no match
*/
public static int indexOfAny(String str, String[] searchStrs) {
if ((str == null) || (searchStrs == null)) {
- return -1;
+ return INDEX_NOT_FOUND;
}
int sz = searchStrs.length;
@@ -1356,7 +1765,7 @@
continue;
}
tmp = str.indexOf(search);
- if (tmp == -1) {
+ if (tmp == INDEX_NOT_FOUND) {
continue;
}
@@ -1365,7 +1774,7 @@
}
}
- return (ret == Integer.MAX_VALUE) ? -1 : ret;
+ return (ret == Integer.MAX_VALUE) ? INDEX_NOT_FOUND : ret;
}
/**
@@ -1374,9 +1783,9 @@
* A null
String will return -1
.
* A null
search array will return -1
.
* A null
or zero length search array entry will be ignored,
- * but a search array containing "" will return the length of str
+ * but a search array containing "" will return the length of str
* if str
is not null. This method uses {@link String#indexOf(String)}
- *
+ *
*
* StringUtils.lastIndexOfAny(null, *) = -1
* StringUtils.lastIndexOfAny(*, null) = -1
@@ -1388,17 +1797,17 @@
* StringUtils.lastIndexOfAny("zzabyycdxx", ["mn","op"]) = -1
* StringUtils.lastIndexOfAny("zzabyycdxx", ["mn",""]) = 10
*
- *
+ *
* @param str the String to check, may be null
* @param searchStrs the Strings to search for, may be null
* @return the last index of any of the Strings, -1 if no match
*/
public static int lastIndexOfAny(String str, String[] searchStrs) {
if ((str == null) || (searchStrs == null)) {
- return -1;
+ return INDEX_NOT_FOUND;
}
int sz = searchStrs.length;
- int ret = -1;
+ int ret = INDEX_NOT_FOUND;
int tmp = 0;
for (int i = 0; i < sz; i++) {
String search = searchStrs[i];
@@ -1423,7 +1832,7 @@
*
* A null
String will return null
.
* An empty ("") String will return "".
- *
+ *
*
* StringUtils.substring(null, *) = null
* StringUtils.substring("", *) = ""
@@ -1433,7 +1842,7 @@
* StringUtils.substring("abc", -2) = "bc"
* StringUtils.substring("abc", -4) = "abc"
*
- *
+ *
* @param str the String to get the substring from, may be null
* @param start the position to start from, negative means
* count back from the end of the String by this many characters
@@ -1458,22 +1867,22 @@
return str.substring(start);
}
-
+
/**
* Gets a substring from the specified String avoiding exceptions.
*
* A negative start position can be used to start/end n
* characters from the end of the String.
*
* The returned substring starts with the character in the start
- * position and ends before the end
position. All postion counting is
- * zero-based -- i.e., to start at the beginning of the string use
- * start = 0
. Negative start and end positions can be used to
+ * position and ends before the end
position. All position counting is
+ * zero-based -- i.e., to start at the beginning of the string use
+ * start = 0
. Negative start and end positions can be used to
* specify offsets relative to the end of the String.
*
* If start
is not strictly to the left of end
, ""
* is returned.
- *
+ *
*
* StringUtils.substring(null, *, *) = null
* StringUtils.substring("", * , *) = "";
@@ -1485,7 +1894,7 @@
* StringUtils.substring("abc", -2, -1) = "b"
* StringUtils.substring("abc", -4, 2) = "ab"
*
- *
+ *
* @param str the String to get the substring from, may be null
* @param start the position to start from, negative means
* count back from the end of the String by this many characters
@@ -1534,7 +1943,7 @@
*
* If len
characters are not available, or the
* String is null
, the String will be returned without
- * an exception. An exception is thrown if len is negative.
+ * an exception. An empty String is returned if len is negative.
*
*
* StringUtils.left(null, *) = null
@@ -1544,9 +1953,9 @@
* StringUtils.left("abc", 2) = "ab"
* StringUtils.left("abc", 4) = "abc"
*
- *
+ *
* @param str the String to get the leftmost characters from, may be null
- * @param len the length of the required String, must be zero or positive
+ * @param len the length of the required String
* @return the leftmost characters, null
if null String input
*/
public static String left(String str, int len) {
@@ -1558,17 +1967,16 @@
}
if (str.length() <= len) {
return str;
- } else {
- return str.substring(0, len);
}
+ return str.substring(0, len);
}
/**
* Gets the rightmost len
characters of a String.
*
* If len
characters are not available, or the String
* is null
, the String will be returned without an
- * an exception. An exception is thrown if len is negative.
+ * an exception. An empty String is returned if len is negative.
*
*
* StringUtils.right(null, *) = null
@@ -1578,9 +1986,9 @@
* StringUtils.right("abc", 2) = "bc"
* StringUtils.right("abc", 4) = "abc"
*
- *
+ *
* @param str the String to get the rightmost characters from, may be null
- * @param len the length of the required String, must be zero or positive
+ * @param len the length of the required String
* @return the rightmost characters, null
if null String input
*/
public static String right(String str, int len) {
@@ -1592,9 +2000,8 @@
}
if (str.length() <= len) {
return str;
- } else {
- return str.substring(str.length() - len);
}
+ return str.substring(str.length() - len);
}
/**
@@ -1603,7 +2010,8 @@
* If len
characters are not available, the remainder
* of the String will be returned without an exception. If the
* String is null
, null
will be returned.
- * An exception is thrown if len is negative.
+ * An empty String is returned if len is negative or exceeds the
+ * length of str
.
*
*
* StringUtils.mid(null, *, *) = null
@@ -1615,10 +2023,10 @@
* StringUtils.mid("abc", 4, 2) = ""
* StringUtils.mid("abc", -2, 2) = "ab"
*
- *
+ *
* @param str the String to get the characters from, may be null
* @param pos the position to start from, negative treated as zero
- * @param len the length of the required String, must be zero or positive
+ * @param len the length of the required String
* @return the middle characters, null
if null String input
*/
public static String mid(String str, int pos, int len) {
@@ -1633,21 +2041,22 @@
}
if (str.length() <= (pos + len)) {
return str.substring(pos);
- } else {
- return str.substring(pos, pos + len);
}
+ return str.substring(pos, pos + len);
}
// SubStringAfter/SubStringBefore
//-----------------------------------------------------------------------
/**
- * Gets the substring before the first occurance of a separator.
+ *
Gets the substring before the first occurrence of a separator.
* The separator is not returned.
*
* A null
string input will return null
.
* An empty ("") string input will return the empty string.
* A null
separator will return the input string.
*
+ * If nothing is found, the string input is returned.
+ *
*
* StringUtils.substringBefore(null, *) = null
* StringUtils.substringBefore("", *) = ""
@@ -1661,33 +2070,35 @@
*
* @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 before the first occurance of the separator,
+ * @return the substring before the first occurrence of the separator,
* null
if null String input
* @since 2.0
*/
public static String substringBefore(String str, String separator) {
- if (str == null || separator == null || str.length() == 0) {
+ if (isEmpty(str) || separator == null) {
return str;
}
if (separator.length() == 0) {
return EMPTY;
}
int pos = str.indexOf(separator);
- if (pos == -1) {
+ if (pos == INDEX_NOT_FOUND) {
return str;
}
return str.substring(0, pos);
}
/**
- * Gets the substring after the first occurance of a separator.
+ *
Gets the substring after the first occurrence of a separator.
* The separator is not returned.
*
* A null
string input will return null
.
* An empty ("") string input will return the empty string.
* A null
separator will return the empty string if the
* input string is not null
.
- *
+ *
+ * If nothing is found, the empty string is returned.
+ *
*
* StringUtils.substringAfter(null, *) = null
* StringUtils.substringAfter("", *) = ""
@@ -1701,32 +2112,34 @@
*
* @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 first occurance of the separator,
+ * @return the substring after the first occurrence of the separator,
* null
if null String input
* @since 2.0
*/
public static String substringAfter(String str, String separator) {
- if (str == null || str.length() == 0) {
+ if (isEmpty(str)) {
return str;
}
if (separator == null) {
return EMPTY;
}
int pos = str.indexOf(separator);
- if (pos == -1) {
+ if (pos == INDEX_NOT_FOUND) {
return EMPTY;
}
return str.substring(pos + separator.length());
}
/**
- * Gets the substring before the last occurance of a separator.
+ *
Gets the substring before the last occurrence of a separator.
* The separator is not returned.
*
* A null
string input will return null
.
* An empty ("") string input will return the empty string.
* An empty or null
separator will return the input string.
- *
+ *
+ * If nothing is found, the string input is returned.
+ *
*
* StringUtils.substringBeforeLast(null, *) = null
* StringUtils.substringBeforeLast("", *) = ""
@@ -1740,30 +2153,32 @@
*
* @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 before the last occurance of the separator,
+ * @return the substring before the last occurrence of the separator,
* null
if null String input
* @since 2.0
*/
public static String substringBeforeLast(String str, String separator) {
- if (str == null || separator == null || str.length() == 0 || separator.length() == 0) {
+ if (isEmpty(str) || isEmpty(separator)) {
return str;
}
int pos = str.lastIndexOf(separator);
- if (pos == -1) {
+ if (pos == INDEX_NOT_FOUND) {
return str;
}
return str.substring(0, pos);
}
/**
- * Gets the substring after the last occurance of a separator.
+ *
Gets the substring after the last occurrence of a separator.
* The separator is not returned.
*
* A null
string input will return null
.
* An empty ("") string input will return the empty string.
* An empty or null
separator will return the empty string if
* the input string is not null
.
*
+ * If nothing is found, the empty string is returned.
+ *
*
* StringUtils.substringAfterLast(null, *) = null
* StringUtils.substringAfterLast("", *) = ""
@@ -1778,19 +2193,19 @@
*
* @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 occurance of the separator,
+ * @return the substring after the last occurrence of the separator,
* null
if null String input
* @since 2.0
*/
public static String substringAfterLast(String str, String separator) {
- if (str == null || str.length() == 0) {
+ if (isEmpty(str)) {
return str;
}
- if (separator == null || separator.length() == 0) {
+ if (isEmpty(separator)) {
return EMPTY;
}
int pos = str.lastIndexOf(separator);
- if (pos == -1 || pos == (str.length() - separator.length())) {
+ if (pos == INDEX_NOT_FOUND || pos == (str.length() - separator.length())) {
return EMPTY;
}
return str.substring(pos + separator.length());
@@ -1804,7 +2219,7 @@
*
* A null
input String returns null
.
* A null
tag returns null
.
- *
+ *
*
* StringUtils.substringBetween(null, *) = null
* StringUtils.substringBetween("", "") = ""
@@ -1822,21 +2237,23 @@
public static String substringBetween(String str, String tag) {
return substringBetween(str, tag, tag);
}
-
+
/**
* Gets the String that is nested in between two Strings.
* Only the first match is returned.
- *
+ *
* A null
input String returns null
.
* A null
open/close returns null
(no match).
- * An empty ("") open/close returns an empty string.
+ * An empty ("") open and close returns an empty string.
*
*
+ * StringUtils.substringBetween("wx[b]yz", "[", "]") = "b"
* StringUtils.substringBetween(null, *, *) = null
+ * StringUtils.substringBetween(*, null, *) = null
+ * StringUtils.substringBetween(*, *, null) = null
* StringUtils.substringBetween("", "", "") = ""
- * StringUtils.substringBetween("", "", "tag") = null
- * StringUtils.substringBetween("", "tag", "tag") = null
- * StringUtils.substringBetween("yabcz", null, null) = null
+ * StringUtils.substringBetween("", "", "]") = null
+ * StringUtils.substringBetween("", "[", "]") = null
* StringUtils.substringBetween("yabcz", "", "") = ""
* StringUtils.substringBetween("yabcz", "y", "z") = "abc"
* StringUtils.substringBetween("yabczyabcz", "y", "z") = "abc"
@@ -1853,15 +2270,68 @@
return null;
}
int start = str.indexOf(open);
- if (start != -1) {
+ if (start != INDEX_NOT_FOUND) {
int end = str.indexOf(close, start + open.length());
- if (end != -1) {
+ if (end != INDEX_NOT_FOUND) {
return str.substring(start + open.length(), end);
}
}
return null;
}
+ /**
+ * Searches a String for substrings delimited by a start and end tag,
+ * returning all matching substrings in an array.
+ *
+ * A null
input String returns null
.
+ * A null
open/close returns null
(no match).
+ * An empty ("") open/close returns null
(no match).
+ *
+ *
+ * StringUtils.substringsBetween("[a][b][c]", "[", "]") = ["a","b","c"]
+ * StringUtils.substringsBetween(null, *, *) = null
+ * StringUtils.substringsBetween(*, null, *) = null
+ * StringUtils.substringsBetween(*, *, null) = null
+ * StringUtils.substringsBetween("", "[", "]") = []
+ *
+ *
+ * @param str the String containing the substrings, null returns null, empty returns empty
+ * @param open the String identifying the start of the substring, empty returns null
+ * @param close the String identifying the end of the substring, empty returns null
+ * @return a String Array of substrings, or null
if no match
+ * @since 2.3
+ */
+ public static String[] substringsBetween(String str, String open, String close) {
+ if (str == null || isEmpty(open) || isEmpty(close)) {
+ return null;
+ }
+ int strLen = str.length();
+ if (strLen == 0) {
+ return ArrayUtils.EMPTY_STRING_ARRAY;
+ }
+ int closeLen = close.length();
+ int openLen = open.length();
+ List list = new ArrayList();
+ int pos = 0;
+ while (pos < (strLen - closeLen)) {
+ int start = str.indexOf(open, pos);
+ if (start < 0) {
+ break;
+ }
+ start += openLen;
+ int end = str.indexOf(close, start);
+ if (end < 0) {
+ break;
+ }
+ list.add(str.substring(start, end));
+ pos = end + closeLen;
+ }
+ if (list.isEmpty()) {
+ return null;
+ }
+ return (String[]) list.toArray(new String [list.size()]);
+ }
+
// Nested extraction
//-----------------------------------------------------------------------
/**
@@ -1870,7 +2340,7 @@
*
* A null
input String returns null
.
* A null
tag returns null
.
- *
+ *
*
* StringUtils.getNestedString(null, *) = null
* StringUtils.getNestedString("", "") = ""
@@ -1889,11 +2359,11 @@
public static String getNestedString(String str, String tag) {
return substringBetween(str, tag, tag);
}
-
+
/**
* Gets the String that is nested in between two Strings.
* Only the first match is returned.
- *
+ *
* A null
input String returns null
.
* A null
open/close returns null
(no match).
* An empty ("") open/close returns an empty string.
@@ -1928,8 +2398,9 @@
* Whitespace is defined by {@link Character#isWhitespace(char)}.
*
* The separator is not included in the returned String array.
- * Adjacent separators are treated as one separator.
- *
+ * Adjacent separators are treated as one separator.
+ * For more control over the split use the StrTokenizer class.
+ *
* A null
input String returns null
.
*
*
@@ -1939,7 +2410,7 @@
* StringUtils.split("abc def") = ["abc", "def"]
* StringUtils.split(" abc ") = ["abc"]
*
- *
+ *
* @param str the String to parse, may be null
* @return an array of parsed Strings, null
if null String input
*/
@@ -1952,8 +2423,9 @@
* This is an alternative to using StringTokenizer.
*
* The separator is not included in the returned String array.
- * Adjacent separators are treated as one separator.
- *
+ * Adjacent separators are treated as one separator.
+ * For more control over the split use the StrTokenizer class.
+ *
* A null
input String returns null
.
*
*
@@ -1962,19 +2434,362 @@
* StringUtils.split("a.b.c", '.') = ["a", "b", "c"]
* StringUtils.split("a..b.c", '.') = ["a", "b", "c"]
* StringUtils.split("a:b:c", '.') = ["a:b:c"]
- * StringUtils.split("a\tb\nc", null) = ["a", "b", "c"]
* StringUtils.split("a b c", ' ') = ["a", "b", "c"]
*
- *
+ *
* @param str the String to parse, may be null
- * @param separatorChar the character used as the delimiter,
- * null
splits on whitespace
+ * @param separatorChar the character used as the delimiter
* @return an array of parsed Strings, null
if null String input
* @since 2.0
*/
public static String[] split(String str, char separatorChar) {
+ return splitWorker(str, separatorChar, false);
+ }
+
+ /**
+ * Splits the provided text into an array, separators specified.
+ * This is an alternative to using StringTokenizer.
+ *
+ * The separator is not included in the returned String array.
+ * Adjacent separators are treated as one separator.
+ * For more control over the split use the StrTokenizer class.
+ *
+ * A null
input String returns null
.
+ * A null
separatorChars splits on whitespace.
+ *
+ *
+ * StringUtils.split(null, *) = null
+ * StringUtils.split("", *) = []
+ * StringUtils.split("abc def", null) = ["abc", "def"]
+ * StringUtils.split("abc def", " ") = ["abc", "def"]
+ * StringUtils.split("abc def", " ") = ["abc", "def"]
+ * StringUtils.split("ab:cd:ef", ":") = ["ab", "cd", "ef"]
+ *
+ *
+ * @param str the String to parse, may be null
+ * @param separatorChars the characters used as the delimiters,
+ * null
splits on whitespace
+ * @return an array of parsed Strings, null
if null String input
+ */
+ public static String[] split(String str, String separatorChars) {
+ return splitWorker(str, separatorChars, -1, false);
+ }
+
+ /**
+ * Splits the provided text into an array with a maximum length,
+ * separators specified.
+ *
+ * The separator is not included in the returned String array.
+ * Adjacent separators are treated as one separator.
+ *
+ * A null
input String returns null
.
+ * A null
separatorChars splits on whitespace.
+ *
+ * If more than max
delimited substrings are found, the last
+ * returned string includes all characters after the first max - 1
+ * returned strings (including separator characters).
+ *
+ *
+ * StringUtils.split(null, *, *) = null
+ * StringUtils.split("", *, *) = []
+ * StringUtils.split("ab de fg", null, 0) = ["ab", "cd", "ef"]
+ * StringUtils.split("ab de fg", null, 0) = ["ab", "cd", "ef"]
+ * StringUtils.split("ab:cd:ef", ":", 0) = ["ab", "cd", "ef"]
+ * StringUtils.split("ab:cd:ef", ":", 2) = ["ab", "cd:ef"]
+ *
+ *
+ * @param str the String to parse, may be null
+ * @param separatorChars the characters used as the delimiters,
+ * null
splits on whitespace
+ * @param max the maximum number of elements to include in the
+ * array. A zero or negative value implies no limit
+ * @return an array of parsed Strings, null
if null String input
+ */
+ public static String[] split(String str, String separatorChars, int max) {
+ return splitWorker(str, separatorChars, max, false);
+ }
+
+ /**
+ * Splits the provided text into an array, separator string specified.
+ *
+ * The separator(s) will not be included in the returned String array.
+ * Adjacent separators are treated as one separator.
+ *
+ * A null
input String returns null
.
+ * A null
separator splits on whitespace.
+ *
+ *
+ * StringUtils.splitByWholeSeparator(null, *) = null
+ * StringUtils.splitByWholeSeparator("", *) = []
+ * StringUtils.splitByWholeSeparator("ab de fg", null) = ["ab", "de", "fg"]
+ * StringUtils.splitByWholeSeparator("ab de fg", null) = ["ab", "de", "fg"]
+ * StringUtils.splitByWholeSeparator("ab:cd:ef", ":") = ["ab", "cd", "ef"]
+ * StringUtils.splitByWholeSeparator("ab-!-cd-!-ef", "-!-") = ["ab", "cd", "ef"]
+ *
+ *
+ * @param str the String to parse, may be null
+ * @param separator String containing the String to be used as a delimiter,
+ * null
splits on whitespace
+ * @return an array of parsed Strings, null
if null String was input
+ */
+ public static String[] splitByWholeSeparator(String str, String separator) {
+ return splitByWholeSeparatorWorker( str, separator, -1, false ) ;
+ }
+
+ /**
+ * Splits the provided text into an array, separator string specified.
+ * Returns a maximum of max
substrings.
+ *
+ * The separator(s) will not be included in the returned String array.
+ * Adjacent separators are treated as one separator.
+ *
+ * A null
input String returns null
.
+ * A null
separator splits on whitespace.
+ *
+ *
+ * StringUtils.splitByWholeSeparator(null, *, *) = null
+ * StringUtils.splitByWholeSeparator("", *, *) = []
+ * StringUtils.splitByWholeSeparator("ab de fg", null, 0) = ["ab", "de", "fg"]
+ * StringUtils.splitByWholeSeparator("ab de fg", null, 0) = ["ab", "de", "fg"]
+ * StringUtils.splitByWholeSeparator("ab:cd:ef", ":", 2) = ["ab", "cd:ef"]
+ * StringUtils.splitByWholeSeparator("ab-!-cd-!-ef", "-!-", 5) = ["ab", "cd", "ef"]
+ * StringUtils.splitByWholeSeparator("ab-!-cd-!-ef", "-!-", 2) = ["ab", "cd-!-ef"]
+ *
+ *
+ * @param str the String to parse, may be null
+ * @param separator String containing the String to be used as a delimiter,
+ * null
splits on whitespace
+ * @param max the maximum number of elements to include in the returned
+ * array. A zero or negative value implies no limit.
+ * @return an array of parsed Strings, null
if null String was input
+ */
+ public static String[] splitByWholeSeparator( String str, String separator, int max ) {
+ return splitByWholeSeparatorWorker(str, separator, max, false);
+ }
+
+ /**
+ * Splits the provided text into an array, separator string specified.
+ *
+ * The separator is not included in the returned String array.
+ * Adjacent separators are treated as separators for empty tokens.
+ * For more control over the split use the StrTokenizer class.
+ *
+ * A null
input String returns null
.
+ * A null
separator splits on whitespace.
+ *
+ *
+ * StringUtils.splitByWholeSeparatorPreserveAllTokens(null, *) = null
+ * StringUtils.splitByWholeSeparatorPreserveAllTokens("", *) = []
+ * StringUtils.splitByWholeSeparatorPreserveAllTokens("ab de fg", null) = ["ab", "de", "fg"]
+ * StringUtils.splitByWholeSeparatorPreserveAllTokens("ab de fg", null) = ["ab", "", "", "de", "fg"]
+ * StringUtils.splitByWholeSeparatorPreserveAllTokens("ab:cd:ef", ":") = ["ab", "cd", "ef"]
+ * StringUtils.splitByWholeSeparatorPreserveAllTokens("ab-!-cd-!-ef", "-!-") = ["ab", "cd", "ef"]
+ *
+ *
+ * @param str the String to parse, may be null
+ * @param separator String containing the String to be used as a delimiter,
+ * null
splits on whitespace
+ * @return an array of parsed Strings, null
if null String was input
+ * @since 2.4
+ */
+ public static String[] splitByWholeSeparatorPreserveAllTokens(String str, String separator) {
+ return splitByWholeSeparatorWorker(str, separator, -1, true);
+ }
+
+ /**
+ * Splits the provided text into an array, separator string specified.
+ * Returns a maximum of max
substrings.
+ *
+ * The separator is not included in the returned String array.
+ * Adjacent separators are treated as separators for empty tokens.
+ * For more control over the split use the StrTokenizer class.
+ *
+ * A null
input String returns null
.
+ * A null
separator splits on whitespace.
+ *
+ *
+ * StringUtils.splitByWholeSeparatorPreserveAllTokens(null, *, *) = null
+ * StringUtils.splitByWholeSeparatorPreserveAllTokens("", *, *) = []
+ * StringUtils.splitByWholeSeparatorPreserveAllTokens("ab de fg", null, 0) = ["ab", "de", "fg"]
+ * StringUtils.splitByWholeSeparatorPreserveAllTokens("ab de fg", null, 0) = ["ab", "", "", "de", "fg"]
+ * StringUtils.splitByWholeSeparatorPreserveAllTokens("ab:cd:ef", ":", 2) = ["ab", "cd:ef"]
+ * StringUtils.splitByWholeSeparatorPreserveAllTokens("ab-!-cd-!-ef", "-!-", 5) = ["ab", "cd", "ef"]
+ * StringUtils.splitByWholeSeparatorPreserveAllTokens("ab-!-cd-!-ef", "-!-", 2) = ["ab", "cd-!-ef"]
+ *
+ *
+ * @param str the String to parse, may be null
+ * @param separator String containing the String to be used as a delimiter,
+ * null
splits on whitespace
+ * @param max the maximum number of elements to include in the returned
+ * array. A zero or negative value implies no limit.
+ * @return an array of parsed Strings, null
if null String was input
+ * @since 2.4
+ */
+ public static String[] splitByWholeSeparatorPreserveAllTokens(String str, String separator, int max) {
+ return splitByWholeSeparatorWorker(str, separator, max, true);
+ }
+
+ /**
+ * Performs the logic for the splitByWholeSeparatorPreserveAllTokens
methods.
+ *
+ * @param str the String to parse, may be null
+ * @param separator String containing the String to be used as a delimiter,
+ * null
splits on whitespace
+ * @param max the maximum number of elements to include in the returned
+ * array. A zero or negative value implies no limit.
+ * @param preserveAllTokens if true
, adjacent separators are
+ * treated as empty token separators; if false
, adjacent
+ * separators are treated as one separator.
+ * @return an array of parsed Strings, null
if null String input
+ * @since 2.4
+ */
+ private static String[] splitByWholeSeparatorWorker(String str, String separator, int max,
+ boolean preserveAllTokens)
+ {
+ if (str == null) {
+ return null;
+ }
+
+ int len = str.length();
+
+ if (len == 0) {
+ return ArrayUtils.EMPTY_STRING_ARRAY;
+ }
+
+ if ((separator == null) || (EMPTY.equals(separator))) {
+ // Split on whitespace.
+ return splitWorker(str, null, max, preserveAllTokens);
+ }
+
+ int separatorLength = separator.length();
+
+ ArrayList substrings = new ArrayList();
+ int numberOfSubstrings = 0;
+ int beg = 0;
+ int end = 0;
+ while (end < len) {
+ end = str.indexOf(separator, beg);
+
+ if (end > -1) {
+ if (end > beg) {
+ numberOfSubstrings += 1;
+
+ if (numberOfSubstrings == max) {
+ end = len;
+ substrings.add(str.substring(beg));
+ } else {
+ // The following is OK, because String.substring( beg, end ) excludes
+ // the character at the position 'end'.
+ substrings.add(str.substring(beg, end));
+
+ // Set the starting point for the next search.
+ // The following is equivalent to beg = end + (separatorLength - 1) + 1,
+ // which is the right calculation:
+ beg = end + separatorLength;
+ }
+ } else {
+ // We found a consecutive occurrence of the separator, so skip it.
+ if (preserveAllTokens) {
+ numberOfSubstrings += 1;
+ if (numberOfSubstrings == max) {
+ end = len;
+ substrings.add(str.substring(beg));
+ } else {
+ substrings.add(EMPTY);
+ }
+ }
+ beg = end + separatorLength;
+ }
+ } else {
+ // String.substring( beg ) goes from 'beg' to the end of the String.
+ substrings.add(str.substring(beg));
+ end = len;
+ }
+ }
+
+ return (String[]) substrings.toArray(new String[substrings.size()]);
+ }
+
+ // -----------------------------------------------------------------------
+ /**
+ * Splits the provided text into an array, using whitespace as the
+ * separator, preserving all tokens, including empty tokens created by
+ * adjacent separators. This is an alternative to using StringTokenizer.
+ * Whitespace is defined by {@link Character#isWhitespace(char)}.
+ *
+ * The separator is not included in the returned String array.
+ * Adjacent separators are treated as separators for empty tokens.
+ * For more control over the split use the StrTokenizer class.
+ *
+ * A null
input String returns null
.
+ *
+ *
+ * StringUtils.splitPreserveAllTokens(null) = null
+ * StringUtils.splitPreserveAllTokens("") = []
+ * StringUtils.splitPreserveAllTokens("abc def") = ["abc", "def"]
+ * StringUtils.splitPreserveAllTokens("abc def") = ["abc", "", "def"]
+ * StringUtils.splitPreserveAllTokens(" abc ") = ["", "abc", ""]
+ *
+ *
+ * @param str the String to parse, may be null
+ * @return an array of parsed Strings, null
if null String input
+ * @since 2.1
+ */
+ public static String[] splitPreserveAllTokens(String str) {
+ return splitWorker(str, null, -1, true);
+ }
+
+ /**
+ * Splits the provided text into an array, separator specified,
+ * preserving all tokens, including empty tokens created by adjacent
+ * separators. This is an alternative to using StringTokenizer.
+ *
+ * The separator is not included in the returned String array.
+ * Adjacent separators are treated as separators for empty tokens.
+ * For more control over the split use the StrTokenizer class.
+ *
+ * A null
input String returns null
.
+ *
+ *
+ * StringUtils.splitPreserveAllTokens(null, *) = null
+ * StringUtils.splitPreserveAllTokens("", *) = []
+ * StringUtils.splitPreserveAllTokens("a.b.c", '.') = ["a", "b", "c"]
+ * StringUtils.splitPreserveAllTokens("a..b.c", '.') = ["a", "", "b", "c"]
+ * StringUtils.splitPreserveAllTokens("a:b:c", '.') = ["a:b:c"]
+ * StringUtils.splitPreserveAllTokens("a\tb\nc", null) = ["a", "b", "c"]
+ * StringUtils.splitPreserveAllTokens("a b c", ' ') = ["a", "b", "c"]
+ * StringUtils.splitPreserveAllTokens("a b c ", ' ') = ["a", "b", "c", ""]
+ * StringUtils.splitPreserveAllTokens("a b c ", ' ') = ["a", "b", "c", "", ""]
+ * StringUtils.splitPreserveAllTokens(" a b c", ' ') = ["", a", "b", "c"]
+ * StringUtils.splitPreserveAllTokens(" a b c", ' ') = ["", "", a", "b", "c"]
+ * StringUtils.splitPreserveAllTokens(" a b c ", ' ') = ["", a", "b", "c", ""]
+ *
+ *
+ * @param str the String to parse, may be null
+ * @param separatorChar the character used as the delimiter,
+ * null
splits on whitespace
+ * @return an array of parsed Strings, null
if null String input
+ * @since 2.1
+ */
+ public static String[] splitPreserveAllTokens(String str, char separatorChar) {
+ return splitWorker(str, separatorChar, true);
+ }
+
+ /**
+ * Performs the logic for the split
and
+ * splitPreserveAllTokens
methods that do not return a
+ * maximum array length.
+ *
+ * @param str the String to parse, may be null
+ * @param separatorChar the separate character
+ * @param preserveAllTokens if true
, adjacent separators are
+ * treated as empty token separators; if false
, adjacent
+ * separators are treated as one separator.
+ * @return an array of parsed Strings, null
if null String input
+ */
+ private static String[] splitWorker(String str, char separatorChar, boolean preserveAllTokens) {
// Performance tuned for 2.0 (JDK1.4)
-
+
if (str == null) {
return null;
}
@@ -1983,85 +2798,125 @@
return ArrayUtils.EMPTY_STRING_ARRAY;
}
List list = new ArrayList();
- int i =0, start = 0;
+ int i = 0, start = 0;
boolean match = false;
+ boolean lastMatch = false;
while (i < len) {
if (str.charAt(i) == separatorChar) {
- if (match) {
+ if (match || preserveAllTokens) {
list.add(str.substring(start, i));
match = false;
+ lastMatch = true;
}
start = ++i;
continue;
}
+ lastMatch = false;
match = true;
i++;
}
- if (match) {
+ if (match || (preserveAllTokens && lastMatch)) {
list.add(str.substring(start, i));
}
return (String[]) list.toArray(new String[list.size()]);
}
/**
- * Splits the provided text into an array, separators specified.
- * This is an alternative to using StringTokenizer.
+ * Splits the provided text into an array, separators specified,
+ * preserving all tokens, including empty tokens created by adjacent
+ * separators. This is an alternative to using StringTokenizer.
*
* The separator is not included in the returned String array.
- * Adjacent separators are treated as one separator.
- *
+ * Adjacent separators are treated as separators for empty tokens.
+ * For more control over the split use the StrTokenizer class.
+ *
* A null
input String returns null
.
* A null
separatorChars splits on whitespace.
*
*
- * StringUtils.split(null, *) = null
- * StringUtils.split("", *) = []
- * StringUtils.split("abc def", null) = ["abc", "def"]
- * StringUtils.split("abc def", " ") = ["abc", "def"]
- * StringUtils.split("abc def", " ") = ["abc", "def"]
- * StringUtils.split("ab:cd:ef", ":") = ["ab", "cd", "ef"]
+ * StringUtils.splitPreserveAllTokens(null, *) = null
+ * StringUtils.splitPreserveAllTokens("", *) = []
+ * StringUtils.splitPreserveAllTokens("abc def", null) = ["abc", "def"]
+ * StringUtils.splitPreserveAllTokens("abc def", " ") = ["abc", "def"]
+ * StringUtils.splitPreserveAllTokens("abc def", " ") = ["abc", "", def"]
+ * StringUtils.splitPreserveAllTokens("ab:cd:ef", ":") = ["ab", "cd", "ef"]
+ * StringUtils.splitPreserveAllTokens("ab:cd:ef:", ":") = ["ab", "cd", "ef", ""]
+ * StringUtils.splitPreserveAllTokens("ab:cd:ef::", ":") = ["ab", "cd", "ef", "", ""]
+ * StringUtils.splitPreserveAllTokens("ab::cd:ef", ":") = ["ab", "", cd", "ef"]
+ * StringUtils.splitPreserveAllTokens(":cd:ef", ":") = ["", cd", "ef"]
+ * StringUtils.splitPreserveAllTokens("::cd:ef", ":") = ["", "", cd", "ef"]
+ * StringUtils.splitPreserveAllTokens(":cd:ef:", ":") = ["", cd", "ef", ""]
*
- *
- * @param str the String to parse, may be null
+ *
+ * @param str the String to parse, may be null
* @param separatorChars the characters used as the delimiters,
* null
splits on whitespace
* @return an array of parsed Strings, null
if null String input
+ * @since 2.1
*/
- public static String[] split(String str, String separatorChars) {
- return split(str, separatorChars, -1);
+ public static String[] splitPreserveAllTokens(String str, String separatorChars) {
+ return splitWorker(str, separatorChars, -1, true);
}
/**
- * Splits the provided text into an array, separators specified.
- * This is an alternative to using StringTokenizer.
+ * Splits the provided text into an array with a maximum length,
+ * separators specified, preserving all tokens, including empty tokens
+ * created by adjacent separators.
*
* The separator is not included in the returned String array.
+ * Adjacent separators are treated as separators for empty tokens.
* Adjacent separators are treated as one separator.
*
* A null
input String returns null
.
* A null
separatorChars splits on whitespace.
- *
+ *
+ * If more than max
delimited substrings are found, the last
+ * returned string includes all characters after the first max - 1
+ * returned strings (including separator characters).
+ *
*
- * StringUtils.split(null, *, *) = null
- * StringUtils.split("", *, *) = []
- * StringUtils.split("ab de fg", null, 0) = ["ab", "cd", "ef"]
- * StringUtils.split("ab de fg", null, 0) = ["ab", "cd", "ef"]
- * StringUtils.split("ab:cd:ef", ":", 0) = ["ab", "cd", "ef"]
- * StringUtils.split("ab:cd:ef", ":", 2) = ["ab", "cdef"]
+ * StringUtils.splitPreserveAllTokens(null, *, *) = null
+ * StringUtils.splitPreserveAllTokens("", *, *) = []
+ * StringUtils.splitPreserveAllTokens("ab de fg", null, 0) = ["ab", "cd", "ef"]
+ * StringUtils.splitPreserveAllTokens("ab de fg", null, 0) = ["ab", "cd", "ef"]
+ * StringUtils.splitPreserveAllTokens("ab:cd:ef", ":", 0) = ["ab", "cd", "ef"]
+ * StringUtils.splitPreserveAllTokens("ab:cd:ef", ":", 2) = ["ab", "cd:ef"]
+ * StringUtils.splitPreserveAllTokens("ab de fg", null, 2) = ["ab", " de fg"]
+ * StringUtils.splitPreserveAllTokens("ab de fg", null, 3) = ["ab", "", " de fg"]
+ * StringUtils.splitPreserveAllTokens("ab de fg", null, 4) = ["ab", "", "", "de fg"]
*
- *
- * @param str the String to parse, may be null
+ *
+ * @param str the String to parse, may be null
* @param separatorChars the characters used as the delimiters,
* null
splits on whitespace
* @param max the maximum number of elements to include in the
* array. A zero or negative value implies no limit
* @return an array of parsed Strings, null
if null String input
+ * @since 2.1
*/
- public static String[] split(String str, String separatorChars, int max) {
+ public static String[] splitPreserveAllTokens(String str, String separatorChars, int max) {
+ return splitWorker(str, separatorChars, max, true);
+ }
+
+ /**
+ * Performs the logic for the split
and
+ * splitPreserveAllTokens
methods that return a maximum array
+ * length.
+ *
+ * @param str the String to parse, may be null
+ * @param separatorChars the separate character
+ * @param max the maximum number of elements to include in the
+ * array. A zero or negative value implies no limit.
+ * @param preserveAllTokens if true
, adjacent separators are
+ * treated as empty token separators; if false
, adjacent
+ * separators are treated as one separator.
+ * @return an array of parsed Strings, null
if null String input
+ */
+ private static String[] splitWorker(String str, String separatorChars, int max, boolean preserveAllTokens) {
// Performance tuned for 2.0 (JDK1.4)
// Direct code is quicker than StringTokenizer.
// Also, StringTokenizer uses isSpace() not isWhitespace()
-
+
if (str == null) {
return null;
}
@@ -2071,22 +2926,26 @@
}
List list = new ArrayList();
int sizePlus1 = 1;
- int i =0, start = 0;
+ int i = 0, start = 0;
boolean match = false;
+ boolean lastMatch = false;
if (separatorChars == null) {
// Null separator means use whitespace
while (i < len) {
if (Character.isWhitespace(str.charAt(i))) {
- if (match) {
+ if (match || preserveAllTokens) {
+ lastMatch = true;
if (sizePlus1++ == max) {
i = len;
+ lastMatch = false;
}
list.add(str.substring(start, i));
match = false;
}
start = ++i;
continue;
}
+ lastMatch = false;
match = true;
i++;
}
@@ -2095,48 +2954,153 @@
char sep = separatorChars.charAt(0);
while (i < len) {
if (str.charAt(i) == sep) {
- if (match) {
+ if (match || preserveAllTokens) {
+ lastMatch = true;
if (sizePlus1++ == max) {
i = len;
+ lastMatch = false;
}
list.add(str.substring(start, i));
match = false;
}
start = ++i;
continue;
}
+ lastMatch = false;
match = true;
i++;
}
} else {
// standard case
while (i < len) {
if (separatorChars.indexOf(str.charAt(i)) >= 0) {
- if (match) {
+ if (match || preserveAllTokens) {
+ lastMatch = true;
if (sizePlus1++ == max) {
i = len;
+ lastMatch = false;
}
list.add(str.substring(start, i));
match = false;
}
start = ++i;
continue;
}
+ lastMatch = false;
match = true;
i++;
}
}
- if (match) {
+ if (match || (preserveAllTokens && lastMatch)) {
list.add(str.substring(start, i));
}
return (String[]) list.toArray(new String[list.size()]);
}
+ /**
+ * Splits a String by Character type as returned by
+ * java.lang.Character.getType(char)
. Groups of contiguous
+ * characters of the same type are returned as complete tokens.
+ *
+ * StringUtils.splitByCharacterType(null) = null
+ * StringUtils.splitByCharacterType("") = []
+ * StringUtils.splitByCharacterType("ab de fg") = ["ab", " ", "de", " ", "fg"]
+ * StringUtils.splitByCharacterType("ab de fg") = ["ab", " ", "de", " ", "fg"]
+ * StringUtils.splitByCharacterType("ab:cd:ef") = ["ab", ":", "cd", ":", "ef"]
+ * StringUtils.splitByCharacterType("number5") = ["number", "5"]
+ * StringUtils.splitByCharacterType("fooBar") = ["foo", "B", "ar"]
+ * StringUtils.splitByCharacterType("foo200Bar") = ["foo", "200", "B", "ar"]
+ * StringUtils.splitByCharacterType("ASFRules") = ["ASFR", "ules"]
+ *
+ * @param str the String to split, may be null
+ * @return an array of parsed Strings, null
if null String input
+ * @since 2.4
+ */
+ public static String[] splitByCharacterType(String str) {
+ return splitByCharacterType(str, false);
+ }
+
+ /**
+ * Splits a String by Character type as returned by
+ * java.lang.Character.getType(char)
. Groups of contiguous
+ * characters of the same type are returned as complete tokens, with the
+ * following exception: the character of type
+ * Character.UPPERCASE_LETTER
, if any, immediately
+ * preceding a token of type Character.LOWERCASE_LETTER
+ * will belong to the following token rather than to the preceding, if any,
+ * Character.UPPERCASE_LETTER
token.
+ *
+ * StringUtils.splitByCharacterTypeCamelCase(null) = null
+ * StringUtils.splitByCharacterTypeCamelCase("") = []
+ * StringUtils.splitByCharacterTypeCamelCase("ab de fg") = ["ab", " ", "de", " ", "fg"]
+ * StringUtils.splitByCharacterTypeCamelCase("ab de fg") = ["ab", " ", "de", " ", "fg"]
+ * StringUtils.splitByCharacterTypeCamelCase("ab:cd:ef") = ["ab", ":", "cd", ":", "ef"]
+ * StringUtils.splitByCharacterTypeCamelCase("number5") = ["number", "5"]
+ * StringUtils.splitByCharacterTypeCamelCase("fooBar") = ["foo", "Bar"]
+ * StringUtils.splitByCharacterTypeCamelCase("foo200Bar") = ["foo", "200", "Bar"]
+ * StringUtils.splitByCharacterTypeCamelCase("ASFRules") = ["ASF", "Rules"]
+ *
+ * @param str the String to split, may be null
+ * @return an array of parsed Strings, null
if null String input
+ * @since 2.4
+ */
+ public static String[] splitByCharacterTypeCamelCase(String str) {
+ return splitByCharacterType(str, true);
+ }
+
+ /**
+ * Splits a String by Character type as returned by
+ * java.lang.Character.getType(char)
. Groups of contiguous
+ * characters of the same type are returned as complete tokens, with the
+ * following exception: if camelCase
is true
,
+ * the character of type Character.UPPERCASE_LETTER
, if any,
+ * immediately preceding a token of type Character.LOWERCASE_LETTER
+ * will belong to the following token rather than to the preceding, if any,
+ * Character.UPPERCASE_LETTER
token.
+ * @param str the String to split, may be null
+ * @param camelCase whether to use so-called "camel-case" for letter types
+ * @return an array of parsed Strings, null
if null String input
+ * @since 2.4
+ */
+ private static String[] splitByCharacterType(String str, boolean camelCase) {
+ if (str == null) {
+ return null;
+ }
+ if (str.length() == 0) {
+ return ArrayUtils.EMPTY_STRING_ARRAY;
+ }
+ char[] c = str.toCharArray();
+ List list = new ArrayList();
+ int tokenStart = 0;
+ int currentType = Character.getType(c[tokenStart]);
+ for (int pos = tokenStart + 1; pos < c.length; pos++) {
+ int type = Character.getType(c[pos]);
+ if (type == currentType) {
+ continue;
+ }
+ if (camelCase && type == Character.LOWERCASE_LETTER && currentType == Character.UPPERCASE_LETTER) {
+ int newTokenStart = pos - 1;
+ if (newTokenStart != tokenStart) {
+ list.add(new String(c, tokenStart, newTokenStart - tokenStart));
+ tokenStart = newTokenStart;
+ }
+ } else {
+ list.add(new String(c, tokenStart, pos - tokenStart));
+ tokenStart = pos;
+ }
+ currentType = type;
+ }
+ list.add(new String(c, tokenStart, c.length - tokenStart));
+ return (String[]) list.toArray(new String[list.size()]);
+ }
+
// Joining
//-----------------------------------------------------------------------
/**
- *
Concatenates elements of an array into a single String.
- * Null objects or empty strings within the array are represented by
+ *
Joins the provided elements into a single String.
+ *
+ * No separator is added to the joined String.
+ * Null objects or empty string elements are represented by
* empty strings.
*
*
@@ -2146,7 +3110,7 @@
* StringUtils.concatenate(["a", "b", "c"]) = "abc"
* StringUtils.concatenate([null, "", "a"]) = "a"
*
- *
+ *
* @param array the array of values to concatenate, may be null
* @return the concatenated String, null
if null array input
* @deprecated Use the better named {@link #join(Object[])} instead.
@@ -2155,37 +3119,37 @@
public static String concatenate(Object[] array) {
return join(array, null);
}
-
+
/**
* Joins the elements of the provided array into a single String
* containing the provided list of elements.
*
* No separator is added to the joined String.
- * Null objects or empty strings within the array are represented by
+ * Null objects or empty strings within the array are represented by
* empty strings.
- *
+ *
*
* StringUtils.join(null) = null
* StringUtils.join([]) = ""
* StringUtils.join([null]) = ""
* StringUtils.join(["a", "b", "c"]) = "abc"
* StringUtils.join([null, "", "a"]) = "a"
*
- *
+ *
* @param array the array of values to join together, may be null
* @return the joined String, null
if null array input
* @since 2.0
*/
public static String join(Object[] array) {
return join(array, null);
}
-
+
/**
* Joins the elements of the provided array into a single String
* containing the provided list of elements.
*
* No delimiter is added before or after the list.
- * Null objects or empty strings within the array are represented by
+ * Null objects or empty strings within the array are represented by
* empty strings.
*
*
@@ -2206,12 +3170,50 @@
if (array == null) {
return null;
}
- int arraySize = array.length;
- int bufSize = (arraySize == 0 ? 0 : ((array[0] == null ? 16 : array[0].toString().length()) + 1) * arraySize);
- StringBuffer buf = new StringBuffer(bufSize);
- for (int i = 0; i < arraySize; i++) {
- if (i > 0) {
+ return join(array, separator, 0, array.length);
+ }
+
+ /**
+ * Joins the elements of the provided array into a single String
+ * containing the provided list of elements.
+ *
+ * No delimiter is added before or after the list.
+ * Null objects or empty strings within the array are represented by
+ * empty strings.
+ *
+ *
+ * StringUtils.join(null, *) = null
+ * StringUtils.join([], *) = ""
+ * StringUtils.join([null], *) = ""
+ * StringUtils.join(["a", "b", "c"], ';') = "a;b;c"
+ * StringUtils.join(["a", "b", "c"], null) = "abc"
+ * StringUtils.join([null, "", "a"], ';') = ";;a"
+ *
+ *
+ * @param array the array of values to join together, may be null
+ * @param separator the separator character to use
+ * @param startIndex the first index to start joining from. It is
+ * an error to pass in an end index past the end of the array
+ * @param endIndex the index to stop joining from (exclusive). It is
+ * an error to pass in an end index past the end of the array
+ * @return the joined String, null
if null array input
+ * @since 2.0
+ */
+ public static String join(Object[] array, char separator, int startIndex, int endIndex) {
+ if (array == null) {
+ return null;
+ }
+ int bufSize = (endIndex - startIndex);
+ if (bufSize <= 0) {
+ return EMPTY;
+ }
+
+ bufSize *= ((array[startIndex] == null ? 16 : array[startIndex].toString().length()) + 1);
+ StrBuilder buf = new StrBuilder(bufSize);
+
+ for (int i = startIndex; i < endIndex; i++) {
+ if (i > startIndex) {
buf.append(separator);
}
if (array[i] != null) {
@@ -2221,13 +3223,14 @@
return buf.toString();
}
+
/**
* Joins the elements of the provided array into a single String
* containing the provided list of elements.
*
* No delimiter is added before or after the list.
- * A null
separator is the same as an empty String ("").
- * Null objects or empty strings within the array are represented by
+ * A null
separator is the same as an empty String ("").
+ * Null objects or empty strings within the array are represented by
* empty strings.
*
*
@@ -2248,23 +3251,58 @@
if (array == null) {
return null;
}
+ return join(array, separator, 0, array.length);
+ }
+
+ /**
+ * Joins the elements of the provided array into a single String
+ * containing the provided list of elements.
+ *
+ * No delimiter is added before or after the list.
+ * A null
separator is the same as an empty String ("").
+ * Null objects or empty strings within the array are represented by
+ * empty strings.
+ *
+ *
+ * StringUtils.join(null, *) = null
+ * StringUtils.join([], *) = ""
+ * StringUtils.join([null], *) = ""
+ * StringUtils.join(["a", "b", "c"], "--") = "a--b--c"
+ * StringUtils.join(["a", "b", "c"], null) = "abc"
+ * StringUtils.join(["a", "b", "c"], "") = "abc"
+ * StringUtils.join([null, "", "a"], ',') = ",,a"
+ *
+ *
+ * @param array the array of values to join together, may be null
+ * @param separator the separator character to use, null treated as ""
+ * @param startIndex the first index to start joining from. It is
+ * an error to pass in an end index past the end of the array
+ * @param endIndex the index to stop joining from (exclusive). It is
+ * an error to pass in an end index past the end of the array
+ * @return the joined String, null
if null array input
+ */
+ public static String join(Object[] array, String separator, int startIndex, int endIndex) {
+ if (array == null) {
+ return null;
+ }
if (separator == null) {
separator = EMPTY;
}
- int arraySize = array.length;
- // ArraySize == 0: Len = 0
- // ArraySize > 0: Len = NofStrings *(len(firstString) + len(separator))
+ // endIndex - startIndex > 0: Len = NofStrings *(len(firstString) + len(separator))
// (Assuming that all Strings are roughly equally long)
- int bufSize
- = ((arraySize == 0) ? 0
- : arraySize * ((array[0] == null ? 16 : array[0].toString().length())
- + ((separator != null) ? separator.length(): 0)));
+ int bufSize = (endIndex - startIndex);
+ if (bufSize <= 0) {
+ return EMPTY;
+ }
- StringBuffer buf = new StringBuffer(bufSize);
+ bufSize *= ((array[startIndex] == null ? 16 : array[startIndex].toString().length())
+ + separator.length());
- for (int i = 0; i < arraySize; i++) {
- if ((separator != null) && (i > 0)) {
+ StrBuilder buf = new StrBuilder(bufSize);
+
+ for (int i = startIndex; i < endIndex; i++) {
+ if (i > startIndex) {
buf.append(separator);
}
if (array[i] != null) {
@@ -2278,7 +3316,7 @@
* Joins the elements of the provided Iterator
into
* a single String containing the provided elements.
*
- * No delimiter is added before or after the list. Null objects or empty
+ *
No delimiter is added before or after the list. Null objects or empty
* strings within the iteration are represented by empty strings.
*
* See the examples here: {@link #join(Object[],char)}.
@@ -2289,19 +3327,33 @@
* @since 2.0
*/
public static String join(Iterator iterator, char separator) {
+
+ // handle null, zero and one elements before building a buffer
if (iterator == null) {
return null;
}
- StringBuffer buf = new StringBuffer(256); // Java default is 16, probably too small
+ if (!iterator.hasNext()) {
+ return EMPTY;
+ }
+ Object first = iterator.next();
+ if (!iterator.hasNext()) {
+ return ObjectUtils.toString(first);
+ }
+
+ // two or more elements
+ StrBuilder buf = new StrBuilder(256); // Java default is 16, probably too small
+ if (first != null) {
+ buf.append(first);
+ }
+
while (iterator.hasNext()) {
+ buf.append(separator);
Object obj = iterator.next();
if (obj != null) {
buf.append(obj);
}
- if (iterator.hasNext()) {
- buf.append(separator);
- }
}
+
return buf.toString();
}
@@ -2319,29 +3371,86 @@
* @return the joined String, null
if null iterator input
*/
public static String join(Iterator iterator, String separator) {
+
+ // handle null, zero and one elements before building a buffer
if (iterator == null) {
return null;
}
- StringBuffer buf = new StringBuffer(256); // Java default is 16, probably too small
+ if (!iterator.hasNext()) {
+ return EMPTY;
+ }
+ Object first = iterator.next();
+ if (!iterator.hasNext()) {
+ return ObjectUtils.toString(first);
+ }
+
+ // two or more elements
+ StrBuilder buf = new StrBuilder(256); // Java default is 16, probably too small
+ if (first != null) {
+ buf.append(first);
+ }
+
while (iterator.hasNext()) {
+ if (separator != null) {
+ buf.append(separator);
+ }
Object obj = iterator.next();
if (obj != null) {
buf.append(obj);
}
- if ((separator != null) && iterator.hasNext()) {
- buf.append(separator);
- }
- }
+ }
return buf.toString();
}
+ /**
+ * Joins the elements of the provided Collection
into
+ * a single String containing the provided elements.
+ *
+ * No delimiter is added before or after the list. Null objects or empty
+ * strings within the iteration are represented by empty strings.
+ *
+ * See the examples here: {@link #join(Object[],char)}.
+ *
+ * @param collection the Collection
of values to join together, may be null
+ * @param separator the separator character to use
+ * @return the joined String, null
if null iterator input
+ * @since 2.3
+ */
+ public static String join(Collection collection, char separator) {
+ if (collection == null) {
+ return null;
+ }
+ return join(collection.iterator(), separator);
+ }
+
+ /**
+ * Joins the elements of the provided Collection
into
+ * a single String containing the provided elements.
+ *
+ * No delimiter is added before or after the list.
+ * A null
separator is the same as an empty String ("").
+ *
+ * See the examples here: {@link #join(Object[],String)}.
+ *
+ * @param collection the Collection
of values to join together, may be null
+ * @param separator the separator character to use, null treated as ""
+ * @return the joined String, null
if null iterator input
+ * @since 2.3
+ */
+ public static String join(Collection collection, String separator) {
+ if (collection == null) {
+ return null;
+ }
+ return join(collection.iterator(), separator);
+ }
+
// Delete
//-----------------------------------------------------------------------
/**
* Deletes all 'space' characters from a String as defined by
* {@link Character#isSpace(char)}.
- *
- * This is the only StringUtils method that uses the
+ *
+ *
This is the only StringUtils method that uses the
* isSpace
definition. You are advised to use
* {@link #deleteWhitespace(String)} instead as whitespace is much
* better localized.
@@ -2354,7 +3463,7 @@
* StringUtils.deleteSpaces("ab c") = "abc"
* StringUtils.deleteSpaces("a\nb\tc ") = "abc"
*
- *
+ *
* Spaces are defined as {' ', '\t', '\r', '\n', '\b'}
* in line with the deprecated isSpace
method.
*
@@ -2380,76 +3489,286 @@
* StringUtils.deleteWhitespace("abc") = "abc"
* StringUtils.deleteWhitespace(" ab c ") = "abc"
*
- *
+ *
* @param str the String to delete whitespace from, may be null
* @return the String without whitespaces, null
if null String input
*/
public static String deleteWhitespace(String str) {
- if (str == null) {
- return null;
+ if (isEmpty(str)) {
+ return str;
}
int sz = str.length();
- StringBuffer buffer = new StringBuffer(sz);
+ char[] chs = new char[sz];
+ int count = 0;
for (int i = 0; i < sz; i++) {
if (!Character.isWhitespace(str.charAt(i))) {
- buffer.append(str.charAt(i));
+ chs[count++] = str.charAt(i);
}
}
- return buffer.toString();
+ if (count == sz) {
+ return str;
+ }
+ return new String(chs, 0, count);
}
+ // Remove
+ //-----------------------------------------------------------------------
+ /**
+ * Removes a substring only if it is at the begining of a source string,
+ * otherwise returns the source string.
+ *
+ * A null
source string will return null
.
+ * An empty ("") source string will return the empty string.
+ * A null
search string will return the source string.
+ *
+ *
+ * StringUtils.removeStart(null, *) = null
+ * StringUtils.removeStart("", *) = ""
+ * StringUtils.removeStart(*, null) = *
+ * StringUtils.removeStart("www.domain.com", "www.") = "domain.com"
+ * StringUtils.removeStart("domain.com", "www.") = "domain.com"
+ * StringUtils.removeStart("www.domain.com", "domain") = "www.domain.com"
+ * StringUtils.removeStart("abc", "") = "abc"
+ *
+ *
+ * @param str the source String to search, may be null
+ * @param remove the String to search for and remove, may be null
+ * @return the substring with the string removed if found,
+ * null
if null String input
+ * @since 2.1
+ */
+ public static String removeStart(String str, String remove) {
+ if (isEmpty(str) || isEmpty(remove)) {
+ return str;
+ }
+ if (str.startsWith(remove)){
+ return str.substring(remove.length());
+ }
+ return str;
+ }
+
+ /**
+ * Case insensitive removal of a substring if it is at the begining of a source string,
+ * otherwise returns the source string.
+ *
+ * A null
source string will return null
.
+ * An empty ("") source string will return the empty string.
+ * A null
search string will return the source string.
+ *
+ *
+ * StringUtils.removeStartIgnoreCase(null, *) = null
+ * StringUtils.removeStartIgnoreCase("", *) = ""
+ * StringUtils.removeStartIgnoreCase(*, null) = *
+ * StringUtils.removeStartIgnoreCase("www.domain.com", "www.") = "domain.com"
+ * StringUtils.removeStartIgnoreCase("www.domain.com", "WWW.") = "domain.com"
+ * StringUtils.removeStartIgnoreCase("domain.com", "www.") = "domain.com"
+ * StringUtils.removeStartIgnoreCase("www.domain.com", "domain") = "www.domain.com"
+ * StringUtils.removeStartIgnoreCase("abc", "") = "abc"
+ *
+ *
+ * @param str the source String to search, may be null
+ * @param remove the String to search for (case insensitive) and remove, may be null
+ * @return the substring with the string removed if found,
+ * null
if null String input
+ * @since 2.4
+ */
+ public static String removeStartIgnoreCase(String str, String remove) {
+ if (isEmpty(str) || isEmpty(remove)) {
+ return str;
+ }
+ if (startsWithIgnoreCase(str, remove)) {
+ return str.substring(remove.length());
+ }
+ return str;
+ }
+
+ /**
+ * Removes a substring only if it is at the end of a source string,
+ * otherwise returns the source string.
+ *
+ * A null
source string will return null
.
+ * An empty ("") source string will return the empty string.
+ * A null
search string will return the source string.
+ *
+ *
+ * StringUtils.removeEnd(null, *) = null
+ * StringUtils.removeEnd("", *) = ""
+ * StringUtils.removeEnd(*, null) = *
+ * StringUtils.removeEnd("www.domain.com", ".com.") = "www.domain.com"
+ * StringUtils.removeEnd("www.domain.com", ".com") = "www.domain"
+ * StringUtils.removeEnd("www.domain.com", "domain") = "www.domain.com"
+ * StringUtils.removeEnd("abc", "") = "abc"
+ *
+ *
+ * @param str the source String to search, may be null
+ * @param remove the String to search for and remove, may be null
+ * @return the substring with the string removed if found,
+ * null
if null String input
+ * @since 2.1
+ */
+ public static String removeEnd(String str, String remove) {
+ if (isEmpty(str) || isEmpty(remove)) {
+ return str;
+ }
+ if (str.endsWith(remove)) {
+ return str.substring(0, str.length() - remove.length());
+ }
+ return str;
+ }
+
+ /**
+ * Case insensitive removal of a substring if it is at the end of a source string,
+ * otherwise returns the source string.
+ *
+ * A null
source string will return null
.
+ * An empty ("") source string will return the empty string.
+ * A null
search string will return the source string.
+ *
+ *
+ * StringUtils.removeEndIgnoreCase(null, *) = null
+ * StringUtils.removeEndIgnoreCase("", *) = ""
+ * StringUtils.removeEndIgnoreCase(*, null) = *
+ * StringUtils.removeEndIgnoreCase("www.domain.com", ".com.") = "www.domain.com"
+ * StringUtils.removeEndIgnoreCase("www.domain.com", ".com") = "www.domain"
+ * StringUtils.removeEndIgnoreCase("www.domain.com", "domain") = "www.domain.com"
+ * StringUtils.removeEndIgnoreCase("abc", "") = "abc"
+ * StringUtils.removeEndIgnoreCase("www.domain.com", ".COM") = "www.domain")
+ * StringUtils.removeEndIgnoreCase("www.domain.COM", ".com") = "www.domain")
+ *
+ *
+ * @param str the source String to search, may be null
+ * @param remove the String to search for (case insensitive) and remove, may be null
+ * @return the substring with the string removed if found,
+ * null
if null String input
+ * @since 2.4
+ */
+ public static String removeEndIgnoreCase(String str, String remove) {
+ if (isEmpty(str) || isEmpty(remove)) {
+ return str;
+ }
+ if (endsWithIgnoreCase(str, remove)) {
+ return str.substring(0, str.length() - remove.length());
+ }
+ return str;
+ }
+
+ /**
+ * Removes all occurrences of a substring from within the source string.
+ *
+ * A null
source string will return null
.
+ * An empty ("") source string will return the empty string.
+ * A null
remove string will return the source string.
+ * An empty ("") remove string will return the source string.
+ *
+ *
+ * StringUtils.remove(null, *) = null
+ * StringUtils.remove("", *) = ""
+ * StringUtils.remove(*, null) = *
+ * StringUtils.remove(*, "") = *
+ * StringUtils.remove("queued", "ue") = "qd"
+ * StringUtils.remove("queued", "zz") = "queued"
+ *
+ *
+ * @param str the source String to search, may be null
+ * @param remove the String to search for and remove, may be null
+ * @return the substring with the string removed if found,
+ * null
if null String input
+ * @since 2.1
+ */
+ public static String remove(String str, String remove) {
+ if (isEmpty(str) || isEmpty(remove)) {
+ return str;
+ }
+ return replace(str, remove, EMPTY, -1);
+ }
+
+ /**
+ * Removes all occurrences of a character from within the source string.
+ *
+ * A null
source string will return null
.
+ * An empty ("") source string will return the empty string.
+ *
+ *
+ * StringUtils.remove(null, *) = null
+ * StringUtils.remove("", *) = ""
+ * StringUtils.remove("queued", 'u') = "qeed"
+ * StringUtils.remove("queued", 'z') = "queued"
+ *
+ *
+ * @param str the source String to search, may be null
+ * @param remove the char to search for and remove, may be null
+ * @return the substring with the char removed if found,
+ * null
if null String input
+ * @since 2.1
+ */
+ public static String remove(String str, char remove) {
+ if (isEmpty(str) || str.indexOf(remove) == INDEX_NOT_FOUND) {
+ return str;
+ }
+ char[] chars = str.toCharArray();
+ int pos = 0;
+ for (int i = 0; i < chars.length; i++) {
+ if (chars[i] != remove) {
+ chars[pos++] = chars[i];
+ }
+ }
+ return new String(chars, 0, pos);
+ }
+
// Replacing
//-----------------------------------------------------------------------
/**
* Replaces a String with another String inside a larger String, once.
- *
+ *
* A null
reference passed to this method is a no-op.
- *
+ *
*
* StringUtils.replaceOnce(null, *, *) = null
* StringUtils.replaceOnce("", *, *) = ""
- * StringUtils.replaceOnce("aba", null, null) = "aba"
- * StringUtils.replaceOnce("aba", null, null) = "aba"
+ * StringUtils.replaceOnce("any", null, *) = "any"
+ * StringUtils.replaceOnce("any", *, null) = "any"
+ * StringUtils.replaceOnce("any", "", *) = "any"
* StringUtils.replaceOnce("aba", "a", null) = "aba"
- * StringUtils.replaceOnce("aba", "a", "") = "aba"
+ * StringUtils.replaceOnce("aba", "a", "") = "ba"
* StringUtils.replaceOnce("aba", "a", "z") = "zba"
*
- *
- * @see #replace(String text, String repl, String with, int max)
+ *
+ * @see #replace(String text, String searchString, String replacement, int max)
* @param text text to search and replace in, may be null
- * @param repl the String to search for, may be null
- * @param with the String to replace with, may be null
+ * @param searchString the String to search for, may be null
+ * @param replacement the String to replace with, may be null
* @return the text with any replacements processed,
* null
if null String input
*/
- public static String replaceOnce(String text, String repl, String with) {
- return replace(text, repl, with, 1);
+ public static String replaceOnce(String text, String searchString, String replacement) {
+ return replace(text, searchString, replacement, 1);
}
/**
- * Replaces all occurances of a String within another String.
+ * Replaces all occurrences of a String within another String.
*
* A null
reference passed to this method is a no-op.
- *
+ *
*
* StringUtils.replace(null, *, *) = null
* StringUtils.replace("", *, *) = ""
- * StringUtils.replace("aba", null, null) = "aba"
- * StringUtils.replace("aba", null, null) = "aba"
+ * StringUtils.replace("any", null, *) = "any"
+ * StringUtils.replace("any", *, null) = "any"
+ * StringUtils.replace("any", "", *) = "any"
* StringUtils.replace("aba", "a", null) = "aba"
- * StringUtils.replace("aba", "a", "") = "aba"
+ * StringUtils.replace("aba", "a", "") = "b"
* StringUtils.replace("aba", "a", "z") = "zbz"
*
- *
- * @see #replace(String text, String repl, String with, int max)
+ *
+ * @see #replace(String text, String searchString, String replacement, int max)
* @param text text to search and replace in, may be null
- * @param repl the String to search for, may be null
- * @param with the String to replace with, may be null
+ * @param searchString the String to search for, may be null
+ * @param replacement the String to replace it with, may be null
* @return the text with any replacements processed,
* null
if null String input
*/
- public static String replace(String text, String repl, String with) {
- return replace(text, repl, with, -1);
+ public static String replace(String text, String searchString, String replacement) {
+ return replace(text, searchString, replacement, -1);
}
/**
@@ -2461,58 +3780,341 @@
*
* StringUtils.replace(null, *, *, *) = null
* StringUtils.replace("", *, *, *) = ""
- * StringUtils.replace("abaa", null, null, 1) = "abaa"
- * StringUtils.replace("abaa", null, null, 1) = "abaa"
- * StringUtils.replace("abaa", "a", null, 1) = "abaa"
- * StringUtils.replace("abaa", "a", "", 1) = "abaa"
+ * StringUtils.replace("any", null, *, *) = "any"
+ * StringUtils.replace("any", *, null, *) = "any"
+ * StringUtils.replace("any", "", *, *) = "any"
+ * StringUtils.replace("any", *, *, 0) = "any"
+ * StringUtils.replace("abaa", "a", null, -1) = "abaa"
+ * StringUtils.replace("abaa", "a", "", -1) = "b"
* StringUtils.replace("abaa", "a", "z", 0) = "abaa"
* StringUtils.replace("abaa", "a", "z", 1) = "zbaa"
* StringUtils.replace("abaa", "a", "z", 2) = "zbza"
* StringUtils.replace("abaa", "a", "z", -1) = "zbzz"
*
- *
+ *
* @param text text to search and replace in, may be null
- * @param repl the String to search for, may be null
- * @param with the String to replace with, may be null
+ * @param searchString the String to search for, may be null
+ * @param replacement the String to replace it with, may be null
* @param max maximum number of values to replace, or -1
if no maximum
* @return the text with any replacements processed,
* null
if null String input
*/
- public static String replace(String text, String repl, String with, int max) {
- if (text == null || repl == null || with == null || repl.length() == 0 || max == 0) {
+ public static String replace(String text, String searchString, String replacement, int max) {
+ if (isEmpty(text) || isEmpty(searchString) || replacement == null || max == 0) {
return text;
}
-
- StringBuffer buf = new StringBuffer(text.length());
- int start = 0, end = 0;
- while ((end = text.indexOf(repl, start)) != -1) {
- buf.append(text.substring(start, end)).append(with);
- start = end + repl.length();
-
+ int start = 0;
+ int end = text.indexOf(searchString, start);
+ if (end == INDEX_NOT_FOUND) {
+ return text;
+ }
+ int replLength = searchString.length();
+ int increase = replacement.length() - replLength;
+ increase = (increase < 0 ? 0 : increase);
+ increase *= (max < 0 ? 16 : (max > 64 ? 64 : max));
+ StrBuilder buf = new StrBuilder(text.length() + increase);
+ while (end != INDEX_NOT_FOUND) {
+ buf.append(text.substring(start, end)).append(replacement);
+ start = end + replLength;
if (--max == 0) {
break;
}
+ end = text.indexOf(searchString, start);
}
buf.append(text.substring(start));
return buf.toString();
}
-
+
+ /**
+ *
+ * Replaces all occurrences of Strings within another String.
+ *
+ *
+ *
+ * A null
reference passed to this method is a no-op, or if
+ * any "search string" or "string to replace" is null, that replace will be
+ * ignored. This will not repeat. For repeating replaces, call the
+ * overloaded method.
+ *
+ *
+ *
+ * StringUtils.replaceEach(null, *, *) = null
+ * StringUtils.replaceEach("", *, *) = ""
+ * StringUtils.replaceEach("aba", null, null) = "aba"
+ * StringUtils.replaceEach("aba", new String[0], null) = "aba"
+ * StringUtils.replaceEach("aba", null, new String[0]) = "aba"
+ * StringUtils.replaceEach("aba", new String[]{"a"}, null) = "aba"
+ * StringUtils.replaceEach("aba", new String[]{"a"}, new String[]{""}) = "b"
+ * StringUtils.replaceEach("aba", new String[]{null}, new String[]{"a"}) = "aba"
+ * StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"w", "t"}) = "wcte"
+ * (example of how it does not repeat)
+ * StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"}) = "dcte"
+ *
+ *
+ * @param text
+ * text to search and replace in, no-op if null
+ * @param searchList
+ * the Strings to search for, no-op if null
+ * @param replacementList
+ * the Strings to replace them with, no-op if null
+ * @return the text with any replacements processed, null
if
+ * null String input
+ * @throws IndexOutOfBoundsException
+ * if the lengths of the arrays are not the same (null is ok,
+ * and/or size 0)
+ * @since 2.4
+ */
+ public static String replaceEach(String text, String[] searchList, String[] replacementList) {
+ return replaceEach(text, searchList, replacementList, false, 0);
+ }
+
+ /**
+ *
+ * Replaces all occurrences of Strings within another String.
+ *
+ *
+ *
+ * A null
reference passed to this method is a no-op, or if
+ * any "search string" or "string to replace" is null, that replace will be
+ * ignored. This will not repeat. For repeating replaces, call the
+ * overloaded method.
+ *
+ *
+ *
+ * StringUtils.replaceEach(null, *, *, *) = null
+ * StringUtils.replaceEach("", *, *, *) = ""
+ * StringUtils.replaceEach("aba", null, null, *) = "aba"
+ * StringUtils.replaceEach("aba", new String[0], null, *) = "aba"
+ * StringUtils.replaceEach("aba", null, new String[0], *) = "aba"
+ * StringUtils.replaceEach("aba", new String[]{"a"}, null, *) = "aba"
+ * StringUtils.replaceEach("aba", new String[]{"a"}, new String[]{""}, *) = "b"
+ * StringUtils.replaceEach("aba", new String[]{null}, new String[]{"a"}, *) = "aba"
+ * StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"w", "t"}, *) = "wcte"
+ * (example of how it repeats)
+ * StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"}, false) = "dcte"
+ * StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"}, true) = "tcte"
+ * StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "ab"}, true) = IllegalArgumentException
+ * StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "ab"}, false) = "dcabe"
+ *
+ *
+ * @param text
+ * text to search and replace in, no-op if null
+ * @param searchList
+ * the Strings to search for, no-op if null
+ * @param replacementList
+ * the Strings to replace them with, no-op if null
+ * @return the text with any replacements processed, null
if
+ * null String input
+ * @throws IllegalArgumentException
+ * if the search is repeating and there is an endless loop due
+ * to outputs of one being inputs to another
+ * @throws IndexOutOfBoundsException
+ * if the lengths of the arrays are not the same (null is ok,
+ * and/or size 0)
+ * @since 2.4
+ */
+ public static String replaceEachRepeatedly(String text, String[] searchList, String[] replacementList) {
+ // timeToLive should be 0 if not used or nothing to replace, else it's
+ // the length of the replace array
+ int timeToLive = searchList == null ? 0 : searchList.length;
+ return replaceEach(text, searchList, replacementList, true, timeToLive);
+ }
+
+ /**
+ *
+ * Replaces all occurrences of Strings within another String.
+ *
+ *
+ *
+ * A null
reference passed to this method is a no-op, or if
+ * any "search string" or "string to replace" is null, that replace will be
+ * ignored.
+ *
+ *
+ *
+ * StringUtils.replaceEach(null, *, *, *) = null
+ * StringUtils.replaceEach("", *, *, *) = ""
+ * StringUtils.replaceEach("aba", null, null, *) = "aba"
+ * StringUtils.replaceEach("aba", new String[0], null, *) = "aba"
+ * StringUtils.replaceEach("aba", null, new String[0], *) = "aba"
+ * StringUtils.replaceEach("aba", new String[]{"a"}, null, *) = "aba"
+ * StringUtils.replaceEach("aba", new String[]{"a"}, new String[]{""}, *) = "b"
+ * StringUtils.replaceEach("aba", new String[]{null}, new String[]{"a"}, *) = "aba"
+ * StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"w", "t"}, *) = "wcte"
+ * (example of how it repeats)
+ * StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"}, false) = "dcte"
+ * StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"}, true) = "tcte"
+ * StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "ab"}, *) = IllegalArgumentException
+ *
+ *
+ * @param text
+ * text to search and replace in, no-op if null
+ * @param searchList
+ * the Strings to search for, no-op if null
+ * @param replacementList
+ * the Strings to replace them with, no-op if null
+ * @param repeat if true, then replace repeatedly
+ * until there are no more possible replacements or timeToLive < 0
+ * @param timeToLive
+ * if less than 0 then there is a circular reference and endless
+ * loop
+ * @return the text with any replacements processed, null
if
+ * null String input
+ * @throws IllegalArgumentException
+ * if the search is repeating and there is an endless loop due
+ * to outputs of one being inputs to another
+ * @throws IndexOutOfBoundsException
+ * if the lengths of the arrays are not the same (null is ok,
+ * and/or size 0)
+ * @since 2.4
+ */
+ private static String replaceEach(String text, String[] searchList, String[] replacementList,
+ boolean repeat, int timeToLive)
+ {
+
+ // 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 (text == null || text.length() == 0 || searchList == null ||
+ searchList.length == 0 || replacementList == null || replacementList.length == 0)
+ {
+ return text;
+ }
+
+ // if recursing, this shouldnt be less than 0
+ if (timeToLive < 0) {
+ throw new IllegalStateException("TimeToLive of " + timeToLive + " is less than 0: " + text);
+ }
+
+ int searchLength = searchList.length;
+ int replacementLength = replacementList.length;
+
+ // make sure lengths are ok, these need to be equal
+ if (searchLength != replacementLength) {
+ throw new IllegalArgumentException("Search and Replace array lengths don't match: "
+ + searchLength
+ + " vs "
+ + replacementLength);
+ }
+
+ // keep track of which still have matches
+ boolean[] noMoreMatchesForReplIndex = new boolean[searchLength];
+
+ // index on index that the match was found
+ int textIndex = -1;
+ int replaceIndex = -1;
+ int tempIndex = -1;
+
+ // 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].length() == 0 || replacementList[i] == null)
+ {
+ continue;
+ }
+ tempIndex = text.indexOf(searchList[i]);
+
+ // see if we need to keep searching for this
+ if (tempIndex == -1) {
+ noMoreMatchesForReplIndex[i] = true;
+ } else {
+ if (textIndex == -1 || tempIndex < textIndex) {
+ textIndex = tempIndex;
+ replaceIndex = i;
+ }
+ }
+ }
+ // NOTE: logic mostly below END
+
+ // no search strings found, we are done
+ if (textIndex == -1) {
+ return text;
+ }
+
+ int start = 0;
+
+ // get a good guess on the size of the result buffer so it doesnt have to double if it goes over a bit
+ int increase = 0;
+
+ // count the replacement text elements that are larger than their corresponding text being replaced
+ for (int i = 0; i < searchList.length; i++) {
+ if (searchList[i] == null || replacementList[i] == null) {
+ continue;
+ }
+ int greater = replacementList[i].length() - searchList[i].length();
+ if (greater > 0) {
+ increase += 3 * greater; // assume 3 matches
+ }
+ }
+ // have upper-bound at 20% increase, then let Java take over
+ increase = Math.min(increase, text.length() / 5);
+
+ StrBuilder buf = new StrBuilder(text.length() + increase);
+
+ while (textIndex != -1) {
+
+ for (int i = start; i < textIndex; i++) {
+ buf.append(text.charAt(i));
+ }
+ buf.append(replacementList[replaceIndex]);
+
+ start = textIndex + searchList[replaceIndex].length();
+
+ textIndex = -1;
+ replaceIndex = -1;
+ tempIndex = -1;
+ // find the next earliest match
+ // NOTE: logic mostly duplicated above START
+ for (int i = 0; i < searchLength; i++) {
+ if (noMoreMatchesForReplIndex[i] || searchList[i] == null ||
+ searchList[i].length() == 0 || replacementList[i] == null)
+ {
+ continue;
+ }
+ tempIndex = text.indexOf(searchList[i], start);
+
+ // see if we need to keep searching for this
+ if (tempIndex == -1) {
+ noMoreMatchesForReplIndex[i] = true;
+ } else {
+ if (textIndex == -1 || tempIndex < textIndex) {
+ textIndex = tempIndex;
+ replaceIndex = i;
+ }
+ }
+ }
+ // NOTE: logic duplicated above END
+
+ }
+ int textLength = text.length();
+ for (int i = start; i < textLength; i++) {
+ buf.append(text.charAt(i));
+ }
+ String result = buf.toString();
+ if (!repeat) {
+ return result;
+ }
+
+ return replaceEach(result, searchList, replacementList, repeat, timeToLive - 1);
+ }
+
// Replace, character based
//-----------------------------------------------------------------------
/**
- * Replaces all occurrances of a character in a String with another.
+ *
Replaces all occurrences of a character in a String with another.
* This is a null-safe version of {@link String#replace(char, char)}.
*
* A null
string input returns null
.
* An empty ("") string input returns an empty string.
- *
+ *
*
* StringUtils.replaceChars(null, *, *) = null
* StringUtils.replaceChars("", *, *) = ""
* StringUtils.replaceChars("abcba", 'b', 'y') = "aycya"
* StringUtils.replaceChars("abcba", 'z', 'y') = "abcba"
*
- *
+ *
* @param str String to replace characters in, may be null
* @param searchChar the character to search for, may be null
* @param replaceChar the character to replace, may be null
@@ -2525,25 +4127,25 @@
}
return str.replace(searchChar, replaceChar);
}
-
+
/**
* Replaces multiple characters in a String in one go.
* This method can also be used to delete characters.
*
* For example:
* replaceChars("hello", "ho", "jy") = jelly
.
- *
+ *
* A null
string input returns null
.
* An empty ("") string input returns an empty string.
* A null or empty set of search characters returns the input string.
- *
+ *
* The length of the search characters should normally equal the length
* of the replace characters.
* If the search characters is longer, then the extra search characters
* are deleted.
* If the search characters is shorter, then the extra replace characters
* are ignored.
- *
+ *
*
* StringUtils.replaceChars(null, *, *) = null
* StringUtils.replaceChars("", *, *) = ""
@@ -2555,47 +4157,40 @@
* StringUtils.replaceChars("abcba", "bc", "y") = "ayya"
* StringUtils.replaceChars("abcba", "bc", "yzx") = "ayzya"
*
- *
+ *
* @param str String to replace characters in, may be null
* @param searchChars a set of characters to search for, may be null
* @param replaceChars a set of characters to replace, may be null
* @return modified String, null
if null string input
* @since 2.0
*/
public static String replaceChars(String str, String searchChars, String replaceChars) {
- if (str == null || str.length() == 0 || searchChars == null || searchChars.length()== 0) {
+ if (isEmpty(str) || isEmpty(searchChars)) {
return str;
}
- char[] chars = str.toCharArray();
- int len = chars.length;
+ if (replaceChars == null) {
+ replaceChars = EMPTY;
+ }
boolean modified = false;
- for (int i = 0, isize = searchChars.length(); i < isize; i++) {
- char searchChar = searchChars.charAt(i);
- if (replaceChars == null || i >= replaceChars.length()) {
- // delete
- int pos = 0;
- for (int j = 0; j < len; j++) {
- if (chars[j] != searchChar) {
- chars[pos++] = chars[j];
- } else {
- modified = true;
- }
+ int replaceCharsLength = replaceChars.length();
+ int strLength = str.length();
+ StrBuilder buf = new StrBuilder(strLength);
+ for (int i = 0; i < strLength; i++) {
+ char ch = str.charAt(i);
+ int index = searchChars.indexOf(ch);
+ if (index >= 0) {
+ modified = true;
+ if (index < replaceCharsLength) {
+ buf.append(replaceChars.charAt(index));
}
- len = pos;
} else {
- // replace
- for (int j = 0; j < len; j++) {
- if (chars[j] == searchChar) {
- chars[j] = replaceChars.charAt(i);
- modified = true;
- }
- }
+ buf.append(ch);
}
}
- if (modified == false) {
- return str;
+ if (modified) {
+ return buf.toString();
}
- return new String(chars, 0, len);
+ return str;
}
// Overlay
@@ -2614,7 +4209,7 @@
* StringUtils.overlayString("abcdef", "zzzz", -1, 4) = IndexOutOfBoundsException
* StringUtils.overlayString("abcdef", "zzzz", 2, 8) = IndexOutOfBoundsException
*
- *
+ *
* @param text the String to do overlaying in, may be null
* @param overlay the String to overlay, may be null
* @param start the position to start overlaying at, must be valid
@@ -2626,7 +4221,7 @@
* Method will be removed in Commons Lang 3.0.
*/
public static String overlayString(String text, String overlay, int start, int end) {
- return new StringBuffer(start + overlay.length() + text.length() - end + 1)
+ return new StrBuilder(start + overlay.length() + text.length() - end + 1)
.append(text.substring(0, start))
.append(overlay)
.append(text.substring(end))
@@ -2635,7 +4230,7 @@
/**
* Overlays part of a String with another String.
- *
+ *
* A null
string input returns null
.
* A negative index is treated as zero.
* An index greater than the string length is treated as the string length.
@@ -2654,7 +4249,7 @@
* StringUtils.overlay("abcdef", "zzzz", -2, -3) = "zzzzabcdef"
* StringUtils.overlay("abcdef", "zzzz", 8, 10) = "abcdefzzzz"
*
- *
+ *
* @param str the String to do overlaying in, may be null
* @param overlay the String to overlay, may be null
* @param start the position to start overlaying at
@@ -2687,7 +4282,7 @@
start = end;
end = temp;
}
- return new StringBuffer(len + start - end + overlay.length() + 1)
+ return new StrBuilder(len + start - end + overlay.length() + 1)
.append(str.substring(0, start))
.append(overlay)
.append(str.substring(end))
@@ -2722,29 +4317,26 @@
* @return String without newline, null
if null String input
*/
public static String chomp(String str) {
- if (str == null || str.length() == 0) {
+ if (isEmpty(str)) {
return str;
}
if (str.length() == 1) {
char ch = str.charAt(0);
- if (ch == '\r' || ch == '\n') {
+ if (ch == CharUtils.CR || ch == CharUtils.LF) {
return EMPTY;
- } else {
- return str;
}
+ return str;
}
int lastIdx = str.length() - 1;
char last = str.charAt(lastIdx);
- if (last == '\n') {
- if (str.charAt(lastIdx - 1) == '\r') {
+ if (last == CharUtils.LF) {
+ if (str.charAt(lastIdx - 1) == CharUtils.CR) {
lastIdx--;
}
- } else if (last == '\r') {
-
- } else {
+ } else if (last != CharUtils.CR) {
lastIdx++;
}
return str.substring(0, lastIdx);
@@ -2765,7 +4357,7 @@
* StringUtils.chomp("foobar", "bar") = "foo"
* StringUtils.chomp("foobar", "baz") = "foobar"
* StringUtils.chomp("foo", "foo") = ""
- * StringUtils.chomp("foo ", "foo") = "foo"
+ * StringUtils.chomp("foo ", "foo") = "foo "
* StringUtils.chomp(" foo", "foo") = " "
* StringUtils.chomp("foo", "foooo") = "foo"
* StringUtils.chomp("foo", "") = "foo"
@@ -2777,7 +4369,7 @@
* @return String without trailing separator, null
if null String input
*/
public static String chomp(String str, String separator) {
- if (str == null || str.length() == 0 || separator == null) {
+ if (isEmpty(str) || separator == null) {
return str;
}
if (str.endsWith(separator)) {
@@ -2789,7 +4381,7 @@
/**
* Remove any "\n" if and only if it is at the end
* of the supplied String.
- *
+ *
* @param str the String to chomp from, must not be null
* @return String without chomped ending
* @throws NullPointerException if str is null
@@ -2799,10 +4391,10 @@
public static String chompLast(String str) {
return chompLast(str, "\n");
}
-
+
/**
* Remove a value if and only if the String ends with that value.
- *
+ *
* @param str the String to chomp from, must not be null
* @param sep the String to chomp, must not be null
* @return String without chomped ending
@@ -2817,12 +4409,11 @@
String sub = str.substring(str.length() - sep.length());
if (sep.equals(sub)) {
return str.substring(0, str.length() - sep.length());
- } else {
- return str;
}
+ return str;
}
- /**
+ /**
* Remove everything and return the last value of a supplied String, and
* everything after it from a String.
*
@@ -2845,7 +4436,7 @@
}
}
- /**
+ /**
* Remove the first value of a supplied String, and everything before it
* from a String.
*
@@ -2858,14 +4449,13 @@
*/
public static String prechomp(String str, String sep) {
int idx = str.indexOf(sep);
- if (idx != -1) {
- return str.substring(idx + sep.length());
- } else {
+ if (idx == -1) {
return str;
- }
+ }
+ return str.substring(idx + sep.length());
}
- /**
+ /**
* Remove and return everything before the first value of a
* supplied String from another String.
*
@@ -2879,11 +4469,10 @@
*/
public static String getPrechomp(String str, String sep) {
int idx = str.indexOf(sep);
- if (idx != -1) {
- return str.substring(0, idx + sep.length());
- } else {
+ if (idx == -1) {
return EMPTY;
- }
+ }
+ return str.substring(0, idx + sep.length());
}
// Chopping
@@ -2922,8 +4511,8 @@
int lastIdx = strLen - 1;
String ret = str.substring(0, lastIdx);
char last = str.charAt(lastIdx);
- if (last == '\n') {
- if (ret.charAt(lastIdx - 1) == '\r') {
+ if (last == CharUtils.LF) {
+ if (ret.charAt(lastIdx - 1) == CharUtils.CR) {
return ret.substring(0, lastIdx - 1);
}
}
@@ -2946,8 +4535,8 @@
return EMPTY;
}
char last = str.charAt(lastIdx);
- if (last == '\n') {
- if (str.charAt(lastIdx - 1) == '\r') {
+ if (last == CharUtils.LF) {
+ if (str.charAt(lastIdx - 1) == CharUtils.CR) {
lastIdx--;
}
} else {
@@ -2956,7 +4545,6 @@
return str.substring(0, lastIdx);
}
-
// Conversion
//-----------------------------------------------------------------------
/**
@@ -3001,7 +4589,7 @@
*/
public static String repeat(String str, int repeat) {
// Performance tuned for 2.0 (JDK1.4)
-
+
if (str == null) {
return null;
}
@@ -3013,37 +4601,67 @@
return str;
}
if (inputLength == 1 && repeat <= PAD_LIMIT) {
- return padding(repeat, str.charAt(0));
+ return padding(repeat, str.charAt(0));
}
int outputLength = inputLength * repeat;
switch (inputLength) {
- case 1:
+ case 1 :
char ch = str.charAt(0);
char[] output1 = new char[outputLength];
for (int i = repeat - 1; i >= 0; i--) {
output1[i] = ch;
}
return new String(output1);
- case 2:
+ case 2 :
char ch0 = str.charAt(0);
char ch1 = str.charAt(1);
char[] output2 = new char[outputLength];
- for (int i = repeat * 2 - 2; i >= 0; i--,i--) {
+ for (int i = repeat * 2 - 2; i >= 0; i--, i--) {
output2[i] = ch0;
output2[i + 1] = ch1;
}
return new String(output2);
- default:
- StringBuffer buf = new StringBuffer(outputLength);
+ default :
+ StrBuilder buf = new StrBuilder(outputLength);
for (int i = 0; i < repeat; i++) {
buf.append(str);
- }
+ }
return buf.toString();
}
}
/**
+ * Repeat a String repeat
times to form a
+ * new String, with a String separator injected each time.
+ *
+ *
+ * StringUtils.repeat(null, null, 2) = null
+ * StringUtils.repeat(null, "x", 2) = null
+ * StringUtils.repeat("", null, 0) = ""
+ * StringUtils.repeat("", "", 2) = ""
+ * StringUtils.repeat("", "x", 3) = "xxx"
+ * StringUtils.repeat("?", ", ", 3) = "?, ?, ?"
+ *
+ *
+ * @param str the String to repeat, may be null
+ * @param separator the String to inject, may be null
+ * @param repeat number of times to repeat str, negative treated as zero
+ * @return a new String consisting of the original String repeated,
+ * null
if null String input
+ * @since 2.5
+ */
+ public static String repeat(String str, String separator, int repeat) {
+ if(str == null || separator == null) {
+ return repeat(str, repeat);
+ } else {
+ // given that repeat(String, int) is quite optimized, better to rely on it than try and splice this into it
+ String result = repeat(str + separator, repeat);
+ return removeEnd(result, separator);
+ }
+ }
+
+ /**
* Returns padding using the specified delimiter repeated
* to a given length.
*
@@ -3053,30 +4671,35 @@
* StringUtils.padding(-2, 'e') = IndexOutOfBoundsException
*
*
+ * Note: this method doesn't not support padding with
+ * Unicode Supplementary Characters
+ * as they require a pair of char
s to be represented.
+ * If you are needing to support full I18N of your applications
+ * consider using {@link #repeat(String, int)} instead.
+ *
+ *
* @param repeat number of times to repeat delim
* @param padChar character to repeat
* @return String with repeated character
* @throws IndexOutOfBoundsException if repeat < 0
+ * @see #repeat(String, int)
*/
- private static String padding(int repeat, char padChar) {
- // be careful of synchronization in this method
- // we are assuming that get and set from an array index is atomic
- String pad = PADDING[padChar];
- if (pad == null) {
- pad = String.valueOf(padChar);
+ private static String padding(int repeat, char padChar) throws IndexOutOfBoundsException {
+ if (repeat < 0) {
+ throw new IndexOutOfBoundsException("Cannot pad a negative amount: " + repeat);
}
- while (pad.length() < repeat) {
- pad = pad.concat(pad);
+ final char[] buf = new char[repeat];
+ for (int i = 0; i < buf.length; i++) {
+ buf[i] = padChar;
}
- PADDING[padChar] = pad;
- return pad.substring(0, repeat);
+ return new String(buf);
}
/**
* Right pad a String with spaces (' ').
*
* The String is padded to the size of size
.
- *
+ *
*
* StringUtils.rightPad(null, *) = null
* StringUtils.rightPad("", 3) = " "
@@ -3157,7 +4780,7 @@
if (str == null) {
return null;
}
- if (padStr == null || padStr.length() == 0) {
+ if (isEmpty(padStr)) {
padStr = " ";
}
int padLen = padStr.length();
@@ -3169,7 +4792,7 @@
if (padLen == 1 && pads <= PAD_LIMIT) {
return rightPad(str, size, padStr.charAt(0));
}
-
+
if (pads == padLen) {
return str.concat(padStr);
} else if (pads < padLen) {
@@ -3187,7 +4810,7 @@
/**
* Left pad a String with spaces (' ').
*
- * The String is padded to the size of size.
+ * The String is padded to the size of size
.
*
*
* StringUtils.leftPad(null, *) = null
@@ -3204,7 +4827,7 @@
* null
if null String input
*/
public static String leftPad(String str, int size) {
- return leftPad(str, size, ' ');
+ return leftPad(str, size, ' ');
}
/**
@@ -3269,7 +4892,7 @@
if (str == null) {
return null;
}
- if (padStr == null || padStr.length() == 0) {
+ if (isEmpty(padStr)) {
padStr = " ";
}
int padLen = padStr.length();
@@ -3281,7 +4904,7 @@
if (padLen == 1 && pads <= PAD_LIMIT) {
return leftPad(str, size, padStr.charAt(0));
}
-
+
if (pads == padLen) {
return padStr.concat(str);
} else if (pads < padLen) {
@@ -3296,12 +4919,24 @@
}
}
+ /**
+ * Gets a String's length or 0
if the String is null
.
+ *
+ * @param str
+ * a String or null
+ * @return String length or 0
if the String is null
.
+ * @since 2.4
+ */
+ public static int length(String str) {
+ return str == null ? 0 : str.length();
+ }
+
// Centering
//-----------------------------------------------------------------------
/**
* Centers a String in a larger String of size size
* using the space character (' ').
- *
+ *
*
If the size is less than the String length, the String is returned.
* A null
String returns null
.
* A negative size is treated as zero.
@@ -3316,7 +4951,7 @@
* StringUtils.center("abcd", 2) = "abcd"
* StringUtils.center("a", 4) = " a "
*
- *
+ *
* @param str the String to center, may be null
* @param size the int size of new String, negative treated as zero
* @return centered String, null
if null String input
@@ -3342,7 +4977,7 @@
* StringUtils.center("a", 4, ' ') = " a "
* StringUtils.center("a", 4, 'y') = "yayy"
*
- *
+ *
* @param str the String to center, may be null
* @param size the int size of new String, negative treated as zero
* @param padChar the character to pad the new String with
@@ -3382,7 +5017,7 @@
* StringUtils.center("abc", 7, null) = " abc "
* StringUtils.center("abc", 7, "") = " abc "
*
- *
+ *
* @param str the String to center, may be null
* @param size the int size of new String, negative treated as zero
* @param padStr the String to pad the new String with, must not be null or empty
@@ -3393,7 +5028,7 @@
if (str == null || size <= 0) {
return str;
}
- if (padStr == null || padStr.length() == 0) {
+ if (isEmpty(padStr)) {
padStr = " ";
}
int strLen = str.length();
@@ -3410,15 +5045,20 @@
//-----------------------------------------------------------------------
/**
* Converts a String to upper case as per {@link String#toUpperCase()}.
- *
+ *
* A null
input String returns null
.
- *
+ *
*
* StringUtils.upperCase(null) = null
* StringUtils.upperCase("") = ""
* StringUtils.upperCase("aBc") = "ABC"
*
- *
+ *
+ * Note: As described in the documentation for {@link String#toUpperCase()},
+ * the result of this method is affected by the current locale.
+ * For platform-independent case transformations, the method {@link #lowerCase(String, Locale)}
+ * should be used with a specific locale (e.g. {@link Locale#ENGLISH}).
+ *
* @param str the String to upper case, may be null
* @return the upper cased String, null
if null String input
*/
@@ -3430,16 +5070,44 @@
}
/**
+ * Converts a String to upper case as per {@link String#toUpperCase(Locale)}.
+ *
+ * A null
input String returns null
.
+ *
+ *
+ * StringUtils.upperCase(null, Locale.ENGLISH) = null
+ * StringUtils.upperCase("", Locale.ENGLISH) = ""
+ * StringUtils.upperCase("aBc", Locale.ENGLISH) = "ABC"
+ *
+ *
+ * @param str the String to upper case, may be null
+ * @param locale the locale that defines the case transformation rules, must not be null
+ * @return the upper cased String, null
if null String input
+ * @since 2.5
+ */
+ public static String upperCase(String str, Locale locale) {
+ if (str == null) {
+ return null;
+ }
+ return str.toUpperCase(locale);
+ }
+
+ /**
* Converts a String to lower case as per {@link String#toLowerCase()}.
- *
+ *
* A null
input String returns null
.
- *
+ *
*
* StringUtils.lowerCase(null) = null
* StringUtils.lowerCase("") = ""
* StringUtils.lowerCase("aBc") = "abc"
*
- *
+ *
+ * Note: As described in the documentation for {@link String#toLowerCase()},
+ * the result of this method is affected by the current locale.
+ * For platform-independent case transformations, the method {@link #lowerCase(String, Locale)}
+ * should be used with a specific locale (e.g. {@link Locale#ENGLISH}).
+ *
* @param str the String to lower case, may be null
* @return the lower cased String, null
if null String input
*/
@@ -3451,19 +5119,42 @@
}
/**
+ * Converts a String to lower case as per {@link String#toLowerCase(Locale)}.
+ *
+ * A null
input String returns null
.
+ *
+ *
+ * StringUtils.lowerCase(null, Locale.ENGLISH) = null
+ * StringUtils.lowerCase("", Locale.ENGLISH) = ""
+ * StringUtils.lowerCase("aBc", Locale.ENGLISH) = "abc"
+ *
+ *
+ * @param str the String to lower case, may be null
+ * @param locale the locale that defines the case transformation rules, must not be null
+ * @return the lower cased String, null
if null String input
+ * @since 2.5
+ */
+ public static String lowerCase(String str, Locale locale) {
+ if (str == null) {
+ return null;
+ }
+ return str.toLowerCase(locale);
+ }
+
+ /**
* Capitalizes a String changing the first letter to title case as
* per {@link Character#toTitleCase(char)}. No other letters are changed.
- *
- * For a word based alorithm, see {@link WordUtils#capitalize(String)}.
+ *
+ *
For a word based algorithm, see {@link WordUtils#capitalize(String)}.
* A null
input String returns null
.
- *
+ *
*
* StringUtils.capitalize(null) = null
* StringUtils.capitalize("") = ""
* StringUtils.capitalize("cat") = "Cat"
* StringUtils.capitalize("cAt") = "CAt"
*
- *
+ *
* @param str the String to capitalize, may be null
* @return the capitalized String, null
if null String input
* @see WordUtils#capitalize(String)
@@ -3475,7 +5166,7 @@
if (str == null || (strLen = str.length()) == 0) {
return str;
}
- return new StringBuffer(strLen)
+ return new StrBuilder(strLen)
.append(Character.toTitleCase(str.charAt(0)))
.append(str.substring(1))
.toString();
@@ -3484,7 +5175,7 @@
/**
* Capitalizes a String changing the first letter to title case as
* per {@link Character#toTitleCase(char)}. No other letters are changed.
- *
+ *
* @param str the String to capitalize, may be null
* @return the capitalized String, null
if null String input
* @deprecated Use the standardly named {@link #capitalize(String)}.
@@ -3497,17 +5188,17 @@
/**
* Uncapitalizes a String changing the first letter to title case as
* per {@link Character#toLowerCase(char)}. No other letters are changed.
- *
- * For a word based alorithm, see {@link WordUtils#uncapitalize(String)}.
+ *
+ *
For a word based algorithm, see {@link WordUtils#uncapitalize(String)}.
* A null
input String returns null
.
- *
+ *
*
* StringUtils.uncapitalize(null) = null
* StringUtils.uncapitalize("") = ""
* StringUtils.uncapitalize("Cat") = "cat"
* StringUtils.uncapitalize("CAT") = "cAT"
*
- *
+ *
* @param str the String to uncapitalize, may be null
* @return the uncapitalized String, null
if null String input
* @see WordUtils#uncapitalize(String)
@@ -3519,7 +5210,7 @@
if (str == null || (strLen = str.length()) == 0) {
return str;
}
- return new StringBuffer(strLen)
+ return new StrBuilder(strLen)
.append(Character.toLowerCase(str.charAt(0)))
.append(str.substring(1))
.toString();
@@ -3528,7 +5219,7 @@
/**
* Uncapitalizes a String changing the first letter to title case as
* per {@link Character#toLowerCase(char)}. No other letters are changed.
- *
+ *
* @param str the String to uncapitalize, may be null
* @return the uncapitalized String, null
if null String input
* @deprecated Use the standardly named {@link #uncapitalize(String)}.
@@ -3541,27 +5232,27 @@
/**
* Swaps the case of a String changing upper and title case to
* lower case, and lower case to upper case.
- *
+ *
*
* - Upper case character converts to Lower case
* - Title case character converts to Lower case
* - Lower case character converts to Upper case
*
- *
- * For a word based alorithm, see {@link WordUtils#swapCase(String)}.
+ *
+ *
For a word based algorithm, see {@link WordUtils#swapCase(String)}.
* A null
input String returns null
.
- *
+ *
*
* StringUtils.swapCase(null) = null
* StringUtils.swapCase("") = ""
* StringUtils.swapCase("The dog has a BONE") = "tHE DOG HAS A bone"
*
- *
+ *
* NOTE: This method changed in Lang version 2.0.
- * It no longer performs a word based alorithm.
+ * It no longer performs a word based algorithm.
* If you only use ASCII, you will notice no change.
* That functionality is available in WordUtils.
- *
+ *
* @param str the String to swap case, may be null
* @return the changed String, null
if null String input
*/
@@ -3570,7 +5261,7 @@
if (str == null || (strLen = str.length()) == 0) {
return str;
}
- StringBuffer buffer = new StringBuffer(strLen);
+ StrBuilder buffer = new StrBuilder(strLen);
char ch = 0;
for (int i = 0; i < strLen; i++) {
@@ -3609,7 +5300,7 @@
* Counts how many times the substring appears in the larger String.
*
* A null
or empty ("") String input returns 0
.
- *
+ *
*
* StringUtils.countMatches(null, *) = 0
* StringUtils.countMatches("", *) = 0
@@ -3622,15 +5313,15 @@
*
* @param str the String to check, may be null
* @param sub the substring to count, may be null
- * @return the number of occurances, 0 if either String is null
+ * @return the number of occurrences, 0 if either String is null
*/
public static int countMatches(String str, String sub) {
- if (str == null || str.length() == 0 || sub == null || sub.length() == 0) {
+ if (isEmpty(str) || isEmpty(sub)) {
return 0;
}
int count = 0;
int idx = 0;
- while ((idx = str.indexOf(sub, idx)) != -1) {
+ while ((idx = str.indexOf(sub, idx)) != INDEX_NOT_FOUND) {
count++;
idx += sub.length();
}
@@ -3643,8 +5334,8 @@
* Checks if the String contains only unicode letters.
*
* null
will return false
.
- * An empty String ("") will return true
.
- *
+ * An empty String (length()=0) will return true
.
+ *
*
* StringUtils.isAlpha(null) = false
* StringUtils.isAlpha("") = true
@@ -3675,8 +5366,8 @@
* space (' ').
*
* null
will return false
- * An empty String ("") will return true
.
- *
+ * An empty String (length()=0) will return true
.
+ *
*
* StringUtils.isAlphaSpace(null) = false
* StringUtils.isAlphaSpace("") = true
@@ -3697,8 +5388,7 @@
}
int sz = str.length();
for (int i = 0; i < sz; i++) {
- if ((Character.isLetter(str.charAt(i)) == false) &&
- (str.charAt(i) != ' ')) {
+ if ((Character.isLetter(str.charAt(i)) == false) && (str.charAt(i) != ' ')) {
return false;
}
}
@@ -3709,8 +5399,8 @@
* Checks if the String contains only unicode letters or digits.
*
* null
will return false
.
- * An empty String ("") will return true
.
- *
+ * An empty String (length()=0) will return true
.
+ *
*
* StringUtils.isAlphanumeric(null) = false
* StringUtils.isAlphanumeric("") = true
@@ -3743,8 +5433,8 @@
* or space (' '
).
*
* null
will return false
.
- * An empty String ("") will return true
.
- *
+ * An empty String (length()=0) will return true
.
+ *
*
* StringUtils.isAlphanumeric(null) = false
* StringUtils.isAlphanumeric("") = true
@@ -3765,21 +5455,58 @@
}
int sz = str.length();
for (int i = 0; i < sz; i++) {
- if ((Character.isLetterOrDigit(str.charAt(i)) == false) &&
- (str.charAt(i) != ' ')) {
+ if ((Character.isLetterOrDigit(str.charAt(i)) == false) && (str.charAt(i) != ' ')) {
return false;
}
}
return true;
}
/**
+ * Checks if the string contains only ASCII printable characters.
+ *
+ * null
will return false
.
+ * An empty String (length()=0) will return true
.
+ *
+ *
+ * StringUtils.isAsciiPrintable(null) = false
+ * StringUtils.isAsciiPrintable("") = true
+ * StringUtils.isAsciiPrintable(" ") = true
+ * StringUtils.isAsciiPrintable("Ceki") = true
+ * StringUtils.isAsciiPrintable("ab2c") = true
+ * StringUtils.isAsciiPrintable("!ab-c~") = true
+ * StringUtils.isAsciiPrintable("\u0020") = true
+ * StringUtils.isAsciiPrintable("\u0021") = true
+ * StringUtils.isAsciiPrintable("\u007e") = true
+ * StringUtils.isAsciiPrintable("\u007f") = false
+ * StringUtils.isAsciiPrintable("Ceki G\u00fclc\u00fc") = false
+ *
+ *
+ * @param str the string to check, may be null
+ * @return true
if every character is in the range
+ * 32 thru 126
+ * @since 2.1
+ */
+ public static boolean isAsciiPrintable(String str) {
+ if (str == null) {
+ return false;
+ }
+ int sz = str.length();
+ for (int i = 0; i < sz; i++) {
+ if (CharUtils.isAsciiPrintable(str.charAt(i)) == false) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /**
* Checks if the String contains only unicode digits.
* A decimal point is not a unicode digit and returns false.
*
* null
will return false
.
- * An empty String ("") will return true
.
- *
+ * An empty String (length()=0) will return true
.
+ *
*
* StringUtils.isNumeric(null) = false
* StringUtils.isNumeric("") = true
@@ -3813,8 +5540,8 @@
* A decimal point is not a unicode digit and returns false.
*
* null
will return false
.
- * An empty String ("") will return true
.
- *
+ * An empty String (length()=0) will return true
.
+ *
*
* StringUtils.isNumeric(null) = false
* StringUtils.isNumeric("") = true
@@ -3836,8 +5563,7 @@
}
int sz = str.length();
for (int i = 0; i < sz; i++) {
- if ((Character.isDigit(str.charAt(i)) == false) &&
- (str.charAt(i) != ' ')) {
+ if ((Character.isDigit(str.charAt(i)) == false) && (str.charAt(i) != ' ')) {
return false;
}
}
@@ -3848,8 +5574,8 @@
* Checks if the String contains only whitespace.
*
* null
will return false
.
- * An empty String ("") will return true
.
- *
+ * An empty String (length()=0) will return true
.
+ *
*
* StringUtils.isWhitespace(null) = false
* StringUtils.isWhitespace("") = true
@@ -3869,77 +5595,182 @@
}
int sz = str.length();
for (int i = 0; i < sz; i++) {
- if ((Character.isWhitespace(str.charAt(i)) == false) ) {
+ if ((Character.isWhitespace(str.charAt(i)) == false)) {
return false;
}
}
return true;
}
+ /**
+ * Checks if the String contains only lowercase characters.
+ *
+ * null
will return false
.
+ * An empty String (length()=0) will return false
.
+ *
+ *
+ * StringUtils.isAllLowerCase(null) = false
+ * StringUtils.isAllLowerCase("") = false
+ * StringUtils.isAllLowerCase(" ") = false
+ * StringUtils.isAllLowerCase("abc") = true
+ * StringUtils.isAllLowerCase("abC") = false
+ *
+ *
+ * @param str the String to check, may be null
+ * @return true
if only contains lowercase characters, and is non-null
+ * @since 2.5
+ */
+ public static boolean isAllLowerCase(String str) {
+ if (str == null || isEmpty(str)) {
+ return false;
+ }
+ int sz = str.length();
+ for (int i = 0; i < sz; i++) {
+ if (Character.isLowerCase(str.charAt(i)) == false) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Checks if the String contains only uppercase characters.
+ *
+ * null
will return false
.
+ * An empty String (length()=0) will return false
.
+ *
+ *
+ * StringUtils.isAllUpperCase(null) = false
+ * StringUtils.isAllUpperCase("") = false
+ * StringUtils.isAllUpperCase(" ") = false
+ * StringUtils.isAllUpperCase("ABC") = true
+ * StringUtils.isAllUpperCase("aBC") = false
+ *
+ *
+ * @param str the String to check, may be null
+ * @return true
if only contains uppercase characters, and is non-null
+ * @since 2.5
+ */
+ public static boolean isAllUpperCase(String str) {
+ if (str == null || isEmpty(str)) {
+ return false;
+ }
+ int sz = str.length();
+ for (int i = 0; i < sz; i++) {
+ if (Character.isUpperCase(str.charAt(i)) == false) {
+ return false;
+ }
+ }
+ return true;
+ }
+
// Defaults
//-----------------------------------------------------------------------
/**
- * Returns either the passed in String,
+ *
Returns either the passed in String,
* or if the String is null
, an empty String ("").
- *
+ *
*
* StringUtils.defaultString(null) = ""
* StringUtils.defaultString("") = ""
* StringUtils.defaultString("bat") = "bat"
*
- *
+ *
* @see ObjectUtils#toString(Object)
* @see String#valueOf(Object)
* @param str the String to check, may be null
* @return the passed in String, or the empty String if it
* was null
*/
public static String defaultString(String str) {
- return (str == null ? EMPTY : str);
+ return str == null ? EMPTY : str;
}
/**
- * Returns either the passed in String,
- * or if the String is null
, an empty String ("").
- *
+ * Returns either the passed in String, or if the String is
+ * null
, the value of defaultStr
.
+ *
*
- * StringUtils.defaultString(null, "null") = "null"
- * StringUtils.defaultString("", "null") = ""
- * StringUtils.defaultString("bat", "null") = "bat"
+ * StringUtils.defaultString(null, "NULL") = "NULL"
+ * StringUtils.defaultString("", "NULL") = ""
+ * StringUtils.defaultString("bat", "NULL") = "bat"
*
- *
+ *
* @see ObjectUtils#toString(Object,String)
* @see String#valueOf(Object)
* @param str the String to check, may be null
- * @param defaultStr the default String to return
+ * @param defaultStr the default String to return
* if the input is null
, may be null
* @return the passed in String, or the default if it was null
*/
public static String defaultString(String str, String defaultStr) {
- return (str == null ? defaultStr : str);
+ return str == null ? defaultStr : str;
}
+ /**
+ * Returns either the passed in String, or if the String is
+ * whitespace, empty ("") or null
, the value of defaultStr
.
+ *
+ *
+ * StringUtils.defaultIfBlank(null, "NULL") = "NULL"
+ * StringUtils.defaultIfBlank("", "NULL") = "NULL"
+ * StringUtils.defaultIfBlank(" ", "NULL") = "NULL"
+ * StringUtils.defaultIfBlank("bat", "NULL") = "bat"
+ * StringUtils.defaultIfBlank("", null) = null
+ *
+ * @param str the String to check, may be null
+ * @param defaultStr the default String to return
+ * if the input is whitespace, empty ("") or null
, may be null
+ * @return the passed in String, or the default
+ * @see StringUtils#defaultString(String, String)
+ * @since 2.6
+ */
+ public static String defaultIfBlank(String str, String defaultStr) {
+ return StringUtils.isBlank(str) ? defaultStr : str;
+ }
+
+ /**
+ * Returns either the passed in String, or if the String is
+ * empty or null
, the value of defaultStr
.
+ *
+ *
+ * StringUtils.defaultIfEmpty(null, "NULL") = "NULL"
+ * StringUtils.defaultIfEmpty("", "NULL") = "NULL"
+ * StringUtils.defaultIfEmpty("bat", "NULL") = "bat"
+ * StringUtils.defaultIfEmpty("", null) = null
+ *
+ *
+ * @param str the String to check, may be null
+ * @param defaultStr the default String to return
+ * if the input is empty ("") or null
, may be null
+ * @return the passed in String, or the default
+ * @see StringUtils#defaultString(String, String)
+ */
+ public static String defaultIfEmpty(String str, String defaultStr) {
+ return StringUtils.isEmpty(str) ? defaultStr : str;
+ }
+
// Reversing
//-----------------------------------------------------------------------
/**
- * Reverses a String as per {@link StringBuffer#reverse()}.
+ * Reverses a String as per {@link StrBuilder#reverse()}.
*
- *
String returns null
.
- *
+ * A null
String returns null
.
+ *
*
* StringUtils.reverse(null) = null
* StringUtils.reverse("") = ""
* StringUtils.reverse("bat") = "tab"
*
- *
+ *
* @param str the String to reverse, may be null
* @return the reversed String, null
if null String input
*/
public static String reverse(String str) {
if (str == null) {
return null;
}
- return new StringBuffer(str).reverse().toString();
+ return new StrBuilder(str).reverse().toString();
}
/**
@@ -3948,14 +5779,14 @@
* The Strings between the delimiters are not reversed.
* Thus java.lang.String becomes String.lang.java (if the delimiter
* is '.'
).
- *
+ *
*
* StringUtils.reverseDelimited(null, *) = null
* StringUtils.reverseDelimited("", *) = ""
* StringUtils.reverseDelimited("a.b.c", 'x') = "a.b.c"
* StringUtils.reverseDelimited("a.b.c", ".") = "c.b.a"
*
- *
+ *
* @param str the String to reverse, may be null
* @param separatorChar the separator character to use
* @return the reversed String, null
if null String input
@@ -3965,7 +5796,7 @@
if (str == null) {
return null;
}
- // could implement manually, but simple way is to reuse other,
+ // could implement manually, but simple way is to reuse other,
// probably slower, methods.
String[] strs = split(str, separatorChar);
ArrayUtils.reverse(strs);
@@ -3978,27 +5809,27 @@
* The Strings between the delimiters are not reversed.
* Thus java.lang.String becomes String.lang.java (if the delimiter
* is "."
).
- *
+ *
*
* StringUtils.reverseDelimitedString(null, *) = null
* StringUtils.reverseDelimitedString("",*) = ""
* StringUtils.reverseDelimitedString("a.b.c", null) = "a.b.c"
* StringUtils.reverseDelimitedString("a.b.c", ".") = "c.b.a"
*
- *
+ *
* @param str the String to reverse, may be null
* @param separatorChars the separator characters to use, null treated as whitespace
* @return the reversed String, null
if null String input
* @deprecated Use {@link #reverseDelimited(String, char)} instead.
* This method is broken as the join doesn't know which char to use.
* Method will be removed in Commons Lang 3.0.
- *
+ *
*/
public static String reverseDelimitedString(String str, String separatorChars) {
if (str == null) {
return null;
}
- // could implement manually, but simple way is to reuse other,
+ // could implement manually, but simple way is to reuse other,
// probably slower, methods.
String[] strs = split(str, separatorChars);
ArrayUtils.reverse(strs);
@@ -4011,7 +5842,7 @@
// Abbreviating
//-----------------------------------------------------------------------
/**
- * Abbreviates a String using ellipses. This will turn
+ *
Abbreviates a String using ellipses. This will turn
* "Now is the time for all good men" into "Now is the time for..."
*
* Specifically:
@@ -4047,7 +5878,7 @@
}
/**
- *
Abbreviates a String using ellipses. This will turn
+ *
Abbreviates a String using ellipses. This will turn
* "Now is the time for all good men" into "...is the time for..."
*
* Works like abbreviate(String, int)
, but allows you to specify
@@ -4108,7 +5939,57 @@
}
return "..." + str.substring(str.length() - (maxWidth - 3));
}
+
+ /**
+ *
Abbreviates a String to the length passed, replacing the middle characters with the supplied
+ * replacement String.
+ *
+ * This abbreviation only occurs if the following criteria is met:
+ *
+ * - Neither the String for abbreviation nor the replacement String are null or empty
+ * - The length to truncate to is less than the length of the supplied String
+ * - The length to truncate to is greater than 0
+ * - The abbreviated String will have enough room for the length supplied replacement String
+ * and the first and last characters of the supplied String for abbreviation
+ *
+ * Otherwise, the returned String will be the same as the supplied String for abbreviation.
+ *
+ *
+ *
+ * StringUtils.abbreviateMiddle(null, null, 0) = null
+ * StringUtils.abbreviateMiddle("abc", null, 0) = "abc"
+ * StringUtils.abbreviateMiddle("abc", ".", 0) = "abc"
+ * StringUtils.abbreviateMiddle("abc", ".", 3) = "abc"
+ * StringUtils.abbreviateMiddle("abcdef", ".", 4) = "ab.f"
+ *
+ *
+ * @param str the String to abbreviate, may be null
+ * @param middle the String to replace the middle characters with, may be null
+ * @param length the length to abbreviate str
to.
+ * @return the abbreviated String if the above criteria is met, or the original String supplied for abbreviation.
+ * @since 2.5
+ */
+ public static String abbreviateMiddle(String str, String middle, int length) {
+ if (isEmpty(str) || isEmpty(middle)) {
+ return str;
+ }
+
+ if (length >= str.length() || length < (middle.length()+2)) {
+ return str;
+ }
+ int targetSting = length-middle.length();
+ int startOffset = targetSting/2+targetSting%2;
+ int endOffset = str.length()-targetSting/2;
+
+ StrBuilder builder = new StrBuilder(length);
+ builder.append(str.substring(0,startOffset));
+ builder.append(middle);
+ builder.append(str.substring(endOffset));
+
+ return builder.toString();
+ }
+
// Difference
//-----------------------------------------------------------------------
/**
@@ -4132,7 +6013,7 @@
*
* @param str1 the first String, may be null
* @param str2 the second String, may be null
- * @return the portion of str2 where it differs from str1; returns the
+ * @return the portion of str2 where it differs from str1; returns the
* empty String if they are equal
* @since 2.0
*/
@@ -4144,7 +6025,7 @@
return str1;
}
int at = indexOfDifference(str1, str2);
- if (at == -1) {
+ if (at == INDEX_NOT_FOUND) {
return EMPTY;
}
return str2.substring(at);
@@ -4153,8 +6034,8 @@
/**
* Compares two Strings, and returns the index at which the
* Strings begin to differ.
- *
- * For example,
+ *
+ *
For example,
* indexOfDifference("i am a machine", "i am a robot") -> 7
*
*
@@ -4175,7 +6056,7 @@
*/
public static int indexOfDifference(String str1, String str2) {
if (str1 == str2) {
- return -1;
+ return INDEX_NOT_FOUND;
}
if (str1 == null || str2 == null) {
return 0;
@@ -4189,22 +6070,168 @@
if (i < str2.length() || i < str1.length()) {
return i;
}
- return -1;
+ return INDEX_NOT_FOUND;
}
+ /**
+ * Compares all Strings in an array and returns the index at which the
+ * Strings begin to differ.
+ *
+ * For example,
+ * indexOfDifference(new String[] {"i am a machine", "i am a robot"}) -> 7
+ *
+ *
+ * StringUtils.indexOfDifference(null) = -1
+ * StringUtils.indexOfDifference(new String[] {}) = -1
+ * StringUtils.indexOfDifference(new String[] {"abc"}) = -1
+ * StringUtils.indexOfDifference(new String[] {null, null}) = -1
+ * StringUtils.indexOfDifference(new String[] {"", ""}) = -1
+ * StringUtils.indexOfDifference(new String[] {"", null}) = 0
+ * StringUtils.indexOfDifference(new String[] {"abc", null, null}) = 0
+ * StringUtils.indexOfDifference(new String[] {null, null, "abc"}) = 0
+ * StringUtils.indexOfDifference(new String[] {"", "abc"}) = 0
+ * StringUtils.indexOfDifference(new String[] {"abc", ""}) = 0
+ * StringUtils.indexOfDifference(new String[] {"abc", "abc"}) = -1
+ * StringUtils.indexOfDifference(new String[] {"abc", "a"}) = 1
+ * StringUtils.indexOfDifference(new String[] {"ab", "abxyz"}) = 2
+ * StringUtils.indexOfDifference(new String[] {"abcde", "abxyz"}) = 2
+ * StringUtils.indexOfDifference(new String[] {"abcde", "xyz"}) = 0
+ * StringUtils.indexOfDifference(new String[] {"xyz", "abcde"}) = 0
+ * StringUtils.indexOfDifference(new String[] {"i am a machine", "i am a robot"}) = 7
+ *
+ *
+ * @param strs array of strings, entries may be null
+ * @return the index where the strings begin to differ; -1 if they are all equal
+ * @since 2.4
+ */
+ public static int indexOfDifference(String[] strs) {
+ if (strs == null || strs.length <= 1) {
+ return INDEX_NOT_FOUND;
+ }
+ boolean anyStringNull = false;
+ boolean allStringsNull = true;
+ int arrayLen = strs.length;
+ int shortestStrLen = Integer.MAX_VALUE;
+ int longestStrLen = 0;
+ // find the min and max string lengths; this avoids checking to make
+ // sure we are not exceeding the length of the string each time through
+ // the bottom loop.
+ for (int i = 0; i < arrayLen; i++) {
+ if (strs[i] == null) {
+ anyStringNull = true;
+ shortestStrLen = 0;
+ } else {
+ allStringsNull = false;
+ shortestStrLen = Math.min(strs[i].length(), shortestStrLen);
+ longestStrLen = Math.max(strs[i].length(), longestStrLen);
+ }
+ }
+
+ // handle lists containing all nulls or all empty strings
+ if (allStringsNull || (longestStrLen == 0 && !anyStringNull)) {
+ return INDEX_NOT_FOUND;
+ }
+
+ // handle lists containing some nulls or some empty strings
+ if (shortestStrLen == 0) {
+ return 0;
+ }
+
+ // find the position with the first difference across all strings
+ int firstDiff = -1;
+ for (int stringPos = 0; stringPos < shortestStrLen; stringPos++) {
+ char comparisonChar = strs[0].charAt(stringPos);
+ for (int arrayPos = 1; arrayPos < arrayLen; arrayPos++) {
+ if (strs[arrayPos].charAt(stringPos) != comparisonChar) {
+ firstDiff = stringPos;
+ break;
+ }
+ }
+ if (firstDiff != -1) {
+ break;
+ }
+ }
+
+ if (firstDiff == -1 && shortestStrLen != longestStrLen) {
+ // we compared all of the characters up to the length of the
+ // shortest string and didn't find a match, but the string lengths
+ // vary, so return the length of the shortest string.
+ return shortestStrLen;
+ }
+ return firstDiff;
+ }
+
+ /**
+ * Compares all Strings in an array and returns the initial sequence of
+ * characters that is common to all of them.
+ *
+ * For example,
+ * getCommonPrefix(new String[] {"i am a machine", "i am a robot"}) -> "i am a "
+ *
+ *
+ * StringUtils.getCommonPrefix(null) = ""
+ * StringUtils.getCommonPrefix(new String[] {}) = ""
+ * StringUtils.getCommonPrefix(new String[] {"abc"}) = "abc"
+ * StringUtils.getCommonPrefix(new String[] {null, null}) = ""
+ * StringUtils.getCommonPrefix(new String[] {"", ""}) = ""
+ * StringUtils.getCommonPrefix(new String[] {"", null}) = ""
+ * StringUtils.getCommonPrefix(new String[] {"abc", null, null}) = ""
+ * StringUtils.getCommonPrefix(new String[] {null, null, "abc"}) = ""
+ * StringUtils.getCommonPrefix(new String[] {"", "abc"}) = ""
+ * StringUtils.getCommonPrefix(new String[] {"abc", ""}) = ""
+ * StringUtils.getCommonPrefix(new String[] {"abc", "abc"}) = "abc"
+ * StringUtils.getCommonPrefix(new String[] {"abc", "a"}) = "a"
+ * StringUtils.getCommonPrefix(new String[] {"ab", "abxyz"}) = "ab"
+ * StringUtils.getCommonPrefix(new String[] {"abcde", "abxyz"}) = "ab"
+ * StringUtils.getCommonPrefix(new String[] {"abcde", "xyz"}) = ""
+ * StringUtils.getCommonPrefix(new String[] {"xyz", "abcde"}) = ""
+ * StringUtils.getCommonPrefix(new String[] {"i am a machine", "i am a robot"}) = "i am a "
+ *
+ *
+ * @param strs array of String objects, entries may be null
+ * @return the initial sequence of characters that are common to all Strings
+ * in the array; empty String if the array is null, the elements are all null
+ * or if there is no common prefix.
+ * @since 2.4
+ */
+ public static String getCommonPrefix(String[] strs) {
+ if (strs == null || strs.length == 0) {
+ return EMPTY;
+ }
+ int smallestIndexOfDiff = indexOfDifference(strs);
+ if (smallestIndexOfDiff == INDEX_NOT_FOUND) {
+ // all strings were identical
+ if (strs[0] == null) {
+ return EMPTY;
+ }
+ return strs[0];
+ } else if (smallestIndexOfDiff == 0) {
+ // there were no common initial characters
+ return EMPTY;
+ } else {
+ // we found a common initial character sequence
+ return strs[0].substring(0, smallestIndexOfDiff);
+ }
+ }
+
// Misc
//-----------------------------------------------------------------------
/**
* Find the Levenshtein distance between two Strings.
*
* This is the number of changes needed to change one String into
- * another, where each change is a single character modification (deletion,
+ * another, where each change is a single character modification (deletion,
* insertion or substitution).
*
- * This implementation of the Levenshtein distance algorithm
- * is from http://www.merriampark.com/ld.htm
+ * The previous implementation of the Levenshtein distance algorithm
+ * was from http://www.merriampark.com/ld.htm
*
+ * Chas Emerick has written an implementation in Java, which avoids an OutOfMemoryError
+ * which can occur when my Java implementation is used with very large strings.
+ * This implementation of the Levenshtein distance algorithm
+ * is from http://www.merriampark.com/ldjava.htm
+ *
*
* StringUtils.getLevenshteinDistance(null, *) = IllegalArgumentException
* StringUtils.getLevenshteinDistance(*, null) = IllegalArgumentException
@@ -4218,7 +6245,7 @@
* StringUtils.getLevenshteinDistance("hippo", "zzzzzzzz") = 8
* StringUtils.getLevenshteinDistance("hello", "hallo") = 1
*
- *
+ *
* @param s the first String, must not be null
* @param t the second String, must not be null
* @return result distance
@@ -4228,77 +6255,340 @@
if (s == null || t == null) {
throw new IllegalArgumentException("Strings must not be null");
}
- int d[][]; // matrix
- int n; // length of s
- int m; // length of t
- int i; // iterates through s
- int j; // iterates through t
- char s_i; // ith character of s
- char t_j; // jth character of t
- int cost; // cost
- // Step 1
- n = s.length();
- m = t.length();
+ /*
+ The difference between this impl. and the previous is that, rather
+ than creating and retaining a matrix of size s.length()+1 by t.length()+1,
+ we maintain two single-dimensional arrays of length s.length()+1. The first, d,
+ is the 'current working' distance array that maintains the newest distance cost
+ counts as we iterate through the characters of String s. Each time we increment
+ the index of String t we are comparing, d is copied to p, the second int[]. Doing so
+ allows us to retain the previous cost counts as required by the algorithm (taking
+ the minimum of the cost count to the left, up one, and diagonally up and to the left
+ of the current cost count being calculated). (Note that the arrays aren't really
+ copied anymore, just switched...this is clearly much better than cloning an array
+ or doing a System.arraycopy() each time through the outer loop.)
+
+ Effectively, the difference between the two implementations is this one does not
+ cause an out of memory condition when calculating the LD over two very large strings.
+ */
+
+ int n = s.length(); // length of s
+ int m = t.length(); // length of t
+
if (n == 0) {
return m;
- }
- if (m == 0) {
+ } else if (m == 0) {
return n;
}
- d = new int[n + 1][m + 1];
- // Step 2
- for (i = 0; i <= n; i++) {
- d[i][0] = i;
+ if (n > m) {
+ // swap the input strings to consume less memory
+ String tmp = s;
+ s = t;
+ t = tmp;
+ n = m;
+ m = t.length();
}
- for (j = 0; j <= m; j++) {
- d[0][j] = j;
+ 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
+
+ // indexes into strings s and t
+ int i; // iterates through s
+ int j; // iterates through t
+
+ char t_j; // jth character of t
+
+ int cost; // cost
+
+ for (i = 0; i<=n; i++) {
+ p[i] = i;
}
- // Step 3
- for (i = 1; i <= n; i++) {
- s_i = s.charAt(i - 1);
+ for (j = 1; j<=m; j++) {
+ t_j = t.charAt(j-1);
+ d[0] = j;
- // Step 4
- for (j = 1; j <= m; j++) {
- t_j = t.charAt(j - 1);
+ for (i=1; i<=n; i++) {
+ cost = s.charAt(i-1)==t_j ? 0 : 1;
+ // minimum of cell to the left+1, to the top+1, diagonally left and up +cost
+ d[i] = Math.min(Math.min(d[i-1]+1, p[i]+1), p[i-1]+cost);
+ }
- // Step 5
- if (s_i == t_j) {
- cost = 0;
- } else {
- cost = 1;
- }
+ // copy current distance counts to 'previous row' distance counts
+ _d = p;
+ p = d;
+ d = _d;
+ }
- // Step 6
- d[i][j] = min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
+ // our last action in the above loop was to switch d and p, so p now
+ // actually has the most recent cost counts
+ return p[n];
+ }
+
+ // startsWith
+ //-----------------------------------------------------------------------
+
+ /**
+ * Check if a String starts with a specified prefix.
+ *
+ * null
s are handled without exceptions. Two null
+ * references are considered to be equal. The comparison is case sensitive.
+ *
+ *
+ * StringUtils.startsWith(null, null) = true
+ * StringUtils.startsWith(null, "abc") = false
+ * StringUtils.startsWith("abcdef", null) = false
+ * StringUtils.startsWith("abcdef", "abc") = true
+ * StringUtils.startsWith("ABCDEF", "abc") = false
+ *
+ *
+ * @see java.lang.String#startsWith(String)
+ * @param str the String to check, may be null
+ * @param prefix the prefix to find, may be null
+ * @return true
if the String starts with the prefix, case sensitive, or
+ * both null
+ * @since 2.4
+ */
+ public static boolean startsWith(String str, String prefix) {
+ return startsWith(str, prefix, false);
+ }
+
+ /**
+ * Case insensitive check if a String starts with a specified prefix.
+ *
+ * null
s are handled without exceptions. Two null
+ * references are considered to be equal. The comparison is case insensitive.
+ *
+ *
+ * StringUtils.startsWithIgnoreCase(null, null) = true
+ * StringUtils.startsWithIgnoreCase(null, "abc") = false
+ * StringUtils.startsWithIgnoreCase("abcdef", null) = false
+ * StringUtils.startsWithIgnoreCase("abcdef", "abc") = true
+ * StringUtils.startsWithIgnoreCase("ABCDEF", "abc") = true
+ *
+ *
+ * @see java.lang.String#startsWith(String)
+ * @param str the String to check, may be null
+ * @param prefix the prefix to find, may be null
+ * @return true
if the String starts with the prefix, case insensitive, or
+ * both null
+ * @since 2.4
+ */
+ public static boolean startsWithIgnoreCase(String str, String prefix) {
+ return startsWith(str, prefix, true);
+ }
+
+ /**
+ * Check if a String starts with a specified prefix (optionally case insensitive).
+ *
+ * @see java.lang.String#startsWith(String)
+ * @param str the String to check, may be null
+ * @param prefix the prefix to find, may be null
+ * @param ignoreCase inidicates whether the compare should ignore case
+ * (case insensitive) or not.
+ * @return true
if the String starts with the prefix or
+ * both null
+ */
+ private static boolean startsWith(String str, String prefix, boolean ignoreCase) {
+ if (str == null || prefix == null) {
+ return (str == null && prefix == null);
+ }
+ if (prefix.length() > str.length()) {
+ return false;
+ }
+ return str.regionMatches(ignoreCase, 0, prefix, 0, prefix.length());
+ }
+
+ /**
+ * Check if a String starts with any of an array of specified strings.
+ *
+ *
+ * StringUtils.startsWithAny(null, null) = false
+ * StringUtils.startsWithAny(null, new String[] {"abc"}) = false
+ * StringUtils.startsWithAny("abcxyz", null) = false
+ * StringUtils.startsWithAny("abcxyz", new String[] {""}) = false
+ * StringUtils.startsWithAny("abcxyz", new String[] {"abc"}) = true
+ * StringUtils.startsWithAny("abcxyz", new String[] {null, "xyz", "abc"}) = true
+ *
+ *
+ * @see #startsWith(String, String)
+ * @param string the String to check, may be null
+ * @param searchStrings the Strings to find, may be null or empty
+ * @return true
if the String starts with any of the the prefixes, case insensitive, or
+ * both null
+ * @since 2.5
+ */
+ public static boolean startsWithAny(String string, String[] searchStrings) {
+ if (isEmpty(string) || ArrayUtils.isEmpty(searchStrings)) {
+ return false;
+ }
+ for (int i = 0; i < searchStrings.length; i++) {
+ String searchString = searchStrings[i];
+ if (StringUtils.startsWith(string, searchString)) {
+ return true;
}
}
+ return false;
+ }
- // Step 7
- return d[n][m];
+ // endsWith
+ //-----------------------------------------------------------------------
+
+ /**
+ * Check if a String ends with a specified suffix.
+ *
+ * null
s are handled without exceptions. Two null
+ * references are considered to be equal. The comparison is case sensitive.
+ *
+ *
+ * StringUtils.endsWith(null, null) = true
+ * StringUtils.endsWith(null, "def") = false
+ * StringUtils.endsWith("abcdef", null) = false
+ * StringUtils.endsWith("abcdef", "def") = true
+ * StringUtils.endsWith("ABCDEF", "def") = false
+ * StringUtils.endsWith("ABCDEF", "cde") = false
+ *
+ *
+ * @see java.lang.String#endsWith(String)
+ * @param str the String to check, may be null
+ * @param suffix the suffix to find, may be null
+ * @return true
if the String ends with the suffix, case sensitive, or
+ * both null
+ * @since 2.4
+ */
+ public static boolean endsWith(String str, String suffix) {
+ return endsWith(str, suffix, false);
}
/**
- * Gets the minimum of three int
values.
+ * Case insensitive check if a String ends with a specified suffix.
+ *
+ * null
s are handled without exceptions. Two null
+ * references are considered to be equal. The comparison is case insensitive.
+ *
+ *
+ * StringUtils.endsWithIgnoreCase(null, null) = true
+ * StringUtils.endsWithIgnoreCase(null, "def") = false
+ * StringUtils.endsWithIgnoreCase("abcdef", null) = false
+ * StringUtils.endsWithIgnoreCase("abcdef", "def") = true
+ * StringUtils.endsWithIgnoreCase("ABCDEF", "def") = true
+ * StringUtils.endsWithIgnoreCase("ABCDEF", "cde") = false
+ *
+ *
+ * @see java.lang.String#endsWith(String)
+ * @param str the String to check, may be null
+ * @param suffix the suffix to find, may be null
+ * @return true
if the String ends with the suffix, case insensitive, or
+ * both null
+ * @since 2.4
+ */
+ public static boolean endsWithIgnoreCase(String str, String suffix) {
+ return endsWith(str, suffix, true);
+ }
+
+ /**
+ * Check if a String ends with a specified suffix (optionally case insensitive).
+ *
+ * @see java.lang.String#endsWith(String)
+ * @param str the String to check, may be null
+ * @param suffix the suffix to find, may be null
+ * @param ignoreCase inidicates whether the compare should ignore case
+ * (case insensitive) or not.
+ * @return true
if the String starts with the prefix or
+ * both null
+ */
+ private static boolean endsWith(String str, String suffix, boolean ignoreCase) {
+ if (str == null || suffix == null) {
+ return (str == null && suffix == null);
+ }
+ if (suffix.length() > str.length()) {
+ return false;
+ }
+ int strOffset = str.length() - suffix.length();
+ return str.regionMatches(ignoreCase, strOffset, suffix, 0, suffix.length());
+ }
+
+ /**
+ *
+ * Similar to http://www.w3.org/TR/xpath/#function-normalize
+ * -space
+ *
+ *
+ * The function returns the argument string with whitespace normalized by using
+ * {@link #trim(String)}
to remove leading and trailing whitespace
+ * and then replacing sequences of whitespace characters by a single space.
+ *
+ * In XML Whitespace characters are the same as those allowed by the S production, which is S ::= (#x20 | #x9 | #xD | #xA)+
+ *
+ * See Java's {@link Character#isWhitespace(char)} for which characters are considered whitespace.
+ *
+ * The difference is that Java's whitespace includes vertical tab and form feed, which this functional will also
+ * normalize. Additonally {@link #trim(String)}
removes control characters (char <= 32) from both
+ * ends of this String.
+ *
+ *
+ * @see Character#isWhitespace(char)
+ * @see #trim(String)
+ * @see
+ * http://www.w3.org/TR/xpath/#function-normalize-space
+ * @param str the source String to normalize whitespaces from, may be null
+ * @return the modified string with whitespace normalized, null
if null String input
*
- * @param a value 1
- * @param b value 2
- * @param c value 3
- * @return the smallest of the values
+ * @since 2.6
*/
- private static int min(int a, int b, int c) {
- // Method copied from NumberUtils to avoid dependency on subpackage
- if (b < a) {
- a = b;
+ public static String normalizeSpace(String str) {
+ str = strip(str);
+ if(str == null || str.length() <= 2) {
+ return str;
}
- if (c < a) {
- a = c;
+ StrBuilder b = new StrBuilder(str.length());
+ for (int i = 0; i < str.length(); i++) {
+ char c = str.charAt(i);
+ if (Character.isWhitespace(c)) {
+ if (i > 0 && !Character.isWhitespace(str.charAt(i - 1))) {
+ b.append(' ');
+ }
+ } else {
+ b.append(c);
+ }
}
- return a;
+ return b.toString();
}
-}
+ /**
+ * Check if a String ends with any of an array of specified strings.
+ *
+ *
+ * StringUtils.endsWithAny(null, null) = false
+ * StringUtils.endsWithAny(null, new String[] {"abc"}) = false
+ * StringUtils.endsWithAny("abcxyz", null) = false
+ * StringUtils.endsWithAny("abcxyz", new String[] {""}) = true
+ * StringUtils.endsWithAny("abcxyz", new String[] {"xyz"}) = true
+ * StringUtils.endsWithAny("abcxyz", new String[] {null, "xyz", "abc"}) = true
+ *
+ *
+ * @param string the String to check, may be null
+ * @param searchStrings the Strings to find, may be null or empty
+ * @return true
if the String ends with any of the the prefixes, case insensitive, or
+ * both null
+ * @since 2.6
+ */
+ public static boolean endsWithAny(String string, String[] searchStrings) {
+ if (isEmpty(string) || ArrayUtils.isEmpty(searchStrings)) {
+ return false;
+ }
+ for (int i = 0; i < searchStrings.length; i++) {
+ String searchString = searchStrings[i];
+ if (StringUtils.endsWith(string, searchString)) {
+ return true;
+ }
+ }
+ return false;
+ }
+}
Index: 3rdParty_sources/commons-lang/org/apache/commons/lang/SystemUtils.java
===================================================================
RCS file: /usr/local/cvsroot/3rdParty_sources/commons-lang/org/apache/commons/lang/SystemUtils.java,v
diff -u -r1.1 -r1.2
--- 3rdParty_sources/commons-lang/org/apache/commons/lang/SystemUtils.java 30 Aug 2012 16:24:42 -0000 1.1
+++ 3rdParty_sources/commons-lang/org/apache/commons/lang/SystemUtils.java 15 Mar 2013 09:52:49 -0000 1.2
@@ -1,720 +1,1392 @@
-/* ====================================================================
- * The Apache Software License, Version 1.1
- *
- * Copyright (c) 2002-2003 The Apache Software Foundation. All rights
- * reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in
- * the documentation and/or other materials provided with the
- * distribution.
- *
- * 3. The end-user documentation included with the redistribution, if
- * any, must include the following acknowledgement:
- * "This product includes software developed by the
- * Apache Software Foundation (http://www.apache.org/)."
- * Alternately, this acknowledgement may appear in the software itself,
- * if and wherever such third-party acknowledgements normally appear.
- *
- * 4. The names "The Jakarta Project", "Commons", and "Apache Software
- * Foundation" must not be used to endorse or promote products derived
- * from this software without prior written permission. For written
- * permission, please contact apache@apache.org.
- *
- * 5. Products derived from this software may not be called "Apache"
- * nor may "Apache" appear in their names without prior written
- * permission of the Apache Software Foundation.
- *
- * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
- * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
- * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
- * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- * ====================================================================
- *
- * This software consists of voluntary contributions made by many
- * individuals on behalf of the Apache Software Foundation. For more
- * information on the Apache Software Foundation, please see
- * .
+/*
+ * 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.lang;
+import java.io.File;
+
/**
- * Helpers for java.lang.System
.
+ *
+ * Helpers for java.lang.System
.
+ *
*
- * If a system property cannot be read due to security restrictions,
+ *
+ * If a system property cannot be read due to security restrictions,
* the corresponding field in this class will be set to null
- * and a message will be written to System.err
.
- *
+ * and a message will be written to System.err
.
+ *
+ *
+ *
+ * #ThreadSafe#
+ *
+ *
+ * @author Apache Software Foundation
* @author Based on code from Avalon Excalibur
* @author Based on code from Lucene
- * @author Stephen Colebourne
* @author Steve Downey
* @author Gary Gregory
* @author Michael Becke
* @author Tetsuya Kaneuchi
+ * @author Rafal Krupinski
+ * @author Jason Gritman
* @since 1.0
* @version $Id$
*/
public class SystemUtils {
+ private static final int JAVA_VERSION_TRIM_SIZE = 3;
+
+ /**
+ * The prefix String for all Windows OS.
+ */
+ private static final String OS_NAME_WINDOWS_PREFIX = "Windows";
+
// System property constants
- //-----------------------------------------------------------------------
+ // -----------------------------------------------------------------------
// These MUST be declared first. Other constants depend on this.
-
+
/**
- * The file.encoding
System Property.
- * File encoding, such as Cp1252
.
+ * The System property key for the user home directory.
+ */
+ private static final String USER_HOME_KEY = "user.home";
+
+ /**
+ * The System property key for the user directory.
+ */
+ private static final String USER_DIR_KEY = "user.dir";
+
+ /**
+ * The System property key for the Java IO temporary directory.
+ */
+ private static final String JAVA_IO_TMPDIR_KEY = "java.io.tmpdir";
+
+ /**
+ * The System property key for the Java home directory.
+ */
+ private static final String JAVA_HOME_KEY = "java.home";
+
+ /**
+ *
+ * The awt.toolkit
System Property.
+ *
+ *
+ * Holds a class name, on Windows XP this is sun.awt.windows.WToolkit
.
+ *
+ *
+ * On platforms without a GUI, this value is null
.
+ *
*
- * Defaults to null
if the runtime does not have
- * security access to read this property or the property does not exist.
+ *
+ * Defaults to null
if the runtime does not have
+ * security access to read this property or the property does not exist.
+ *
*
+ *
+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
+ * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will
+ * be out of sync with that System property.
+ *
+ *
+ * @since 2.1
+ */
+ public static final String AWT_TOOLKIT = getSystemProperty("awt.toolkit");
+
+ /**
+ *
+ * The file.encoding
System Property.
+ *
+ *
+ * File encoding, such as Cp1252
.
+ *
+ *
+ *
+ * Defaults to null
if the runtime does not have
+ * security access to read this property or the property does not exist.
+ *
+ *
+ *
+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
+ * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
+ * will be out of sync with that System property.
+ *
+ *
* @since 2.0
- * @since Java 1.2.
+ * @since Java 1.2
*/
public static final String FILE_ENCODING = getSystemProperty("file.encoding");
/**
- * The file.separator
System Property.
- * File separator ("/"
on UNIX).
- *
- * Defaults to null
if the runtime does not have
- * security access to read this property or the property does not exist.
+ *
+ * The file.separator
System Property. File separator ("/"
on UNIX).
+ *
*
- * @since Java 1.1.
+ *
+ * Defaults to null
if the runtime does not have
+ * security access to read this property or the property does not exist.
+ *
+ *
+ *
+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
+ * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
+ * will be out of sync with that System property.
+ *
+ *
+ * @since Java 1.1
*/
public static final String FILE_SEPARATOR = getSystemProperty("file.separator");
/**
- * The java.class.path
System Property. Java class path.
- *
- * Defaults to null
if the runtime does not have
- * security access to read this property or the property does not exist.
+ *
+ * The java.awt.fonts
System Property.
+ *
*
- * @since Java 1.1.
+ *
+ * Defaults to null
if the runtime does not have
+ * security access to read this property or the property does not exist.
+ *
+ *
+ *
+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
+ * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
+ * will be out of sync with that System property.
+ *
+ *
+ * @since 2.1
*/
+ public static final String JAVA_AWT_FONTS = getSystemProperty("java.awt.fonts");
+
+ /**
+ *
+ * The java.awt.graphicsenv
System Property.
+ *
+ *
+ *
+ * Defaults to null
if the runtime does not have
+ * security access to read this property or the property does not exist.
+ *
+ *
+ *
+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
+ * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
+ * will be out of sync with that System property.
+ *
+ *
+ * @since 2.1
+ */
+ public static final String JAVA_AWT_GRAPHICSENV = getSystemProperty("java.awt.graphicsenv");
+
+ /**
+ *
+ * The java.awt.headless
System Property.
+ * The value of this property is the String "true"
or "false"
.
+ *
+ *
+ *
+ * Defaults to null
if the runtime does not have
+ * security access to read this property or the property does not exist.
+ *
+ *
+ *
+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
+ * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
+ * will be out of sync with that System property.
+ *
+ *
+ * @see #isJavaAwtHeadless()
+ * @since 2.1
+ * @since Java 1.4
+ */
+ public static final String JAVA_AWT_HEADLESS = getSystemProperty("java.awt.headless");
+
+ /**
+ *
+ * The java.awt.printerjob
System Property.
+ *
+ *
+ *
+ * Defaults to null
if the runtime does not have
+ * security access to read this property or the property does not exist.
+ *
+ *
+ *
+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
+ * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
+ * will be out of sync with that System property.
+ *
+ *
+ * @since 2.1
+ */
+ public static final String JAVA_AWT_PRINTERJOB = getSystemProperty("java.awt.printerjob");
+
+ /**
+ *
+ * The java.class.path
System Property. Java class path.
+ *
+ *
+ *
+ * Defaults to null
if the runtime does not have
+ * security access to read this property or the property does not exist.
+ *
+ *
+ *
+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
+ * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
+ * will be out of sync with that System property.
+ *
+ *
+ * @since Java 1.1
+ */
public static final String JAVA_CLASS_PATH = getSystemProperty("java.class.path");
/**
- * The java.class.version
System Property.
- * Java class format version number.
- *
- * Defaults to null
if the runtime does not have
- * security access to read this property or the property does not exist.
+ *
+ * The java.class.version
System Property. Java class format version number.
+ *
*
- * @since Java 1.1.
+ *
+ * Defaults to null
if the runtime does not have
+ * security access to read this property or the property does not exist.
+ *
+ *
+ *
+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
+ * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
+ * will be out of sync with that System property.
+ *
+ *
+ * @since Java 1.1
*/
public static final String JAVA_CLASS_VERSION = getSystemProperty("java.class.version");
/**
- * The java.compiler
System Property. Name of JIT compiler to use.
- * First in JDK version 1.2. Not used in Sun JDKs after 1.2.
- *
- * Defaults to null
if the runtime does not have
- * security access to read this property or the property does not exist.
+ *
+ * The java.compiler
System Property. Name of JIT compiler to use.
+ * First in JDK version 1.2. Not used in Sun JDKs after 1.2.
+ *
*
+ *
+ * Defaults to null
if the runtime does not have
+ * security access to read this property or the property does not exist.
+ *
+ *
+ *
+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
+ * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
+ * will be out of sync with that System property.
+ *
+ *
* @since Java 1.2. Not used in Sun versions after 1.2.
*/
public static final String JAVA_COMPILER = getSystemProperty("java.compiler");
/**
- * The java.ext.dirs
System Property. Path of extension directory
- * or directories.
- *
- * Defaults to null
if the runtime does not have
- * security access to read this property or the property does not exist.
+ *
+ * The java.endorsed.dirs
System Property. Path of endorsed directory or directories.
+ *
*
+ *
+ * Defaults to null
if the runtime does not have
+ * security access to read this property or the property does not exist.
+ *
+ *
+ *
+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
+ * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
+ * will be out of sync with that System property.
+ *
+ *
+ * @since Java 1.4
+ */
+ public static final String JAVA_ENDORSED_DIRS = getSystemProperty("java.endorsed.dirs");
+
+ /**
+ *
+ * The java.ext.dirs
System Property. Path of extension directory or directories.
+ *
+ *
+ *
+ * Defaults to null
if the runtime does not have
+ * security access to read this property or the property does not exist.
+ *
+ *
+ *
+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
+ * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
+ * will be out of sync with that System property.
+ *
+ *
* @since Java 1.3
*/
public static final String JAVA_EXT_DIRS = getSystemProperty("java.ext.dirs");
/**
- * The java.home
System Property. Java installation directory.
- *
- * Defaults to null
if the runtime does not have
- * security access to read this property or the property does not exist.
+ *
+ * The java.home
System Property. Java installation directory.
+ *
*
+ *
+ * Defaults to null
if the runtime does not have
+ * security access to read this property or the property does not exist.
+ *
+ *
+ *
+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
+ * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
+ * will be out of sync with that System property.
+ *
+ *
* @since Java 1.1
*/
- public static final String JAVA_HOME = getSystemProperty("java.home");
+ public static final String JAVA_HOME = getSystemProperty(JAVA_HOME_KEY);
/**
- * The java.io.tmpdir
System Property. Default temp file path.
- *
- * Defaults to null
if the runtime does not have
- * security access to read this property or the property does not exist.
+ *
+ * The java.io.tmpdir
System Property. Default temp file path.
+ *
*
+ *
+ * Defaults to null
if the runtime does not have
+ * security access to read this property or the property does not exist.
+ *
+ *
+ *
+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
+ * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
+ * will be out of sync with that System property.
+ *
+ *
* @since Java 1.2
*/
- public static final String JAVA_IO_TMPDIR = getSystemProperty("java.io.tmpdir");
+ public static final String JAVA_IO_TMPDIR = getSystemProperty(JAVA_IO_TMPDIR_KEY);
/**
- * The java.library.path
System Property. List of paths to search
- * when loading libraries.
- *
- * Defaults to null
if the runtime does not have
- * security access to read this property or the property does not exist.
+ *
+ * The java.library.path
System Property. List of paths to search when loading libraries.
+ *
*
+ *
+ * Defaults to null
if the runtime does not have
+ * security access to read this property or the property does not exist.
+ *
+ *
+ *
+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
+ * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
+ * will be out of sync with that System property.
+ *
+ *
* @since Java 1.2
*/
public static final String JAVA_LIBRARY_PATH = getSystemProperty("java.library.path");
/**
- * The java.runtime.name
System Property. Java Runtime Environment
- * name.
- *
- * Defaults to null
if the runtime does not have
- * security access to read this property or the property does not exist.
+ *
+ * The java.runtime.name
System Property. Java Runtime Environment name.
+ *
*
+ *
+ * Defaults to null
if the runtime does not have
+ * security access to read this property or the property does not exist.
+ *
+ *
+ *
+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
+ * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
+ * will be out of sync with that System property.
+ *
+ *
* @since 2.0
* @since Java 1.3
*/
public static final String JAVA_RUNTIME_NAME = getSystemProperty("java.runtime.name");
/**
- * The java.runtime.version
System Property. Java Runtime Environment
- * version.
- *
- * Defaults to null
if the runtime does not have
- * security access to read this property or the property does not exist.
+ *
+ * The java.runtime.version
System Property. Java Runtime Environment version.
+ *
*
+ *
+ * Defaults to null
if the runtime does not have
+ * security access to read this property or the property does not exist.
+ *
+ *
+ *
+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
+ * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
+ * will be out of sync with that System property.
+ *
+ *
* @since 2.0
* @since Java 1.3
*/
public static final String JAVA_RUNTIME_VERSION = getSystemProperty("java.runtime.version");
/**
- * The java.specification.name
System Property. Java Runtime Environment
- * specification name.
- *
- * Defaults to null
if the runtime does not have
- * security access to read this property or the property does not exist.
+ *
+ * The java.specification.name
System Property. Java Runtime Environment specification name.
+ *
*
+ *
+ * Defaults to null
if the runtime does not have
+ * security access to read this property or the property does not exist.
+ *
+ *
+ *
+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
+ * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
+ * will be out of sync with that System property.
+ *
+ *
* @since Java 1.2
*/
public static final String JAVA_SPECIFICATION_NAME = getSystemProperty("java.specification.name");
/**
- * The java.specification.vendor
System Property. Java Runtime Environment
- * specification vendor.
- *
- * Defaults to null
if the runtime does not have
- * security access to read this property or the property does not exist.
+ *
+ * The java.specification.vendor
System Property. Java Runtime Environment specification vendor.
+ *
*
+ *
+ * Defaults to null
if the runtime does not have
+ * security access to read this property or the property does not exist.
+ *
+ *
+ *
+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
+ * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
+ * will be out of sync with that System property.
+ *
+ *
* @since Java 1.2
*/
public static final String JAVA_SPECIFICATION_VENDOR = getSystemProperty("java.specification.vendor");
/**
- * The java.specification.version
System Property. Java Runtime Environment
- * specification version.
- *
- * Defaults to null
if the runtime does not have
- * security access to read this property or the property does not exist.
+ *
+ * The java.specification.version
System Property. Java Runtime Environment specification version.
+ *
*
+ *
+ * Defaults to null
if the runtime does not have
+ * security access to read this property or the property does not exist.
+ *
+ *
+ *
+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
+ * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
+ * will be out of sync with that System property.
+ *
+ *
* @since Java 1.3
*/
public static final String JAVA_SPECIFICATION_VERSION = getSystemProperty("java.specification.version");
/**
- * The java.vendor
System Property. Java vendor-specific string.
- *
- * Defaults to null
if the runtime does not have
- * security access to read this property or the property does not exist.
+ *
+ * The java.util.prefs.PreferencesFactory
System Property. A class name.
+ *
*
+ *
+ * Defaults to null
if the runtime does not have
+ * security access to read this property or the property does not exist.
+ *
+ *
+ *
+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
+ * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
+ * will be out of sync with that System property.
+ *
+ *
+ * @since 2.1
+ * @since Java 1.4
+ */
+ public static final String JAVA_UTIL_PREFS_PREFERENCES_FACTORY =
+ getSystemProperty("java.util.prefs.PreferencesFactory");
+
+ /**
+ *
+ * The java.vendor
System Property. Java vendor-specific string.
+ *
+ *
+ *
+ * Defaults to null
if the runtime does not have
+ * security access to read this property or the property does not exist.
+ *
+ *
+ *
+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
+ * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
+ * will be out of sync with that System property.
+ *
+ *
* @since Java 1.1
*/
public static final String JAVA_VENDOR = getSystemProperty("java.vendor");
/**
- * The java.vendor.url
System Property. Java vendor URL.
- *
- * Defaults to null
if the runtime does not have
- * security access to read this property or the property does not exist.
- *
+ *
+ * The java.vendor.url
System Property. Java vendor URL.
+ *
+ *
+ *
+ * Defaults to null
if the runtime does not have
+ * security access to read this property or the property does not exist.
+ *
+ *
+ *
+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
+ * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
+ * will be out of sync with that System property.
+ *
+ *
* @since Java 1.1
- */
+ */
public static final String JAVA_VENDOR_URL = getSystemProperty("java.vendor.url");
/**
- * The java.version
System Property. Java version number.
- *
- * Defaults to null
if the runtime does not have
- * security access to read this property or the property does not exist.
+ *
+ * The java.version
System Property. Java version number.
+ *
*
+ *
+ * Defaults to null
if the runtime does not have
+ * security access to read this property or the property does not exist.
+ *
+ *
+ *
+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
+ * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
+ * will be out of sync with that System property.
+ *
+ *
* @since Java 1.1
*/
public static final String JAVA_VERSION = getSystemProperty("java.version");
/**
- * The java.vm.info
System Property. Java Virtual Machine implementation
- * info.
- *
- * Defaults to null
if the runtime does not have
- * security access to read this property or the property does not exist.
+ *
+ * The java.vm.info
System Property. Java Virtual Machine implementation info.
+ *
*
+ *
+ * Defaults to null
if the runtime does not have
+ * security access to read this property or the property does not exist.
+ *
+ *
+ *
+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
+ * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
+ * will be out of sync with that System property.
+ *
+ *
* @since 2.0
* @since Java 1.2
*/
public static final String JAVA_VM_INFO = getSystemProperty("java.vm.info");
/**
- * The java.vm.name
System Property. Java Virtual Machine implementation
- * name.
- *
- * Defaults to null
if the runtime does not have
- * security access to read this property or the property does not exist.
+ *
+ * The java.vm.name
System Property. Java Virtual Machine implementation name.
+ *
*
+ *
+ * Defaults to null
if the runtime does not have
+ * security access to read this property or the property does not exist.
+ *
+ *
+ *
+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
+ * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
+ * will be out of sync with that System property.
+ *
+ *
* @since Java 1.2
*/
public static final String JAVA_VM_NAME = getSystemProperty("java.vm.name");
/**
- * The java.vm.specification.name
System Property. Java Virtual Machine
- * specification name.
- *
- * Defaults to null
if the runtime does not have
- * security access to read this property or the property does not exist.
+ *
+ * The java.vm.specification.name
System Property. Java Virtual Machine specification name.
+ *
*
+ *
+ * Defaults to null
if the runtime does not have
+ * security access to read this property or the property does not exist.
+ *
+ *
+ *
+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
+ * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
+ * will be out of sync with that System property.
+ *
+ *
* @since Java 1.2
*/
public static final String JAVA_VM_SPECIFICATION_NAME = getSystemProperty("java.vm.specification.name");
/**
- * The java.vm.specification.vendor
System Property. Java Virtual
- * Machine specification vendor.
- *
- * Defaults to null
if the runtime does not have
- * security access to read this property or the property does not exist.
+ *
+ * The java.vm.specification.vendor
System Property. Java Virtual Machine specification vendor.
+ *
*
+ *
+ * Defaults to null
if the runtime does not have
+ * security access to read this property or the property does not exist.
+ *
+ *
+ *
+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
+ * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
+ * will be out of sync with that System property.
+ *
+ *
* @since Java 1.2
*/
public static final String JAVA_VM_SPECIFICATION_VENDOR = getSystemProperty("java.vm.specification.vendor");
/**
- * The java.vm.specification.version
System Property. Java Virtual Machine
- * specification version.
- *
- * Defaults to null
if the runtime does not have
- * security access to read this property or the property does not exist.
+ *
+ * The java.vm.specification.version
System Property. Java Virtual Machine specification version.
+ *
*
+ *
+ * Defaults to null
if the runtime does not have
+ * security access to read this property or the property does not exist.
+ *
+ *
+ *
+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
+ * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
+ * will be out of sync with that System property.
+ *
+ *
* @since Java 1.2
*/
public static final String JAVA_VM_SPECIFICATION_VERSION = getSystemProperty("java.vm.specification.version");
/**
- * The java.vm.vendor
System Property. Java Virtual Machine implementation
- * vendor.
- *
- * Defaults to null
if the runtime does not have
- * security access to read this property or the property does not exist.
+ *
+ * The java.vm.vendor
System Property. Java Virtual Machine implementation vendor.
+ *
*
+ *
+ * Defaults to null
if the runtime does not have
+ * security access to read this property or the property does not exist.
+ *
+ *
+ *
+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
+ * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
+ * will be out of sync with that System property.
+ *
+ *
* @since Java 1.2
*/
public static final String JAVA_VM_VENDOR = getSystemProperty("java.vm.vendor");
/**
- * The java.vm.version
System Property. Java Virtual Machine
- * implementation version.
- *
- * Defaults to null
if the runtime does not have
- * security access to read this property or the property does not exist.
+ *
+ * The java.vm.version
System Property. Java Virtual Machine implementation version.
+ *
*
+ *
+ * Defaults to null
if the runtime does not have
+ * security access to read this property or the property does not exist.
+ *
+ *
+ *
+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
+ * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
+ * will be out of sync with that System property.
+ *
+ *
* @since Java 1.2
*/
public static final String JAVA_VM_VERSION = getSystemProperty("java.vm.version");
/**
- * The line.separator
System Property. Line separator
- * ("\n<"
on UNIX).
- *
- * Defaults to null
if the runtime does not have
- * security access to read this property or the property does not exist.
+ *
+ * The line.separator
System Property. Line separator ("\n"
on UNIX).
+ *
*
+ *
+ * Defaults to null
if the runtime does not have
+ * security access to read this property or the property does not exist.
+ *
+ *
+ *
+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
+ * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
+ * will be out of sync with that System property.
+ *
+ *
* @since Java 1.1
*/
public static final String LINE_SEPARATOR = getSystemProperty("line.separator");
/**
- * The os.arch
System Property. Operating system architecture.
- *
- * Defaults to null
if the runtime does not have
- * security access to read this property or the property does not exist.
+ *
+ * The os.arch
System Property. Operating system architecture.
+ *
*
+ *
+ * Defaults to null
if the runtime does not have
+ * security access to read this property or the property does not exist.
+ *
+ *
+ *
+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
+ * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
+ * will be out of sync with that System property.
+ *
+ *
* @since Java 1.1
*/
public static final String OS_ARCH = getSystemProperty("os.arch");
/**
- * The os.name
System Property. Operating system name.
- *
- * Defaults to null
if the runtime does not have
- * security access to read this property or the property does not exist.
+ *
+ * The os.name
System Property. Operating system name.
+ *
*
+ *
+ * Defaults to null
if the runtime does not have
+ * security access to read this property or the property does not exist.
+ *
+ *
+ *
+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
+ * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
+ * will be out of sync with that System property.
+ *
+ *
* @since Java 1.1
*/
public static final String OS_NAME = getSystemProperty("os.name");
/**
- * The os.version
System Property. Operating system version.
- *
- * Defaults to null
if the runtime does not have
- * security access to read this property or the property does not exist.
+ *
+ * The os.version
System Property. Operating system version.
+ *
*
+ *
+ * Defaults to null
if the runtime does not have
+ * security access to read this property or the property does not exist.
+ *
+ *
+ *
+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
+ * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
+ * will be out of sync with that System property.
+ *
+ *
* @since Java 1.1
*/
public static final String OS_VERSION = getSystemProperty("os.version");
/**
- * The path.separator
System Property. Path separator
- * (":"
on UNIX).
- *
- * Defaults to null
if the runtime does not have
- * security access to read this property or the property does not exist.
+ *
+ * The path.separator
System Property. Path separator (":"
on UNIX).
+ *
*
+ *
+ * Defaults to null
if the runtime does not have
+ * security access to read this property or the property does not exist.
+ *
+ *
+ *
+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
+ * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
+ * will be out of sync with that System property.
+ *
+ *
* @since Java 1.1
*/
public static final String PATH_SEPARATOR = getSystemProperty("path.separator");
/**
- * The user.country
or user.region
System Property.
- * User's country code, such as GB
. First in JDK version 1.2 as
- * user.region
. Renamed to user.country
in 1.4
- *
- * Defaults to null
if the runtime does not have
- * security access to read this property or the property does not exist.
+ *
+ * The user.country
or user.region
System Property.
+ * User's country code, such as GB
. First in
+ * Java version 1.2 as user.region
. Renamed to user.country
in 1.4
+ *
*
+ *
+ * Defaults to null
if the runtime does not have
+ * security access to read this property or the property does not exist.
+ *
+ *
+ *
+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
+ * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
+ * will be out of sync with that System property.
+ *
+ *
* @since 2.0
* @since Java 1.2
*/
public static final String USER_COUNTRY =
- (getSystemProperty("user.country") == null ?
- getSystemProperty("user.region") : getSystemProperty("user.country"));
+ getSystemProperty("user.country") == null ?
+ getSystemProperty("user.region") : getSystemProperty("user.country");
/**
- * The user.dir
System Property. User's current working
- * directory.
- *
- * Defaults to null
if the runtime does not have
- * security access to read this property or the property does not exist.
+ *
+ * The user.dir
System Property. User's current working directory.
+ *
*
+ *
+ * Defaults to null
if the runtime does not have
+ * security access to read this property or the property does not exist.
+ *
+ *
+ *
+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
+ * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
+ * will be out of sync with that System property.
+ *
+ *
* @since Java 1.1
*/
- public static final String USER_DIR = getSystemProperty("user.dir");
+ public static final String USER_DIR = getSystemProperty(USER_DIR_KEY);
/**
- * The user.home
System Property. User's home directory.
- *
- * Defaults to null
if the runtime does not have
- * security access to read this property or the property does not exist.
+ *
+ * The user.home
System Property. User's home directory.
+ *
*
+ *
+ * Defaults to null
if the runtime does not have
+ * security access to read this property or the property does not exist.
+ *
+ *
+ *
+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
+ * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
+ * will be out of sync with that System property.
+ *
+ *
* @since Java 1.1
*/
- public static final String USER_HOME = getSystemProperty("user.home");
+ public static final String USER_HOME = getSystemProperty(USER_HOME_KEY);
/**
- * The user.language
System Property. User's language code,
- * such as 'en'.
- *
- * Defaults to null
if the runtime does not have
- * security access to read this property or the property does not exist.
+ *
+ * The user.language
System Property. User's language code, such as "en"
.
+ *
*
+ *
+ * Defaults to null
if the runtime does not have
+ * security access to read this property or the property does not exist.
+ *
+ *
+ *
+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
+ * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
+ * will be out of sync with that System property.
+ *
+ *
* @since 2.0
* @since Java 1.2
*/
public static final String USER_LANGUAGE = getSystemProperty("user.language");
/**
- * The user.name
System Property. User's account name.
- *
- * Defaults to null
if the runtime does not have
- * security access to read this property or the property does not exist.
+ *
+ * The user.name
System Property. User's account name.
+ *
*
+ *
+ * Defaults to null
if the runtime does not have
+ * security access to read this property or the property does not exist.
+ *
+ *
+ *
+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
+ * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
+ * will be out of sync with that System property.
+ *
+ *
* @since Java 1.1
*/
public static final String USER_NAME = getSystemProperty("user.name");
+ /**
+ *
+ * The user.timezone
System Property. For example: "America/Los_Angeles"
.
+ *
+ *
+ *
+ * Defaults to null
if the runtime does not have
+ * security access to read this property or the property does not exist.
+ *
+ *
+ *
+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
+ * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
+ * will be out of sync with that System property.
+ *
+ *
+ * @since 2.1
+ */
+ public static final String USER_TIMEZONE = getSystemProperty("user.timezone");
+
// Java version
- //-----------------------------------------------------------------------
- // These MUST be declared after those above as they depend on the
+ // -----------------------------------------------------------------------
+ // This MUST be declared after those above as it depends on the
// values being set up
-
+
/**
- * Gets the Java version as a float
.
- *
- * Example return values:
+ *
+ * Gets the Java version as a String
trimming leading letters.
+ *
+ *
+ *
+ * The field will return null
if {@link #JAVA_VERSION} is null
.
+ *
+ *
+ * @since 2.1
+ */
+ public static final String JAVA_VERSION_TRIMMED = getJavaVersionTrimmed();
+
+ // Java version values
+ // -----------------------------------------------------------------------
+ // These MUST be declared after the trim above as they depend on the
+ // value being set up
+
+ /**
+ *
+ * Gets the Java version as a float
.
+ *
+ *
+ *
+ * Example return values:
+ *
*
- * 1.2f
for JDK 1.2
- * 1.31f
for JDK 1.3.1
+ * 1.2f
for Java 1.2
+ * 1.31f
for Java 1.3.1
*
- *
- * The field will return zero if {@link #JAVA_VERSION} is null
.
*
+ *
+ * The field will return zero if {@link #JAVA_VERSION} is null
.
+ *
+ *
* @since 2.0
*/
public static final float JAVA_VERSION_FLOAT = getJavaVersionAsFloat();
/**
- * Gets the Java version as an int
.
- *
- * Example return values:
+ *
+ * Gets the Java version as an int
.
+ *
+ *
+ *
+ * Example return values:
+ *
*
- * 120
for JDK 1.2
- * 131
for JDK 1.3.1
+ * 120
for Java 1.2
+ * 131
for Java 1.3.1
*
- *
- * The field will return zero if {@link #JAVA_VERSION} is null
.
*
+ *
+ * The field will return zero if {@link #JAVA_VERSION} is null
.
+ *
+ *
* @since 2.0
*/
public static final int JAVA_VERSION_INT = getJavaVersionAsInt();
// Java version checks
- //-----------------------------------------------------------------------
+ // -----------------------------------------------------------------------
// These MUST be declared after those above as they depend on the
// values being set up
-
+
/**
- * Is true
if this is Java version 1.1 (also 1.1.x versions).
- *
- * The field will return false
if {@link #JAVA_VERSION} is
- * null
.
+ *
+ * Is true
if this is Java version 1.1 (also 1.1.x versions).
+ *
+ *
+ *
+ * The field will return false
if {@link #JAVA_VERSION} is null
.
+ *
*/
public static final boolean IS_JAVA_1_1 = getJavaVersionMatches("1.1");
/**
- * Is true
if this is Java version 1.2 (also 1.2.x versions).
- *
- * The field will return false
if {@link #JAVA_VERSION} is
- * null
.
+ *
+ * Is true
if this is Java version 1.2 (also 1.2.x versions).
+ *
+ *
+ *
+ * The field will return false
if {@link #JAVA_VERSION} is null
.
+ *
*/
public static final boolean IS_JAVA_1_2 = getJavaVersionMatches("1.2");
/**
- * Is true
if this is Java version 1.3 (also 1.3.x versions).
- *
- * The field will return false
if {@link #JAVA_VERSION} is
- * null
.
+ *
+ * Is true
if this is Java version 1.3 (also 1.3.x versions).
+ *
+ *
+ *
+ * The field will return false
if {@link #JAVA_VERSION} is null
.
+ *
*/
public static final boolean IS_JAVA_1_3 = getJavaVersionMatches("1.3");
/**
- * Is true
if this is Java version 1.4 (also 1.4.x versions).
- *
- * The field will false
false if {@link #JAVA_VERSION} is
- * null
.
+ *
+ * Is true
if this is Java version 1.4 (also 1.4.x versions).
+ *
+ *
+ *
+ * The field will return false
if {@link #JAVA_VERSION} is null
.
+ *
*/
public static final boolean IS_JAVA_1_4 = getJavaVersionMatches("1.4");
/**
- * Is true
if this is Java version 1.5 (also 1.5.x versions).
- *
- * The field will return false
if {@link #JAVA_VERSION} is
- * null
.
+ *
+ * Is true
if this is Java version 1.5 (also 1.5.x versions).
+ *
+ *
+ *
+ * The field will return false
if {@link #JAVA_VERSION} is null
.
+ *
*/
public static final boolean IS_JAVA_1_5 = getJavaVersionMatches("1.5");
+ /**
+ *
+ * Is true
if this is Java version 1.6 (also 1.6.x versions).
+ *
+ *
+ *
+ * The field will return false
if {@link #JAVA_VERSION} is null
.
+ *
+ */
+ public static final boolean IS_JAVA_1_6 = getJavaVersionMatches("1.6");
+
+ /**
+ *
+ * Is true
if this is Java version 1.7 (also 1.7.x versions).
+ *
+ *
+ *
+ * The field will return false
if {@link #JAVA_VERSION} is null
.
+ *
+ *
+ * @since 2.5
+ */
+ public static final boolean IS_JAVA_1_7 = getJavaVersionMatches("1.7");
+
// Operating system checks
- //-----------------------------------------------------------------------
+ // -----------------------------------------------------------------------
// These MUST be declared after those above as they depend on the
// values being set up
// OS names from http://www.vamphq.com/os.html
- // Selected ones included - please advise commons-dev@jakarta.apache.org
+ // Selected ones included - please advise dev@commons.apache.org
// if you want another added or a mistake corrected
/**
- * Is true
if this is AIX.
- *
- * The field will return false
if OS_NAME
is
- * null
.
+ *
+ * Is true
if this is AIX.
+ *
*
+ *
+ * The field will return false
if OS_NAME
is null
.
+ *
+ *
* @since 2.0
*/
- public static final boolean IS_OS_AIX = getOSMatches("AIX");
+ public static final boolean IS_OS_AIX = getOSMatchesName("AIX");
/**
- * Is true
if this is HP-UX.
- *
- * The field will return false
if OS_NAME
is
- * null
.
+ *
+ * Is true
if this is HP-UX.
+ *
*
+ *
+ * The field will return false
if OS_NAME
is null
.
+ *
+ *
* @since 2.0
*/
- public static final boolean IS_OS_HP_UX = getOSMatches("HP-UX");
+ public static final boolean IS_OS_HP_UX = getOSMatchesName("HP-UX");
/**
- * Is true
if this is Irix.
- *
- * The field will return false
if OS_NAME
is
- * null
.
+ *
+ * Is true
if this is Irix.
+ *
*
+ *
+ * The field will return false
if OS_NAME
is null
.
+ *
+ *
* @since 2.0
*/
- public static final boolean IS_OS_IRIX = getOSMatches("Irix");
+ public static final boolean IS_OS_IRIX = getOSMatchesName("Irix");
/**
- * Is true
if this is Linux.
- *
- * The field will return false
if OS_NAME
is
- * null
.
+ *
+ * Is true
if this is Linux.
+ *
*
+ *
+ * The field will return false
if OS_NAME
is null
.
+ *
+ *
* @since 2.0
*/
- public static final boolean IS_OS_LINUX = getOSMatches("Linux") || getOSMatches("LINUX");
+ public static final boolean IS_OS_LINUX = getOSMatchesName("Linux") || getOSMatchesName("LINUX");
/**
- * Is true
if this is Mac.
- *
- * The field will return false
if OS_NAME
is
- * null
.
+ *
+ * Is true
if this is Mac.
+ *
*
+ *
+ * The field will return false
if OS_NAME
is null
.
+ *
+ *
* @since 2.0
*/
- public static final boolean IS_OS_MAC = getOSMatches("Mac");
+ public static final boolean IS_OS_MAC = getOSMatchesName("Mac");
/**
- * Is true
if this is Mac.
- *
- * The field will return false
if OS_NAME
is
- * null
.
+ *
+ * Is true
if this is Mac.
+ *
*
+ *
+ * The field will return false
if OS_NAME
is null
.
+ *
+ *
* @since 2.0
*/
- public static final boolean IS_OS_MAC_OSX = getOSMatches("Mac OS X");
+ public static final boolean IS_OS_MAC_OSX = getOSMatchesName("Mac OS X");
/**
- * Is true
if this is OS/2.
- *
- * The field will return false
if OS_NAME
is
- * null
.
+ *
+ * Is true
if this is OS/2.
+ *
*
+ *
+ * The field will return false
if OS_NAME
is null
.
+ *
+ *
* @since 2.0
*/
- public static final boolean IS_OS_OS2 = getOSMatches("OS/2");
+ public static final boolean IS_OS_OS2 = getOSMatchesName("OS/2");
/**
- * Is true
if this is Solaris.
- *
- * The field will return false
if OS_NAME
is
- * null
.
+ *
+ * Is true
if this is Solaris.
+ *
*
+ *
+ * The field will return false
if OS_NAME
is null
.
+ *
+ *
* @since 2.0
*/
- public static final boolean IS_OS_SOLARIS = getOSMatches("Solaris");
+ public static final boolean IS_OS_SOLARIS = getOSMatchesName("Solaris");
/**
- * Is true
if this is SunOS.
- *
- * The field will return false
if OS_NAME
is
- * null
.
+ *
+ * Is true
if this is SunOS.
+ *
*
+ *
+ * The field will return false
if OS_NAME
is null
.
+ *
+ *
* @since 2.0
*/
- public static final boolean IS_OS_SUN_OS = getOSMatches("SunOS");
+ public static final boolean IS_OS_SUN_OS = getOSMatchesName("SunOS");
/**
- * Is true
if this is Windows.
- *
- * The field will return false
if OS_NAME
is
- * null
.
+ *
+ * Is true
if this is a UNIX like system,
+ * as in any of AIX, HP-UX, Irix, Linux, MacOSX, Solaris or SUN OS.
+ *
*
+ *
+ * The field will return false
if OS_NAME
is null
.
+ *
+ *
+ * @since 2.1
+ */
+ public static final boolean IS_OS_UNIX =
+ IS_OS_AIX || IS_OS_HP_UX || IS_OS_IRIX || IS_OS_LINUX ||
+ IS_OS_MAC_OSX || IS_OS_SOLARIS || IS_OS_SUN_OS;
+
+ /**
+ *
+ * Is true
if this is Windows.
+ *
+ *
+ *
+ * The field will return false
if OS_NAME
is null
.
+ *
+ *
* @since 2.0
*/
- public static final boolean IS_OS_WINDOWS = getOSMatches("Windows");
+ public static final boolean IS_OS_WINDOWS = getOSMatchesName(OS_NAME_WINDOWS_PREFIX);
/**
- * Is true
if this is Windows 2000.
- *
- * The field will return false
if OS_NAME
is
- * null
.
+ *
+ * Is true
if this is Windows 2000.
+ *
*
+ *
+ * The field will return false
if OS_NAME
is null
.
+ *
+ *
* @since 2.0
*/
- public static final boolean IS_OS_WINDOWS_2000 = getOSMatches("Windows", "5.0");
+ public static final boolean IS_OS_WINDOWS_2000 = getOSMatches(OS_NAME_WINDOWS_PREFIX, "5.0");
/**
- * Is true
if this is Windows 95.
- *
- * The field will return false
if OS_NAME
is
- * null
.
+ *
+ * Is true
if this is Windows 95.
+ *
*
+ *
+ * The field will return false
if OS_NAME
is null
.
+ *
+ *
* @since 2.0
*/
- public static final boolean IS_OS_WINDOWS_95 = getOSMatches("Windows 9", "4.0");
- // JDK 1.2 running on Windows98 returns 'Windows 95', hence the above
+ public static final boolean IS_OS_WINDOWS_95 = getOSMatches(OS_NAME_WINDOWS_PREFIX + " 9", "4.0");
+ // Java 1.2 running on Windows98 returns 'Windows 95', hence the above
/**
- * Is true
if this is Windows 98.
- *
- * The field will return false
if OS_NAME
is
- * null
.
+ *
+ * Is true
if this is Windows 98.
+ *
*
+ *
+ * The field will return false
if OS_NAME
is null
.
+ *
+ *
* @since 2.0
*/
- public static final boolean IS_OS_WINDOWS_98 = getOSMatches("Windows 9", "4.1");
- // JDK 1.2 running on Windows98 returns 'Windows 95', hence the above
+ public static final boolean IS_OS_WINDOWS_98 = getOSMatches(OS_NAME_WINDOWS_PREFIX + " 9", "4.1");
+ // Java 1.2 running on Windows98 returns 'Windows 95', hence the above
/**
- * Is true
if this is Windows ME.
- *
- * The field will return false
if OS_NAME
is
- * null
.
+ *
+ * Is true
if this is Windows ME.
+ *
*
+ *
+ * The field will return false
if OS_NAME
is null
.
+ *
+ *
* @since 2.0
*/
- public static final boolean IS_OS_WINDOWS_ME = getOSMatches("Windows", "4.9");
- // JDK 1.2 running on WindowsME may return 'Windows 95', hence the above
+ public static final boolean IS_OS_WINDOWS_ME = getOSMatches(OS_NAME_WINDOWS_PREFIX, "4.9");
+ // Java 1.2 running on WindowsME may return 'Windows 95', hence the above
/**
- * Is true
if this is Windows NT.
- *
- * The field will return false
if OS_NAME
is
- * null
.
+ *
+ * Is true
if this is Windows NT.
+ *
*
+ *
+ * The field will return false
if OS_NAME
is null
.
+ *
+ *
* @since 2.0
*/
- public static final boolean IS_OS_WINDOWS_NT = getOSMatches("Windows NT");
- // Windows 2000 returns 'Windows 2000' but may suffer from same JDK1.2 problem
+ public static final boolean IS_OS_WINDOWS_NT = getOSMatchesName(OS_NAME_WINDOWS_PREFIX + " NT");
+ // Windows 2000 returns 'Windows 2000' but may suffer from same Java1.2 problem
/**
- * Is true
if this is Windows XP.
- *
- * The field will return false
if OS_NAME
is
- * null
.
+ *
+ * Is true
if this is Windows XP.
+ *
*
+ *
+ * The field will return false
if OS_NAME
is null
.
+ *
+ *
* @since 2.0
*/
- public static final boolean IS_OS_WINDOWS_XP = getOSMatches("Windows", "5.1");
- // Windows XP returns 'Windows 2000' just for fun...
+ public static final boolean IS_OS_WINDOWS_XP = getOSMatches(OS_NAME_WINDOWS_PREFIX, "5.1");
- //-----------------------------------------------------------------------
+ // -----------------------------------------------------------------------
/**
- * SystemUtils instances should NOT be constructed in standard
- * programming. Instead, the class should be used as
- * SystemUtils.FILE_SEPARATOR
.
- *
- * This constructor is public to permit tools that require a JavaBean
- * instance to operate.
+ *
+ * Is true
if this is Windows Vista.
+ *
+ *
+ *
+ * The field will return false
if OS_NAME
is null
.
+ *
+ *
+ * @since 2.4
*/
- public SystemUtils() {
+ public static final boolean IS_OS_WINDOWS_VISTA = getOSMatches(OS_NAME_WINDOWS_PREFIX, "6.0");
+
+ /**
+ *
+ * Is true
if this is Windows 7.
+ *
+ *
+ *
+ * The field will return false
if OS_NAME
is null
.
+ *
+ *
+ * @since 2.5
+ */
+ public static final boolean IS_OS_WINDOWS_7 = getOSMatches(OS_NAME_WINDOWS_PREFIX, "6.1");
+
+ /**
+ *
+ * Gets the Java home directory as a File
.
+ *
+ *
+ * @return a directory
+ * @throws SecurityException if a security manager exists and its
+ * checkPropertyAccess
method doesn't allow access to the specified system property.
+ * @see System#getProperty(String)
+ * @since 2.1
+ */
+ public static File getJavaHome() {
+ return new File(System.getProperty(JAVA_HOME_KEY));
}
-
- //-----------------------------------------------------------------------
+
/**
+ *
+ * Gets the Java IO temporary directory as a File
.
+ *
+ *
+ * @return a directory
+ * @throws SecurityException if a security manager exists and its
+ * checkPropertyAccess
method doesn't allow access to the specified system
+ * property.
+ * @see System#getProperty(String)
+ * @since 2.1
+ */
+ public static File getJavaIoTmpDir() {
+ return new File(System.getProperty(JAVA_IO_TMPDIR_KEY));
+ }
+
+ /**
* Gets the Java version number as a float
.
*
* Example return values:
@@ -732,155 +1404,498 @@
}
/**
- * Gets the Java version number as a float
.
- *
- * Example return values:
+ *
+ * Gets the Java version number as a float
.
+ *
+ *
+ *
+ * Example return values:
+ *
*
- * 1.2f
for JDK 1.2
- * 1.31f
for JDK 1.3.1
+ * 1.2f
for Java 1.2
+ * 1.31f
for Java 1.3.1
+ * 1.6f
for Java 1.6.0_20
*
*
- * Patch releases are not reported.
- * Zero is returned if {@link #JAVA_VERSION} is null
.
+ *
+ * Patch releases are not reported.
+ *
*
- * @return the version, for example 1.31f for JDK 1.3.1
+ * @return the version, for example 1.31f for Java 1.3.1
*/
private static float getJavaVersionAsFloat() {
- if (JAVA_VERSION == null) {
- return 0f;
- }
- String str = JAVA_VERSION.substring(0, 3);
- if (JAVA_VERSION.length() >= 5) {
- str = str + JAVA_VERSION.substring(4, 5);
- }
- return Float.parseFloat(str);
+ return toVersionFloat(toJavaVersionIntArray(SystemUtils.JAVA_VERSION, JAVA_VERSION_TRIM_SIZE));
}
-
+
/**
- * Gets the Java version number as an int
.
- *
- * Example return values:
+ *
+ * Gets the Java version number as an int
.
+ *
+ *
+ *
+ * Example return values:
+ *
*
- * 120
for JDK 1.2
- * 131
for JDK 1.3.1
+ * 120
for Java 1.2
+ * 131
for Java 1.3.1
+ * 160
for Java 1.6.0_20
*
*
- * Patch releases are not reported.
- * Zero is returned if {@link #JAVA_VERSION} is null
.
+ *
+ * Patch releases are not reported.
+ *
*
- * @return the version, for example 131 for JDK 1.3.1
+ * @return the version, for example 131 for Java 1.3.1
*/
private static int getJavaVersionAsInt() {
- if (JAVA_VERSION == null) {
- return 0;
- }
- String str = JAVA_VERSION.substring(0, 1);
- str = str + JAVA_VERSION.substring(2, 3);
- if (JAVA_VERSION.length() >= 5) {
- str = str + JAVA_VERSION.substring(4, 5);
- } else {
- str = str + "0";
- }
- return Integer.parseInt(str);
+ return toVersionInt(toJavaVersionIntArray(SystemUtils.JAVA_VERSION, JAVA_VERSION_TRIM_SIZE));
}
/**
- * Decides if the java version matches.
+ *
+ * Decides if the Java version matches.
+ *
*
- * @param versionPrefix the prefix for the java version
+ * @param versionPrefix
+ * the prefix for the java version
* @return true if matches, or false if not or can't determine
*/
private static boolean getJavaVersionMatches(String versionPrefix) {
- if (JAVA_VERSION == null) {
- return false;
- }
- return JAVA_VERSION.startsWith(versionPrefix);
- }
-
+ return isJavaVersionMatch(JAVA_VERSION_TRIMMED, versionPrefix);
+ }
+
/**
- * Decides if the operating system matches.
+ * Trims the text of the java version to start with numbers.
*
- * @param osNamePrefix the prefix for the os name
- * @return true if matches, or false if not or can't determine
+ * @return the trimmed java version
*/
- private static boolean getOSMatches(String osNamePrefix) {
- if (OS_NAME == null) {
- return false;
+ private static String getJavaVersionTrimmed() {
+ if (JAVA_VERSION != null) {
+ for (int i = 0; i < JAVA_VERSION.length(); i++) {
+ char ch = JAVA_VERSION.charAt(i);
+ if (ch >= '0' && ch <= '9') {
+ return JAVA_VERSION.substring(i);
+ }
+ }
}
- return OS_NAME.startsWith(osNamePrefix);
- }
+ return null;
+ }
/**
- * Decides if the operating system matches.
+ * Decides if the operating system matches.
*
- * @param osNamePrefix the prefix for the os name
- * @param osVersionPrefix the prefix for the version
+ * @param osNamePrefix
+ * the prefix for the os name
+ * @param osVersionPrefix
+ * the prefix for the version
* @return true if matches, or false if not or can't determine
*/
private static boolean getOSMatches(String osNamePrefix, String osVersionPrefix) {
- if (OS_NAME == null || OS_VERSION == null) {
- return false;
- }
- return OS_NAME.startsWith(osNamePrefix) && OS_VERSION.startsWith(osVersionPrefix);
- }
+ return isOSMatch(OS_NAME, OS_VERSION, osNamePrefix, osVersionPrefix);
+ }
- //-----------------------------------------------------------------------
/**
- * Gets a System property, defaulting to null
if the property
- * cannot be read.
- *
- * If a SecurityException
is caught, the return
- * value is null
and a message is written to System.err
.
+ * Decides if the operating system matches.
*
- * @param property the system property name
+ * @param osNamePrefix
+ * the prefix for the os name
+ * @return true if matches, or false if not or can't determine
+ */
+ private static boolean getOSMatchesName(String osNamePrefix) {
+ return isOSNameMatch(OS_NAME, osNamePrefix);
+ }
+
+ // -----------------------------------------------------------------------
+ /**
+ *
+ * Gets a System property, defaulting to null
if the property cannot be read.
+ *
+ *
+ *
+ * If a SecurityException
is caught, the return value is null
and a message is written to
+ * System.err
.
+ *
+ *
+ * @param property
+ * the system property name
* @return the system property value or null
if a security problem occurs
*/
private static String getSystemProperty(String property) {
try {
return System.getProperty(property);
} catch (SecurityException ex) {
// we are not allowed to look at this property
- System.err.println(
- "Caught a SecurityException reading the system property '" + property
- + "'; the SystemUtils property value will default to null."
- );
+ System.err.println("Caught a SecurityException reading the system property '" + property
+ + "'; the SystemUtils property value will default to null.");
return null;
}
- }
-
+ }
+
/**
- * Is the Java version at least the requested version.
- *
- * Example input:
+ *
+ * Gets the user directory as a File
.
+ *
+ *
+ * @return a directory
+ * @throws SecurityException if a security manager exists and its
+ * checkPropertyAccess
method doesn't allow access to the specified system property.
+ * @see System#getProperty(String)
+ * @since 2.1
+ */
+ public static File getUserDir() {
+ return new File(System.getProperty(USER_DIR_KEY));
+ }
+
+ /**
+ *
+ * Gets the user home directory as a File
.
+ *
+ *
+ * @return a directory
+ * @throws SecurityException if a security manager exists and its
+ * checkPropertyAccess
method doesn't allow access to the specified system property.
+ * @see System#getProperty(String)
+ * @since 2.1
+ */
+ public static File getUserHome() {
+ return new File(System.getProperty(USER_HOME_KEY));
+ }
+
+ /**
+ * Returns whether the {@link #JAVA_AWT_HEADLESS} value is true
.
+ *
+ * @return true
if JAVA_AWT_HEADLESS
is "true"
, false
otherwise.
+ *
+ * @see #JAVA_AWT_HEADLESS
+ * @since 2.1
+ * @since Java 1.4
+ */
+ public static boolean isJavaAwtHeadless() {
+ return JAVA_AWT_HEADLESS != null ? JAVA_AWT_HEADLESS.equals(Boolean.TRUE.toString()) : false;
+ }
+
+ /**
+ *
+ * Is the Java version at least the requested version.
+ *
+ *
+ *
+ * Example input:
+ *
*
- * 1.2f
to test for JDK 1.2
- * 1.31f
to test for JDK 1.3.1
+ * 1.2f
to test for Java 1.2
+ * 1.31f
to test for Java 1.3.1
*
*
- * @param requiredVersion the required version, for example 1.31f
- * @return true
if the actual version is equal or greater
- * than the required version
+ * @param requiredVersion
+ * the required version, for example 1.31f
+ * @return true
if the actual version is equal or greater than the required version
*/
public static boolean isJavaVersionAtLeast(float requiredVersion) {
- return (JAVA_VERSION_FLOAT >= requiredVersion);
+ return JAVA_VERSION_FLOAT >= requiredVersion;
}
-
+
/**
- * Is the Java version at least the requested version.
- *
- * Example input:
+ *
+ * Is the Java version at least the requested version.
+ *
+ *
+ *
+ * Example input:
+ *
*
- * 120
to test for JDK 1.2 or greater
- * 131
to test for JDK 1.3.1 or greater
+ * 120
to test for Java 1.2 or greater
+ * 131
to test for Java 1.3.1 or greater
*
*
- * @param requiredVersion the required version, for example 131
- * @return true
if the actual version is equal or greater
- * than the required version
+ * @param requiredVersion
+ * the required version, for example 131
+ * @return true
if the actual version is equal or greater than the required version
* @since 2.0
*/
public static boolean isJavaVersionAtLeast(int requiredVersion) {
- return (JAVA_VERSION_INT >= requiredVersion);
+ return JAVA_VERSION_INT >= requiredVersion;
}
-
+
+ /**
+ *
+ * Decides if the Java version matches.
+ *
+ *
+ * This method is package private instead of private to support unit test invocation.
+ *
+ *
+ * @param version
+ * the actual Java version
+ * @param versionPrefix
+ * the prefix for the expected Java version
+ * @return true if matches, or false if not or can't determine
+ */
+ static boolean isJavaVersionMatch(String version, String versionPrefix) {
+ if (version == null) {
+ return false;
+ }
+ return version.startsWith(versionPrefix);
+ }
+
+ /**
+ * Decides if the operating system matches.
+ *
+ * This method is package private instead of private to support unit test invocation.
+ *
+ *
+ * @param osName
+ * the actual OS name
+ * @param osVersion
+ * the actual OS version
+ * @param osNamePrefix
+ * the prefix for the expected OS name
+ * @param osVersionPrefix
+ * the prefix for the expected OS version
+ * @return true if matches, or false if not or can't determine
+ */
+ static boolean isOSMatch(String osName, String osVersion, String osNamePrefix, String osVersionPrefix) {
+ if (osName == null || osVersion == null) {
+ return false;
+ }
+ return osName.startsWith(osNamePrefix) && osVersion.startsWith(osVersionPrefix);
+ }
+
+ /**
+ * Decides if the operating system matches.
+ *
+ * This method is package private instead of private to support unit test invocation.
+ *
+ *
+ * @param osName
+ * the actual OS name
+ * @param osNamePrefix
+ * the prefix for the expected OS name
+ * @return true if matches, or false if not or can't determine
+ */
+ static boolean isOSNameMatch(String osName, String osNamePrefix) {
+ if (osName == null) {
+ return false;
+ }
+ return osName.startsWith(osNamePrefix);
+ }
+
+ /**
+ *
+ * Converts the given Java version string to a float
.
+ *
+ *
+ *
+ * Example return values:
+ *
+ *
+ * 1.2f
for Java 1.2
+ * 1.31f
for Java 1.3.1
+ * 1.6f
for Java 1.6.0_20
+ *
+ *
+ *
+ * Patch releases are not reported.
+ *
+ *
+ * This method is package private instead of private to support unit test invocation.
+ *
+ *
+ * @param version The string version
+ * @return the version, for example 1.31f for Java 1.3.1
+ */
+ static float toJavaVersionFloat(String version) {
+ return toVersionFloat(toJavaVersionIntArray(version, JAVA_VERSION_TRIM_SIZE));
+ }
+
+ /**
+ *
+ * Converts the given Java version string to an int
.
+ *
+ *
+ *
+ * Example return values:
+ *
+ *
+ * 120
for Java 1.2
+ * 131
for Java 1.3.1
+ * 160
for Java 1.6.0_20
+ *
+ *
+ *
+ * Patch releases are not reported.
+ *
+ *
+ * This method is package private instead of private to support unit test invocation.
+ *
+ *
+ * @param version The string version
+ * @return the version, for example 131 for Java 1.3.1
+ */
+ static int toJavaVersionInt(String version) {
+ return toVersionInt(toJavaVersionIntArray(version, JAVA_VERSION_TRIM_SIZE));
+ }
+
+ /**
+ *
+ * Converts the given Java version string to an int[]
of maximum size 3
.
+ *
+ *
+ *
+ * Example return values:
+ *
+ *
+ * [1, 2, 0]
for Java 1.2
+ * [1, 3, 1]
for Java 1.3.1
+ * [1, 5, 0]
for Java 1.5.0_21
+ *
+ *
+ * This method is package private instead of private to support unit test invocation.
+ *
+ *
+ * @param version The string version
+ * @return the version, for example [1, 5, 0] for Java 1.5.0_21
+ */
+ static int[] toJavaVersionIntArray(String version) {
+ return toJavaVersionIntArray(version, Integer.MAX_VALUE);
+ }
+
+ /**
+ *
+ * Converts the given Java version string to an int[]
of maximum size limit
.
+ *
+ *
+ *
+ * Example return values:
+ *
+ *
+ * [1, 2, 0]
for Java 1.2
+ * [1, 3, 1]
for Java 1.3.1
+ * [1, 5, 0, 21]
for Java 1.5.0_21
+ *
+ *
+ * @param version The string version
+ * @param limit version limit
+ * @return the version, for example [1, 5, 0, 21] for Java 1.5.0_21
+ */
+ private static int[] toJavaVersionIntArray(String version, int limit) {
+ if (version == null) {
+ return ArrayUtils.EMPTY_INT_ARRAY;
+ }
+ String[] strings = StringUtils.split(version, "._- ");
+ int[] ints = new int[Math.min(limit, strings.length)];
+ int j = 0;
+ for (int i = 0; i < strings.length && j < limit; i++) {
+ String s = strings[i];
+ if (s.length() > 0) {
+ try {
+ ints[j] = Integer.parseInt(s);
+ j++;
+ } catch (Exception e) {
+ }
+ }
+ }
+ if (ints.length > j) {
+ int[] newInts = new int[j];
+ System.arraycopy(ints, 0, newInts, 0, j);
+ ints = newInts;
+ }
+ return ints;
+ }
+
+ /**
+ *
+ * Converts given the Java version array to a float
.
+ *
+ *
+ *
+ * Example return values:
+ *
+ *
+ * 1.2f
for Java 1.2
+ * 1.31f
for Java 1.3.1
+ * 1.6f
for Java 1.6.0_20
+ *
+ *
+ *
+ * Patch releases are not reported.
+ *
+ *
+ * @param javaVersions The version numbers
+ * @return the version, for example 1.31f for Java 1.3.1
+ */
+ private static float toVersionFloat(int[] javaVersions) {
+ if (javaVersions == null || javaVersions.length == 0) {
+ return 0f;
+ }
+ if (javaVersions.length == 1) {
+ return javaVersions[0];
+ }
+ StringBuffer builder = new StringBuffer();
+ builder.append(javaVersions[0]);
+ builder.append('.');
+ for (int i = 1; i < javaVersions.length; i++) {
+ builder.append(javaVersions[i]);
+ }
+ try {
+ return Float.parseFloat(builder.toString());
+ } catch (Exception ex) {
+ return 0f;
+ }
+ }
+
+ /**
+ *
+ * Converts given the Java version array to an int
.
+ *
+ *
+ *
+ * Example return values:
+ *
+ *
+ * 120
for Java 1.2
+ * 131
for Java 1.3.1
+ * 160
for Java 1.6.0_20
+ *
+ *
+ *
+ * Patch releases are not reported.
+ *
+ *
+ * @param javaVersions The version numbers
+ * @return the version, for example 1.31f for Java 1.3.1
+ */
+ private static int toVersionInt(int[] javaVersions) {
+ if (javaVersions == null) {
+ return 0;
+ }
+ int intVersion = 0;
+ int len = javaVersions.length;
+ if (len >= 1) {
+ intVersion = javaVersions[0] * 100;
+ }
+ if (len >= 2) {
+ intVersion += javaVersions[1] * 10;
+ }
+ if (len >= 3) {
+ intVersion += javaVersions[2];
+ }
+ return intVersion;
+ }
+
+ // -----------------------------------------------------------------------
+ /**
+ *
+ * SystemUtils instances should NOT be constructed in standard programming. Instead, the class should be used as
+ * SystemUtils.FILE_SEPARATOR
.
+ *
+ *
+ *
+ * This constructor is public to permit tools that require a JavaBean instance to operate.
+ *
+ */
+ public SystemUtils() {
+ super();
+ }
+
}
Index: 3rdParty_sources/commons-lang/org/apache/commons/lang/UnhandledException.java
===================================================================
RCS file: /usr/local/cvsroot/3rdParty_sources/commons-lang/org/apache/commons/lang/UnhandledException.java,v
diff -u -r1.1 -r1.2
--- 3rdParty_sources/commons-lang/org/apache/commons/lang/UnhandledException.java 30 Aug 2012 16:24:42 -0000 1.1
+++ 3rdParty_sources/commons-lang/org/apache/commons/lang/UnhandledException.java 15 Mar 2013 09:52:49 -0000 1.2
@@ -1,87 +1,73 @@
-/* ====================================================================
- * The Apache Software License, Version 1.1
- *
- * Copyright (c) 2002-2003 The Apache Software Foundation. All rights
- * reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in
- * the documentation and/or other materials provided with the
- * distribution.
- *
- * 3. The end-user documentation included with the redistribution, if
- * any, must include the following acknowledgement:
- * "This product includes software developed by the
- * Apache Software Foundation (http://www.apache.org/)."
- * Alternately, this acknowledgement may appear in the software itself,
- * if and wherever such third-party acknowledgements normally appear.
- *
- * 4. The names "The Jakarta Project", "Commons", and "Apache Software
- * Foundation" must not be used to endorse or promote products derived
- * from this software without prior written permission. For written
- * permission, please contact apache@apache.org.
- *
- * 5. Products derived from this software may not be called "Apache"
- * nor may "Apache" appear in their names without prior written
- * permission of the Apache Software Foundation.
- *
- * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
- * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
- * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
- * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- * ====================================================================
- *
- * This software consists of voluntary contributions made by many
- * individuals on behalf of the Apache Software Foundation. For more
- * information on the Apache Software Foundation, please see
- * .
+/*
+ * 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.lang;
import org.apache.commons.lang.exception.NestableRuntimeException;
/**
- * Thrown when it is impossible or undesirable to consume
- * or throw a checked exception.
+ * Thrown when it is impossible or undesirable to consume or throw a checked exception.
+ * This exception supplements the standard exception classes by providing a more
+ * semantically rich description of the problem.
*
+ * UnhandledException
represents the case where a method has to deal
+ * with a checked exception but does not wish to.
+ * Instead, the checked exception is rethrown in this unchecked wrapper.
+ *
+ *
+ * public void foo() {
+ * try {
+ * // do something that throws IOException
+ * } catch (IOException ex) {
+ * // don't want to or can't throw IOException from foo()
+ * throw new UnhandledException(ex);
+ * }
+ * }
+ *
+ *
* @author Matthew Hawthorne
* @since 2.0
* @version $Id$
*/
public class UnhandledException extends NestableRuntimeException {
/**
- * Constructs the exception using a cause.
+ * Required for serialization support.
*
+ * @see java.io.Serializable
+ */
+ private static final long serialVersionUID = 1832101364842773720L;
+
+ /**
+ * Constructs the exception using a cause.
+ *
* @param cause the underlying cause
*/
- public UnhandledException(Throwable cause) {
- super(cause);
- }
+ public UnhandledException(Throwable cause) {
+ super(cause);
+ }
/**
* Constructs the exception using a message and cause.
- *
+ *
* @param message the message to use
* @param cause the underlying cause
*/
- public UnhandledException(String message, Throwable cause) {
- super(message, cause);
- }
+ public UnhandledException(String message, Throwable cause) {
+ super(message, cause);
+ }
}
Index: 3rdParty_sources/commons-lang/org/apache/commons/lang/Validate.java
===================================================================
RCS file: /usr/local/cvsroot/3rdParty_sources/commons-lang/org/apache/commons/lang/Validate.java,v
diff -u -r1.1 -r1.2
--- 3rdParty_sources/commons-lang/org/apache/commons/lang/Validate.java 30 Aug 2012 16:24:42 -0000 1.1
+++ 3rdParty_sources/commons-lang/org/apache/commons/lang/Validate.java 15 Mar 2013 09:52:49 -0000 1.2
@@ -1,55 +1,18 @@
-/* ====================================================================
- * The Apache Software License, Version 1.1
- *
- * Copyright (c) 2002-2003 The Apache Software Foundation. All rights
- * reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in
- * the documentation and/or other materials provided with the
- * distribution.
- *
- * 3. The end-user documentation included with the redistribution, if
- * any, must include the following acknowledgement:
- * "This product includes software developed by the
- * Apache Software Foundation (http://www.apache.org/)."
- * Alternately, this acknowledgement may appear in the software itself,
- * if and wherever such third-party acknowledgements normally appear.
- *
- * 4. The names "The Jakarta Project", "Commons", and "Apache Software
- * Foundation" must not be used to endorse or promote products derived
- * from this software without prior written permission. For written
- * permission, please contact apache@apache.org.
- *
- * 5. Products derived from this software may not be called "Apache"
- * nor may "Apache" appear in their names without prior written
- * permission of the Apache Software Foundation.
- *
- * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
- * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
- * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
- * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- * ====================================================================
- *
- * This software consists of voluntary contributions made by many
- * individuals on behalf of the Apache Software Foundation. For more
- * information on the Apache Software Foundation, please see
- * .
+/*
+ * 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.lang;
@@ -58,7 +21,7 @@
import java.util.Map;
/**
- * Assists in validating arguments.
+ * This class assists in validating arguments.
*
* The class is based along the lines of JUnit. If an argument value is
* deemed invalid, an IllegalArgumentException is thrown. For example:
@@ -68,42 +31,39 @@
* Validate.notNull( surname, "The surname must not be null");
*
*
+ * @author Apache Software Foundation
* @author Ola Berg
- * @author Stephen Colebourne
* @author Gary Gregory
+ * @author Norm Deane
* @since 2.0
* @version $Id$
*/
public class Validate {
+ // Validate has no dependencies on other classes in Commons Lang at present
/**
* Constructor. This class should not normally be instantiated.
*/
public Validate() {
+ super();
}
-
+
// isTrue
//---------------------------------------------------------------------------------
-
/**
- * Validate an argument, throwing IllegalArgumentException
- * if the test result is false
.
- *
- * This is used when validating according to an arbitrary boolean expression,
- * such as validating a primitive number or using your own custom validation
- * expression.
+ * Validate that the argument condition is true
; otherwise
+ * throwing an exception with the specified message. This method is useful when
+ * validating according to an arbitrary boolean expression, such as validating an
+ * object or using your own custom validation expression.
*
- *
- * Validate.isTrue( myObject.isOk(), "The object is not OK: ", myObject);
- *
+ * Validate.isTrue( myObject.isOk(), "The object is not OK: ", myObject);
*
- * For performance reasons, the object is passed as a separate parameter and
- * appended to the message string only in the case of an error.
+ * For performance reasons, the object value is passed as a separate parameter and
+ * appended to the exception message only in the case of an error.
*
- * @param expression a boolean expression
- * @param message the exception message you would like to see if the
- * expression is false
- * @param value the value to append to the message in case of error
+ * @param expression the boolean expression to check
+ * @param message the exception message if invalid
+ * @param value the value to append to the message when invalid
* @throws IllegalArgumentException if expression is false
*/
public static void isTrue(boolean expression, String message, Object value) {
@@ -113,23 +73,19 @@
}
/**
- * Validate an argument, throwing IllegalArgumentException
- * if the test result is false
.
- *
- * This is used when validating according to an arbitrary boolean expression,
- * such as validating a primitive number or using your own custom validation
- * expression.
+ * Validate that the argument condition is true
; otherwise
+ * throwing an exception with the specified message. This method is useful when
+ * validating according to an arbitrary boolean expression, such as validating a
+ * primitive number or using your own custom validation expression.
*
- *
- * Validate.isTrue( i > 0, "The value must be greater than zero: ", i);
- *
+ * Validate.isTrue(i > 0.0, "The value must be greater than zero: ", i);
*
- * For performance reasons, the object is passed as a separate parameter and
- * appended to the message string only in the case of an error.
+ * For performance reasons, the long value is passed as a separate parameter and
+ * appended to the exception message only in the case of an error.
*
- * @param expression a boolean expression
- * @param message the exception message you would like to see if the expression is false
- * @param value the value to append to the message in case of error
+ * @param expression the boolean expression to check
+ * @param message the exception message if invalid
+ * @param value the value to append to the message when invalid
* @throws IllegalArgumentException if expression is false
*/
public static void isTrue(boolean expression, String message, long value) {
@@ -139,24 +95,19 @@
}
/**
- * Validate an argument, throwing IllegalArgumentException
- * if the test result is false
.
- *
- * This is used when validating according to an arbitrary boolean expression,
- * such as validating a primitive number or using your own custom validation
- * expression.
+ * Validate that the argument condition is true
; otherwise
+ * throwing an exception with the specified message. This method is useful when
+ * validating according to an arbitrary boolean expression, such as validating a
+ * primitive number or using your own custom validation expression.
*
- *
- * Validate.isTrue( d > 0.0, "The value must be greater than zero: ", d);
- *
+ * Validate.isTrue(d > 0.0, "The value must be greater than zero: ", d);
*
- * For performance reasons, the object is passed as a separate parameter and
- * appended to the message string only in the case of an error.
+ * For performance reasons, the double value is passed as a separate parameter and
+ * appended to the exception message only in the case of an error.
*
- * @param expression a boolean expression
- * @param message the exception message you would like to see if the expression
- * is false
- * @param value the value to append to the message in case of error
+ * @param expression the boolean expression to check
+ * @param message the exception message if invalid
+ * @param value the value to append to the message when invalid
* @throws IllegalArgumentException if expression is false
*/
public static void isTrue(boolean expression, String message, double value) {
@@ -166,24 +117,18 @@
}
/**
- * Validate an argument, throwing IllegalArgumentException
- * if the test result is false
.
- *
- * This is used when validating according to an arbitrary boolean expression,
- * such as validating a primitive number or using your own custom validation
- * expression.
+ * Validate that the argument condition is true
; otherwise
+ * throwing an exception with the specified message. This method is useful when
+ * validating according to an arbitrary boolean expression, such as validating a
+ * primitive number or using your own custom validation expression.
*
*
* Validate.isTrue( (i > 0), "The value must be greater than zero");
* Validate.isTrue( myObject.isOk(), "The object is not OK");
*
*
- * For performance reasons, the message string should not involve a string append,
- * instead use the {@link #isTrue(boolean, String, Object)} method.
- *
- * @param expression a boolean expression
- * @param message the exception message you would like to see if the expression
- * is false
+ * @param expression the boolean expression to check
+ * @param message the exception message if invalid
* @throws IllegalArgumentException if expression is false
*/
public static void isTrue(boolean expression, String message) {
@@ -193,21 +138,19 @@
}
/**
- * Validate an argument, throwing IllegalArgumentException
- * if the test result is false
.
- *
- * This is used when validating according to an arbitrary boolean expression,
- * such as validating a primitive number or using your own custom validation
- * expression.
+ * Validate that the argument condition is true
; otherwise
+ * throwing an exception. This method is useful when validating according
+ * to an arbitrary boolean expression, such as validating a
+ * primitive number or using your own custom validation expression.
*
*
- * Validate.isTrue( i > 0 );
- * Validate.isTrue( myObject.isOk() );
- *
+ * Validate.isTrue(i > 0);
+ * Validate.isTrue(myObject.isOk());
*
- * The message in the exception is 'The validated expression is false'.
+ * The message of the exception is "The validated expression is
+ * false".
*
- * @param expression a boolean expression
+ * @param expression the boolean expression to check
* @throws IllegalArgumentException if expression is false
*/
public static void isTrue(boolean expression) {
@@ -220,56 +163,48 @@
//---------------------------------------------------------------------------------
/**
- * Validate an argument, throwing IllegalArgumentException
- * if the argument is null
.
+ * Validate that the specified argument is not null
;
+ * otherwise throwing an exception.
*
- *
- * Validate.notNull(myObject, "The object must not be null");
- *
+ * Validate.notNull(myObject);
+ *
+ * The message of the exception is "The validated object is
+ * null".
*
- * @param object the object to check is not null
- * @param message the exception message you would like to see
- * if the object is null
+ * @param object the object to check
* @throws IllegalArgumentException if the object is null
*/
- public static void notNull(Object object, String message) {
- if (object == null) {
- throw new IllegalArgumentException(message);
- }
+ public static void notNull(Object object) {
+ notNull(object, "The validated object is null");
}
/**
- * Validate an argument, throwing IllegalArgumentException
- * if the argument is null
.
+ * Validate that the specified argument is not null
;
+ * otherwise throwing an exception with the specified message.
*
- *
- * Validate.notNull(myObject);
- *
- *
- * The message in the exception is 'The validated object is null'.
+ * Validate.notNull(myObject, "The object must not be null");
*
- * @param object the object to check is not null
- * @throws IllegalArgumentException if the object is null
+ * @param object the object to check
+ * @param message the exception message if invalid
*/
- public static void notNull(Object object) {
+ public static void notNull(Object object, String message) {
if (object == null) {
- throw new IllegalArgumentException("The validated object is null");
+ throw new IllegalArgumentException(message);
}
}
// notEmpty array
//---------------------------------------------------------------------------------
/**
- * Validate an argument, throwing IllegalArgumentException
- * if the argument array is empty (null
or no elements).
+ * Validate that the specified argument array is neither null
+ * nor a length of zero (no elements); otherwise throwing an exception
+ * with the specified message.
*
- *
- * Validate.notEmpty(myArray, "The array must not be empty");
- *
+ * Validate.notEmpty(myArray, "The array must not be empty");
*
- * @param array the array to check is not empty
- * @param message the exception message you would like to see if the array is empty
+ * @param array the array to check
+ * @param message the exception message if invalid
* @throws IllegalArgumentException if the array is empty
*/
public static void notEmpty(Object[] array, String message) {
@@ -279,37 +214,33 @@
}
/**
- * Validate an argument, throwing IllegalArgumentException
- * if the argument array is empty (null
or no elements).
+ * Validate that the specified argument array is neither null
+ * nor a length of zero (no elements); otherwise throwing an exception.
*
- *
- * Validate.notEmpty(myArray);
- *
- *
- * The message in the exception is 'The validated array is empty'.
+ *
Validate.notEmpty(myArray);
*
- * @param array the array to check is not empty
+ * The message in the exception is "The validated array is
+ * empty".
+ *
+ * @param array the array to check
* @throws IllegalArgumentException if the array is empty
*/
public static void notEmpty(Object[] array) {
- if (array == null || array.length == 0) {
- throw new IllegalArgumentException("The validated array is empty");
- }
+ notEmpty(array, "The validated array is empty");
}
// notEmpty collection
//---------------------------------------------------------------------------------
/**
- *
Validate an argument, throwing IllegalArgumentException
- * if the argument Collection is empty (null
or no elements).
+ * Validate that the specified argument collection is neither null
+ * nor a size of zero (no elements); otherwise throwing an exception
+ * with the specified message.
*
- *
- * Validate.notEmpty(myCollection, "The collection must not be empty");
- *
+ * Validate.notEmpty(myCollection, "The collection must not be empty");
*
- * @param collection the collection to check is not empty
- * @param message the exception message you would like to see if the collection is empty
+ * @param collection the collection to check
+ * @param message the exception message if invalid
* @throws IllegalArgumentException if the collection is empty
*/
public static void notEmpty(Collection collection, String message) {
@@ -319,37 +250,33 @@
}
/**
- * Validate an argument, throwing IllegalArgumentException
- * if the argument Collection is empty (null
or no elements).
+ * Validate that the specified argument collection is neither null
+ * nor a size of zero (no elements); otherwise throwing an exception.
*
- *
- * Validate.notEmpty(myCollection);
- *
- *
- * The message in the exception is 'The validated collection is empty'.
+ * Validate.notEmpty(myCollection);
*
- * @param collection the collection to check is not empty
+ * The message in the exception is "The validated collection is
+ * empty".
+ *
+ * @param collection the collection to check
* @throws IllegalArgumentException if the collection is empty
*/
public static void notEmpty(Collection collection) {
- if (collection == null || collection.size() == 0) {
- throw new IllegalArgumentException("The validated collection is empty");
- }
+ notEmpty(collection, "The validated collection is empty");
}
// notEmpty map
//---------------------------------------------------------------------------------
/**
- * Validate an argument, throwing IllegalArgumentException
- * if the argument Map is empty (null
or no elements).
+ * Validate that the specified argument map is neither null
+ * nor a size of zero (no elements); otherwise throwing an exception
+ * with the specified message.
*
- *
- * Validate.notEmpty(myMap, "The collection must not be empty");
- *
+ * Validate.notEmpty(myMap, "The map must not be empty");
*
- * @param map the map to check is not empty
- * @param message the exception message you would like to see if the map is empty
+ * @param map the map to check
+ * @param message the exception message if invalid
* @throws IllegalArgumentException if the map is empty
*/
public static void notEmpty(Map map, String message) {
@@ -359,37 +286,34 @@
}
/**
- * Validate an argument, throwing IllegalArgumentException
- * if the argument Map is empty (null
or no elements).
+ * Validate that the specified argument map is neither null
+ * nor a size of zero (no elements); otherwise throwing an exception.
*
- *
- * Validate.notEmpty(myMap);
- *
- *
- * The message in the exception is 'The validated map is empty'.
+ * Validate.notEmpty(myMap);
*
- * @param map the map to check is not empty
+ * The message in the exception is "The validated map is
+ * empty".
+ *
+ * @param map the map to check
* @throws IllegalArgumentException if the map is empty
+ * @see #notEmpty(Map, String)
*/
public static void notEmpty(Map map) {
- if (map == null || map.size() == 0) {
- throw new IllegalArgumentException("The validated map is empty");
- }
+ notEmpty(map, "The validated map is empty");
}
// notEmpty string
//---------------------------------------------------------------------------------
/**
- * Validate an argument, throwing IllegalArgumentException
- * if the argument String is empty (null
or zero length).
+ * Validate that the specified argument string is
+ * neither null
nor a length of zero (no characters);
+ * otherwise throwing an exception with the specified message.
*
- *
- * Validate.notEmpty(myString, "The string must not be empty");
- *
+ * Validate.notEmpty(myString, "The string must not be empty");
*
- * @param string the string to check is not empty
- * @param message the exception message you would like to see if the string is empty
+ * @param string the string to check
+ * @param message the exception message if invalid
* @throws IllegalArgumentException if the string is empty
*/
public static void notEmpty(String string, String message) {
@@ -399,41 +323,39 @@
}
/**
- * Validate an argument, throwing IllegalArgumentException
- * if the argument String is empty (null
or zero length).
+ * Validate that the specified argument string is
+ * neither null
nor a length of zero (no characters);
+ * otherwise throwing an exception with the specified message.
*
- *
- * Validate.notEmpty(myString);
- *
- *
- * The message in the exception is 'The validated string is empty'.
+ * Validate.notEmpty(myString);
*
- * @param string the string to check is not empty
+ * The message in the exception is "The validated
+ * string is empty".
+ *
+ * @param string the string to check
* @throws IllegalArgumentException if the string is empty
*/
public static void notEmpty(String string) {
- if (string == null || string.length() == 0) {
- throw new IllegalArgumentException("The validated string is empty");
- }
+ notEmpty(string, "The validated string is empty");
}
// notNullElements array
//---------------------------------------------------------------------------------
/**
- * Validate an argument, throwing IllegalArgumentException
- * if the argument array has null
elements or is
- * null
.
+ * Validate that the specified argument array is neither
+ * null
nor contains any elements that are null
;
+ * otherwise throwing an exception with the specified message.
*
- *
- * Validate.notEmpty(myArray, "The array must not contain null elements");
- *
+ * Validate.noNullElements(myArray, "The array contain null at position %d");
*
- * @param array the array to check
- * @param message the exception message if the array has
- * null
elements
- * @throws IllegalArgumentException if the array has null
- * elements or is null
+ * If the array is null
, then the message in the exception
+ * is "The validated object is null".
+ *
+ * @param array the array to check
+ * @param message the exception message if the collection has null
elements
+ * @throws IllegalArgumentException if the array is null
or
+ * an element in the array is null
*/
public static void noNullElements(Object[] array, String message) {
Validate.notNull(array);
@@ -445,19 +367,22 @@
}
/**
- * Validate an argument, throwing IllegalArgumentException
- * if the argument array has null
elements or is
- * null
.
+ * Validate that the specified argument array is neither
+ * null
nor contains any elements that are null
;
+ * otherwise throwing an exception.
*
- *
- * Validate.notEmpty(myArray);
- *
- *
- * The message in the exception is 'The validated array contains null element at index: '.
+ * Validate.noNullElements(myArray);
*
- * @param array the array to check
- * @throws IllegalArgumentException if the array has null
- * elements or is null
+ * If the array is null
, then the message in the exception
+ * is "The validated object is null".
+ *
+ * If the array has a null
element, then the message in the
+ * exception is "The validated array contains null element at index:
+ * " followed by the index.
+ *
+ * @param array the array to check
+ * @throws IllegalArgumentException if the array is null
or
+ * an element in the array is null
*/
public static void noNullElements(Object[] array) {
Validate.notNull(array);
@@ -472,51 +397,108 @@
//---------------------------------------------------------------------------------
/**
- * Validate an argument, throwing IllegalArgumentException
- * if the argument collection has null
elements or is
- * null
.
+ * Validate that the specified argument collection is neither
+ * null
nor contains any elements that are null
;
+ * otherwise throwing an exception with the specified message.
*
- *
- * Validate.notEmpty(myCollection, "The collection must not contain null elements");
- *
+ * Validate.noNullElements(myCollection, "The collection contains null elements");
*
+ * If the collection is null
, then the message in the exception
+ * is "The validated object is null".
+ *
+ *
* @param collection the collection to check
- * @param message the exception message if the array has
- * null
elements
- * @throws IllegalArgumentException if the collection has
- * null
elements or is null
+ * @param message the exception message if the collection has
+ * @throws IllegalArgumentException if the collection is null
or
+ * an element in the collection is null
*/
public static void noNullElements(Collection collection, String message) {
Validate.notNull(collection);
+ for (Iterator it = collection.iterator(); it.hasNext();) {
+ if (it.next() == null) {
+ throw new IllegalArgumentException(message);
+ }
+ }
+ }
+
+ /**
+ * Validate that the specified argument collection is neither
+ * null
nor contains any elements that are null
;
+ * otherwise throwing an exception.
+ *
+ *
Validate.noNullElements(myCollection);
+ *
+ * If the collection is null
, then the message in the exception
+ * is "The validated object is null".
+ *
+ * If the collection has a null
element, then the message in the
+ * exception is "The validated collection contains null element at index:
+ * " followed by the index.
+ *
+ * @param collection the collection to check
+ * @throws IllegalArgumentException if the collection is null
or
+ * an element in the collection is null
+ */
+ public static void noNullElements(Collection collection) {
+ Validate.notNull(collection);
int i = 0;
for (Iterator it = collection.iterator(); it.hasNext(); i++) {
if (it.next() == null) {
- throw new IllegalArgumentException(message);
+ throw new IllegalArgumentException("The validated collection contains null element at index: " + i);
}
}
}
/**
* Validate an argument, throwing IllegalArgumentException
- * if the argument collection has null
elements or is
- * null
.
+ * if the argument collection is null
or has elements that
+ * are not of type clazz
or a subclass.
*
*
- * Validate.notEmpty(myCollection);
+ * Validate.allElementsOfType(collection, String.class, "Collection has invalid elements");
*
*
- * The message in the exception is 'The validated collection contains null element at index: '.
+ * @param collection the collection to check, not null
+ * @param clazz the Class
which the collection's elements are expected to be, not null
+ * @param message the exception message if the Collection
has elements not of type clazz
+ * @since 2.1
+ */
+ public static void allElementsOfType(Collection collection, Class clazz, String message) {
+ Validate.notNull(collection);
+ Validate.notNull(clazz);
+ for (Iterator it = collection.iterator(); it.hasNext(); ) {
+ if (clazz.isInstance(it.next()) == false) {
+ throw new IllegalArgumentException(message);
+ }
+ }
+ }
+
+ /**
+ *
+ * Validate an argument, throwing IllegalArgumentException
if the argument collection is
+ * null
or has elements that are not of type clazz
or a subclass.
+ *
*
- * @param collection the collection to check
- * @throws IllegalArgumentException if the collection has
- * null
elements or is null
+ *
+ * Validate.allElementsOfType(collection, String.class);
+ *
+ *
+ *
+ * The message in the exception is 'The validated collection contains an element not of type clazz at index: '.
+ *
+ *
+ * @param collection the collection to check, not null
+ * @param clazz the Class
which the collection's elements are expected to be, not null
+ * @since 2.1
*/
- public static void noNullElements(Collection collection) {
+ public static void allElementsOfType(Collection collection, Class clazz) {
Validate.notNull(collection);
+ Validate.notNull(clazz);
int i = 0;
for (Iterator it = collection.iterator(); it.hasNext(); i++) {
- if (it.next() == null) {
- throw new IllegalArgumentException("The validated collection contains null element at index: " + i);
+ if (clazz.isInstance(it.next()) == false) {
+ throw new IllegalArgumentException("The validated collection contains an element not of type "
+ + clazz.getName() + " at index: " + i);
}
}
}
Index: 3rdParty_sources/commons-lang/org/apache/commons/lang/WordUtils.java
===================================================================
RCS file: /usr/local/cvsroot/3rdParty_sources/commons-lang/org/apache/commons/lang/WordUtils.java,v
diff -u -r1.1 -r1.2
--- 3rdParty_sources/commons-lang/org/apache/commons/lang/WordUtils.java 30 Aug 2012 16:24:42 -0000 1.1
+++ 3rdParty_sources/commons-lang/org/apache/commons/lang/WordUtils.java 15 Mar 2013 09:52:49 -0000 1.2
@@ -1,55 +1,18 @@
-/* ====================================================================
- * The Apache Software License, Version 1.1
- *
- * Copyright (c) 2002-2003 The Apache Software Foundation. All rights
- * reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in
- * the documentation and/or other materials provided with the
- * distribution.
- *
- * 3. The end-user documentation included with the redistribution, if
- * any, must include the following acknowledgement:
- * "This product includes software developed by the
- * Apache Software Foundation (http://www.apache.org/)."
- * Alternately, this acknowledgement may appear in the software itself,
- * if and wherever such third-party acknowledgements normally appear.
- *
- * 4. The names "The Jakarta Project", "Commons", and "Apache Software
- * Foundation" must not be used to endorse or promote products derived
- * from this software without prior written permission. For written
- * permission, please contact apache@apache.org.
- *
- * 5. Products derived from this software may not be called "Apache"
- * nor may "Apache" appear in their names without prior written
- * permission of the Apache Software Foundation.
- *
- * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
- * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
- * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
- * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- * ====================================================================
- *
- * This software consists of voluntary contributions made by many
- * individuals on behalf of the Apache Software Foundation. For more
- * information on the Apache Software Foundation, please see
- * .
+/*
+ * 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.lang;
@@ -61,8 +24,7 @@
* Each method documents its behaviour in more detail.
*
* @author Apache Jakarta Velocity
- * @author Henri Yandell
- * @author Stephen Colebourne
+ * @author Apache Software Foundation
* @author Henning P. Schmiedehausen
* @author Gary Gregory
* @since 2.0
@@ -71,14 +33,15 @@
public class WordUtils {
/**
- * WordWrapUtils
instances should NOT be constructed in
+ *
WordUtils
instances should NOT be constructed in
* standard programming. Instead, the class should be used as
- * WordWrapUtils.wrap("foo bar", 20);
.
+ * WordUtils.wrap("foo bar", 20);
.
*
* This constructor is public to permit tools that require a JavaBean
* instance to operate.
*/
public WordUtils() {
+ super();
}
// Wrapping
@@ -152,7 +115,7 @@
// }
// }
//
-// return (stringBuffer.toString());
+// return stringBuffer.toString();
// }
// Wrapping
@@ -256,8 +219,9 @@
//-----------------------------------------------------------------------
/**
* Capitalizes all the whitespace separated words in a String.
- * Only the first letter of each word is changed. To change all letters to
- * the capitalized case, use {@link #capitalizeFully(String)}.
+ * Only the first letter of each word is changed. To convert the
+ * rest of each word to lowercase at the same time,
+ * use {@link #capitalizeFully(String)}.
*
* Whitespace is defined by {@link Character#isWhitespace(char)}.
* A null
input String returns null
.
@@ -276,67 +240,122 @@
* @see #capitalizeFully(String)
*/
public static String capitalize(String str) {
- int strLen;
- if (str == null || (strLen = str.length()) == 0) {
+ return capitalize(str, null);
+ }
+
+ /**
+ *
Capitalizes all the delimiter separated words in a String.
+ * Only the first letter of each word is changed. To convert the
+ * rest of each word to lowercase at the same time,
+ * use {@link #capitalizeFully(String, char[])}.
+ *
+ * The delimiters represent a set of characters understood to separate words.
+ * The first string character and the first non-delimiter character after a
+ * delimiter will be capitalized.
+ *
+ * A null
input String returns null
.
+ * Capitalization uses the unicode title case, normally equivalent to
+ * upper case.
+ *
+ *
+ * WordUtils.capitalize(null, *) = null
+ * WordUtils.capitalize("", *) = ""
+ * WordUtils.capitalize(*, new char[0]) = *
+ * WordUtils.capitalize("i am fine", null) = "I Am Fine"
+ * WordUtils.capitalize("i aM.fine", {'.'}) = "I aM.Fine"
+ *
+ *
+ * @param str the String to capitalize, may be null
+ * @param delimiters set of characters to determine capitalization, null means whitespace
+ * @return capitalized String, null
if null String input
+ * @see #uncapitalize(String)
+ * @see #capitalizeFully(String)
+ * @since 2.1
+ */
+ public static String capitalize(String str, char[] delimiters) {
+ int delimLen = (delimiters == null ? -1 : delimiters.length);
+ if (str == null || str.length() == 0 || delimLen == 0) {
return str;
}
+ int strLen = str.length();
StringBuffer buffer = new StringBuffer(strLen);
- boolean whitespace = true;
+ boolean capitalizeNext = true;
for (int i = 0; i < strLen; i++) {
char ch = str.charAt(i);
- if (Character.isWhitespace(ch)) {
+
+ if (isDelimiter(ch, delimiters)) {
buffer.append(ch);
- whitespace = true;
- } else if (whitespace) {
+ capitalizeNext = true;
+ } else if (capitalizeNext) {
buffer.append(Character.toTitleCase(ch));
- whitespace = false;
+ capitalizeNext = false;
} else {
buffer.append(ch);
}
}
return buffer.toString();
}
+ //-----------------------------------------------------------------------
/**
- * Capitalizes all the whitespace separated words in a String.
- * All letters are changed, so the resulting string will be fully changed.
+ * Converts all the whitespace separated words in a String into capitalized words,
+ * that is each word is made up of a titlecase character and then a series of
+ * lowercase characters.
*
* Whitespace is defined by {@link Character#isWhitespace(char)}.
* A null
input String returns null
.
* Capitalization uses the unicode title case, normally equivalent to
* upper case.
*
*
- * WordUtils.capitalize(null) = null
- * WordUtils.capitalize("") = ""
- * WordUtils.capitalize("i am FINE") = "I Am Fine"
+ * WordUtils.capitalizeFully(null) = null
+ * WordUtils.capitalizeFully("") = ""
+ * WordUtils.capitalizeFully("i am FINE") = "I Am Fine"
*
*
* @param str the String to capitalize, may be null
* @return capitalized String, null
if null String input
*/
public static String capitalizeFully(String str) {
- int strLen;
- if (str == null || (strLen = str.length()) == 0) {
+ return capitalizeFully(str, null);
+ }
+
+ /**
+ * Converts all the delimiter separated words in a String into capitalized words,
+ * that is each word is made up of a titlecase character and then a series of
+ * lowercase characters.
+ *
+ * The delimiters represent a set of characters understood to separate words.
+ * The first string character and the first non-delimiter character after a
+ * delimiter will be capitalized.
+ *
+ * A null
input String returns null
.
+ * Capitalization uses the unicode title case, normally equivalent to
+ * upper case.
+ *
+ *
+ * WordUtils.capitalizeFully(null, *) = null
+ * WordUtils.capitalizeFully("", *) = ""
+ * WordUtils.capitalizeFully(*, null) = *
+ * WordUtils.capitalizeFully(*, new char[0]) = *
+ * WordUtils.capitalizeFully("i aM.fine", {'.'}) = "I am.Fine"
+ *
+ *
+ * @param str the String to capitalize, may be null
+ * @param delimiters set of characters to determine capitalization, null means whitespace
+ * @return capitalized String, null
if null String input
+ * @since 2.1
+ */
+ public static String capitalizeFully(String str, char[] delimiters) {
+ int delimLen = (delimiters == null ? -1 : delimiters.length);
+ if (str == null || str.length() == 0 || delimLen == 0) {
return str;
}
- StringBuffer buffer = new StringBuffer(strLen);
- boolean whitespace = true;
- for (int i = 0; i < strLen; i++) {
- char ch = str.charAt(i);
- if (Character.isWhitespace(ch)) {
- buffer.append(ch);
- whitespace = true;
- } else if (whitespace) {
- buffer.append(Character.toTitleCase(ch));
- whitespace = false;
- } else {
- buffer.append(Character.toLowerCase(ch));
- }
- }
- return buffer.toString();
+ str = str.toLowerCase();
+ return capitalize(str, delimiters);
}
+ //-----------------------------------------------------------------------
/**
* Uncapitalizes all the whitespace separated words in a String.
* Only the first letter of each word is changed.
@@ -355,27 +374,59 @@
* @see #capitalize(String)
*/
public static String uncapitalize(String str) {
- int strLen;
- if (str == null || (strLen = str.length()) == 0) {
+ return uncapitalize(str, null);
+ }
+
+ /**
+ * Uncapitalizes all the whitespace separated words in a String.
+ * Only the first letter of each word is changed.
+ *
+ * The delimiters represent a set of characters understood to separate words.
+ * The first string character and the first non-delimiter character after a
+ * delimiter will be uncapitalized.
+ *
+ * Whitespace is defined by {@link Character#isWhitespace(char)}.
+ * A null
input String returns null
.
+ *
+ *
+ * WordUtils.uncapitalize(null, *) = null
+ * WordUtils.uncapitalize("", *) = ""
+ * WordUtils.uncapitalize(*, null) = *
+ * WordUtils.uncapitalize(*, new char[0]) = *
+ * WordUtils.uncapitalize("I AM.FINE", {'.'}) = "i AM.fINE"
+ *
+ *
+ * @param str the String to uncapitalize, may be null
+ * @param delimiters set of characters to determine uncapitalization, null means whitespace
+ * @return uncapitalized String, null
if null String input
+ * @see #capitalize(String)
+ * @since 2.1
+ */
+ public static String uncapitalize(String str, char[] delimiters) {
+ int delimLen = (delimiters == null ? -1 : delimiters.length);
+ if (str == null || str.length() == 0 || delimLen == 0) {
return str;
}
+ int strLen = str.length();
StringBuffer buffer = new StringBuffer(strLen);
- boolean whitespace = true;
+ boolean uncapitalizeNext = true;
for (int i = 0; i < strLen; i++) {
char ch = str.charAt(i);
- if (Character.isWhitespace(ch)) {
+
+ if (isDelimiter(ch, delimiters)) {
buffer.append(ch);
- whitespace = true;
- } else if (whitespace) {
+ uncapitalizeNext = true;
+ } else if (uncapitalizeNext) {
buffer.append(Character.toLowerCase(ch));
- whitespace = false;
+ uncapitalizeNext = false;
} else {
buffer.append(ch);
}
}
return buffer.toString();
}
+ //-----------------------------------------------------------------------
/**
* Swaps the case of a String using a word based algorithm.
*
@@ -429,5 +480,168 @@
}
return buffer.toString();
}
-
+
+ //-----------------------------------------------------------------------
+ /**
+ * Extracts the initial letters from each word in the String.
+ *
+ * The first letter of the string and all first letters after
+ * whitespace are returned as a new string.
+ * Their case is not changed.
+ *
+ * Whitespace is defined by {@link Character#isWhitespace(char)}.
+ * A null
input String returns null
.
+ *
+ *
+ * WordUtils.initials(null) = null
+ * WordUtils.initials("") = ""
+ * WordUtils.initials("Ben John Lee") = "BJL"
+ * WordUtils.initials("Ben J.Lee") = "BJ"
+ *
+ *
+ * @param str the String to get initials from, may be null
+ * @return String of initial letters, null
if null String input
+ * @see #initials(String,char[])
+ * @since 2.2
+ */
+ public static String initials(String str) {
+ return initials(str, null);
+ }
+
+ /**
+ * Extracts the initial letters from each word in the String.
+ *
+ * The first letter of the string and all first letters after the
+ * defined delimiters are returned as a new string.
+ * Their case is not changed.
+ *
+ * If the delimiters array is null, then Whitespace is used.
+ * Whitespace is defined by {@link Character#isWhitespace(char)}.
+ * A null
input String returns null
.
+ * An empty delimiter array returns an empty String.
+ *
+ *
+ * WordUtils.initials(null, *) = null
+ * WordUtils.initials("", *) = ""
+ * WordUtils.initials("Ben John Lee", null) = "BJL"
+ * WordUtils.initials("Ben J.Lee", null) = "BJ"
+ * WordUtils.initials("Ben J.Lee", [' ','.']) = "BJL"
+ * WordUtils.initials(*, new char[0]) = ""
+ *
+ *
+ * @param str the String to get initials from, may be null
+ * @param delimiters set of characters to determine words, null means whitespace
+ * @return String of initial letters, null
if null String input
+ * @see #initials(String)
+ * @since 2.2
+ */
+ public static String initials(String str, char[] delimiters) {
+ if (str == null || str.length() == 0) {
+ return str;
+ }
+ if (delimiters != null && delimiters.length == 0) {
+ return "";
+ }
+ int strLen = str.length();
+ char[] buf = new char[strLen / 2 + 1];
+ int count = 0;
+ boolean lastWasGap = true;
+ for (int i = 0; i < strLen; i++) {
+ char ch = str.charAt(i);
+
+ if (isDelimiter(ch, delimiters)) {
+ lastWasGap = true;
+ } else if (lastWasGap) {
+ buf[count++] = ch;
+ lastWasGap = false;
+ } else {
+ // ignore ch
+ }
+ }
+ return new String(buf, 0, count);
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Is the character a delimiter.
+ *
+ * @param ch the character to check
+ * @param delimiters the delimiters
+ * @return true if it is a delimiter
+ */
+ private static boolean isDelimiter(char ch, char[] delimiters) {
+ if (delimiters == null) {
+ return Character.isWhitespace(ch);
+ }
+ for (int i = 0, isize = delimiters.length; i < isize; i++) {
+ if (ch == delimiters[i]) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Abbreviates a string nicely.
+ *
+ * This method searches for the first space after the lower limit and abbreviates
+ * the String there. It will also append any String passed as a parameter
+ * to the end of the String. The upper limit can be specified to forcibly
+ * abbreviate a String.
+ *
+ * @param str the string to be abbreviated. If null is passed, null is returned.
+ * If the empty String is passed, the empty string is returned.
+ * @param lower the lower limit.
+ * @param upper the upper limit; specify -1 if no limit is desired.
+ * If the upper limit is lower than the lower limit, it will be
+ * adjusted to be the same as the lower limit.
+ * @param appendToEnd String to be appended to the end of the abbreviated string.
+ * This is appended ONLY if the string was indeed abbreviated.
+ * The append does not count towards the lower or upper limits.
+ * @return the abbreviated String.
+ * @since 2.4
+ */
+ public static String abbreviate(String str, int lower, int upper, String appendToEnd) {
+ // initial parameter checks
+ if (str == null) {
+ return null;
+ }
+ if (str.length() == 0) {
+ return StringUtils.EMPTY;
+ }
+
+ // if the lower value is greater than the length of the string,
+ // set to the length of the string
+ if (lower > str.length()) {
+ lower = str.length();
+ }
+ // if the upper value is -1 (i.e. no limit) or is greater
+ // than the length of the string, set to the length of the string
+ if (upper == -1 || upper > str.length()) {
+ upper = str.length();
+ }
+ // if upper is less than lower, raise it to lower
+ if (upper < lower) {
+ upper = lower;
+ }
+
+ StringBuffer result = new StringBuffer();
+ int index = StringUtils.indexOf(str, " ", lower);
+ if (index == -1) {
+ result.append(str.substring(0, upper));
+ // only if abbreviation has occured do we append the appendToEnd value
+ if (upper != str.length()) {
+ result.append(StringUtils.defaultString(appendToEnd));
+ }
+ } else if (index > upper) {
+ result.append(str.substring(0, upper));
+ result.append(StringUtils.defaultString(appendToEnd));
+ } else {
+ result.append(str.substring(0, index));
+ result.append(StringUtils.defaultString(appendToEnd));
+ }
+ return result.toString();
+ }
+
}
Index: 3rdParty_sources/commons-lang/org/apache/commons/lang/overview.html
===================================================================
RCS file: /usr/local/cvsroot/3rdParty_sources/commons-lang/org/apache/commons/lang/overview.html,v
diff -u -r1.1 -r1.2
--- 3rdParty_sources/commons-lang/org/apache/commons/lang/overview.html 30 Aug 2012 16:24:42 -0000 1.1
+++ 3rdParty_sources/commons-lang/org/apache/commons/lang/overview.html 15 Mar 2013 09:52:49 -0000 1.2
@@ -1,7 +1,23 @@
+
-This document is the API specification for the Apache Jakarta Commons Lang Library, version 2.0.
+This document is the API specification for the Apache Commons Lang library.
-
\ No newline at end of file
+