Return-Path: Delivered-To: apmail-directory-commits-archive@www.apache.org Received: (qmail 59342 invoked from network); 20 Jan 2006 13:51:20 -0000 Received: from hermes.apache.org (HELO mail.apache.org) (209.237.227.199) by minotaur.apache.org with SMTP; 20 Jan 2006 13:51:20 -0000 Received: (qmail 46926 invoked by uid 500); 20 Jan 2006 13:51:05 -0000 Delivered-To: apmail-directory-commits-archive@directory.apache.org Received: (qmail 46722 invoked by uid 500); 20 Jan 2006 13:51:02 -0000 Mailing-List: contact commits-help@directory.apache.org; run by ezmlm Precedence: bulk List-Help: List-Unsubscribe: List-Post: List-Id: Reply-To: dev@directory.apache.org Delivered-To: mailing list commits@directory.apache.org Received: (qmail 46703 invoked by uid 99); 20 Jan 2006 13:51:02 -0000 Received: from asf.osuosl.org (HELO asf.osuosl.org) (140.211.166.49) by apache.org (qpsmtpd/0.29) with ESMTP; Fri, 20 Jan 2006 05:51:02 -0800 X-ASF-Spam-Status: No, hits=0.6 required=10.0 tests=NO_REAL_NAME X-Spam-Check-By: apache.org Received: from [209.237.227.194] (HELO minotaur.apache.org) (209.237.227.194) by apache.org (qpsmtpd/0.29) with SMTP; Fri, 20 Jan 2006 05:50:50 -0800 Received: (qmail 58157 invoked by uid 65534); 20 Jan 2006 13:50:29 -0000 Message-ID: <20060120135029.58153.qmail@minotaur.apache.org> Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Subject: svn commit: r370807 [6/22] - in /directory/sandbox/trustin/mina-spi: ./ core/src/main/java/org/apache/mina/common/ core/src/main/java/org/apache/mina/common/support/ core/src/main/java/org/apache/mina/common/support/discovery/ core/src/main/java/org/ap... Date: Fri, 20 Jan 2006 13:48:55 -0000 To: commits@directory.apache.org From: trustin@apache.org X-Mailer: svnmailer-1.0.5 X-Virus-Checked: Checked by ClamAV on apache.org X-Spam-Rating: minotaur.apache.org 1.6.2 0/1000/N Propchange: directory/sandbox/trustin/mina-spi/core/src/main/java/org/apache/mina/common/support/lang/ArrayUtils.java ------------------------------------------------------------------------------ svn:keywords = HeadURL Id LastChangedBy LastChangedDate LastChangedRevision Added: directory/sandbox/trustin/mina-spi/core/src/main/java/org/apache/mina/common/support/lang/BitField.java URL: http://svn.apache.org/viewcvs/directory/sandbox/trustin/mina-spi/core/src/main/java/org/apache/mina/common/support/lang/BitField.java?rev=370807&view=auto ============================================================================== --- directory/sandbox/trustin/mina-spi/core/src/main/java/org/apache/mina/common/support/lang/BitField.java (added) +++ directory/sandbox/trustin/mina-spi/core/src/main/java/org/apache/mina/common/support/lang/BitField.java Fri Jan 20 05:47:50 2006 @@ -0,0 +1,289 @@ +/* + * Copyright 2002-2005 The Apache Software Foundation. + * + * Licensed 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.mina.common.support.lang; + +/** + *

Operations on bit-mapped fields.

+ * + * @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 + * @version $Id$ + */ +public class BitField { + + private final int _mask; + private final int _shift_count; + + /** + *

Creates a BitField instance.

+ * + * @param mask the mask specifying which bits apply to this + * BitField. Bits that are set in this mask are the bits + * that this BitField operates on + */ + public BitField(int mask) { + _mask = mask; + int count = 0; + int bit_pattern = mask; + + if (bit_pattern != 0) { + while ((bit_pattern & 1) == 0) { + count++; + bit_pattern >>= 1; + } + } + _shift_count = count; + } + + /** + *

Obtains the value for the specified BitField, appropriately + * shifted right.

+ * + *

Many users of a BitField will want to treat the specified + * bits as an int value, and will not want to be aware that the + * value is stored as a BitField (and so shifted left so many + * bits).

+ * + * @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(int holder) { + return getRawValue(holder) >> _shift_count; + } + + /** + *

Obtains the value for the specified BitField, appropriately + * shifted right, as a short.

+ * + *

Many users of a BitField will want to treat the specified + * bits as an int value, and will not want to be aware that the + * value is stored as a BitField (and so shifted left so many + * bits).

+ * + * @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(short holder) { + return (short) getValue(holder); + } + + /** + *

Obtains the value for the specified BitField, unshifted.

+ * + * @param holder the int data containing the bits we're + * interested in + * @return the selected bits + */ + public int getRawValue(int holder) { + return holder & _mask; + } + + /** + *

Obtains the value for the specified BitField, unshifted.

+ * + * @param holder the short data containing the bits we're + * interested in + * @return the selected bits + */ + public short getShortRawValue(short holder) { + return (short) getRawValue(holder); + } + + /** + *

Returns whether the field is set or not.

+ * + *

This is most commonly used for a single-bit field, which is + * often used to represent a boolean value; the results of using + * it for a multi-bit field is to determine whether *any* of its + * bits are set.

+ * + * @param holder the int data containing the bits we're interested + * in + * @return true if any of the bits are set, + * else false + */ + public boolean isSet(int holder) { + return (holder & _mask) != 0; + } + + /** + *

Returns whether all of the bits are set or not.

+ * + *

This is a stricter test than {@link #isSet(int)}, + * in that all of the bits in a multi-bit set must be set + * for this method to return true.

+ * + * @param holder the int data containing the bits we're + * interested in + * @return true if all of the bits are set, + * else false + */ + public boolean isAllSet(int holder) { + return (holder & _mask) == _mask; + } + + /** + *

Replaces the bits with new values.

+ * + * @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(int holder, int value) { + return (holder & ~_mask) | ((value << _shift_count) & _mask); + } + + /** + *

Replaces the bits with new values.

+ * + * @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(short holder, short value) { + return (short) setValue(holder, value); + } + + /** + *

Clears the bits.

+ * + * @param holder the int data containing the bits we're + * interested in + * @return the value of holder with the specified bits cleared + * (set to 0) + */ + public int clear(int holder) { + return holder & ~_mask; + } + + /** + *

Clears the bits.

+ * + * @param holder the short data containing the bits we're + * interested in + * @return the value of holder with the specified bits cleared + * (set to 0) + */ + public short clearShort(short holder) { + return (short) clear(holder); + } + + /** + *

Clears the bits.

+ * + * @param holder the byte data containing the bits we're + * interested in + * + * @return the value of holder with the specified bits cleared + * (set to 0) + */ + public byte clearByte(byte holder) { + return (byte) clear(holder); + } + + /** + *

Sets the bits.

+ * + * @param holder the int data containing the bits we're + * interested in + * @return the value of holder with the specified bits set + * to 1 + */ + public int set(int holder) { + return holder | _mask; + } + + /** + *

Sets the bits.

+ * + * @param holder the short data containing the bits we're + * interested in + * @return the value of holder with the specified bits set + * to 1 + */ + public short setShort(short holder) { + return (short) set(holder); + } + + /** + *

Sets the bits.

+ * + * @param holder the byte data containing the bits we're + * interested in + * + * @return the value of holder with the specified bits set + * to 1 + */ + public byte setByte(byte holder) { + return (byte) set(holder); + } + + /** + *

Sets a boolean BitField.

+ * + * @param holder the int data containing the bits we're + * interested in + * @param flag indicating whether to set or clear the bits + * @return the value of holder with the specified bits set or + * cleared + */ + public int setBoolean(int holder, boolean flag) { + return flag ? set(holder) : clear(holder); + } + + /** + *

Sets a boolean BitField.

+ * + * @param holder the short data containing the bits we're + * interested in + * @param flag indicating whether to set or clear the bits + * @return the value of holder with the specified bits set or + * cleared + */ + public short setShortBoolean(short holder, boolean flag) { + return flag ? setShort(holder) : clearShort(holder); + } + + /** + *

Sets a boolean BitField.

+ * + * @param holder the byte data containing the bits we're + * interested in + * @param flag indicating whether to set or clear the bits + * @return the value of holder with the specified bits set or + * cleared + */ + public byte setByteBoolean(byte holder, boolean flag) { + return flag ? setByte(holder) : clearByte(holder); + } + +} Propchange: directory/sandbox/trustin/mina-spi/core/src/main/java/org/apache/mina/common/support/lang/BitField.java ------------------------------------------------------------------------------ svn:keywords = HeadURL Id LastChangedBy LastChangedDate LastChangedRevision Added: directory/sandbox/trustin/mina-spi/core/src/main/java/org/apache/mina/common/support/lang/BooleanUtils.java URL: http://svn.apache.org/viewcvs/directory/sandbox/trustin/mina-spi/core/src/main/java/org/apache/mina/common/support/lang/BooleanUtils.java?rev=370807&view=auto ============================================================================== --- directory/sandbox/trustin/mina-spi/core/src/main/java/org/apache/mina/common/support/lang/BooleanUtils.java (added) +++ directory/sandbox/trustin/mina-spi/core/src/main/java/org/apache/mina/common/support/lang/BooleanUtils.java Fri Jan 20 05:47:50 2006 @@ -0,0 +1,928 @@ +/* + * Copyright 2002-2005 The Apache Software Foundation. + * + * Licensed 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.mina.common.support.lang; + +import org.apache.mina.common.support.lang.math.NumberUtils; + +/** + *

Operations on boolean primitives and Boolean 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.

+ * + * @author Stephen Colebourne + * @author Matthew Hawthorne + * @author Gary Gregory + * @since 2.0 + * @version $Id$ + */ +public class BooleanUtils { + + /** + *

BooleanUtils instances should NOT be constructed in standard programming. + * Instead, the class should be used as BooleanUtils.toBooleanObject(true);.

+ * + *

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

+ */ + public BooleanUtils() { + } + + // Boolean utilities + //-------------------------------------------------------------------------- + /** + *

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 + */ + public static Boolean negate(Boolean bool) { + if (bool == null) { + return null; + } + return (bool.booleanValue() ? Boolean.FALSE : Boolean.TRUE); + } + + // boolean Boolean methods + //----------------------------------------------------------------------- + /** + *

Is a Boolean value true, handling null.

+ * + *
+     *   BooleanUtils.isTrue(Boolean.TRUE)  = true
+     *   BooleanUtils.isTrue(Boolean.FALSE) = false
+     *   BooleanUtils.isTrue(null)          = false
+     * 
+ * + * @param bool the boolean to convert + * @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; + } + + /** + *

Is a Boolean value false, handling null.

+ * + *
+     *   BooleanUtils.isFalse(Boolean.TRUE)  = false
+     *   BooleanUtils.isFalse(Boolean.FALSE) = true
+     *   BooleanUtils.isFalse(null)          = false
+     * 
+ * + * @param bool the boolean to convert + * @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; + } + + /** + *

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; + } + + /** + *

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 + */ + public static boolean toBoolean(Boolean bool) { + if (bool == null) { + return 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 + */ + public static boolean toBooleanDefaultIfNull(Boolean bool, boolean valueIfNull) { + if (bool == null) { + return valueIfNull; + } + return bool.booleanValue() ? true : false; + } + + // Integer to Boolean methods + //----------------------------------------------------------------------- + /** + *

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; + } + + /** + *

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; + } + + /** + *

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 + */ + public static Boolean toBooleanObject(Integer value) { + if (value == null) { + return null; + } + 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 + * @return true or false + * @throws IllegalArgumentException if no match + */ + public static boolean toBoolean(int value, int trueValue, int falseValue) { + if (value == trueValue) { + return true; + } else if (value == falseValue) { + return false; + } + // no match + throw new IllegalArgumentException("The Integer did not match either specified value"); + } + + /** + *

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 + * @param falseValue the value to match for false, + * may be null + * @return true or false + * @throws IllegalArgumentException if no match + */ + public static boolean toBoolean(Integer value, Integer trueValue, Integer falseValue) { + if (value == null) { + if (trueValue == null) { + return true; + } else if (falseValue == null) { + return false; + } + } else if (value.equals(trueValue)) { + return true; + } else if (value.equals(falseValue)) { + return false; + } + // no match + throw new IllegalArgumentException("The Integer did not match either specified value"); + } + + /** + *

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 + * @param nullValue the value to to match for null + * @return Boolean.TRUE, Boolean.FALSE, or null + * @throws IllegalArgumentException if no match + */ + public static Boolean toBooleanObject(int value, int trueValue, int falseValue, int nullValue) { + if (value == trueValue) { + return Boolean.TRUE; + } else if (value == falseValue) { + return Boolean.FALSE; + } else if (value == nullValue) { + return null; + } + // no match + throw new IllegalArgumentException("The Integer did not match any specified value"); + } + + /** + *

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 + * @param falseValue the value to match for false, + * may be null + * @param nullValue the value to to match for null, + * may be null + * @return Boolean.TRUE, Boolean.FALSE, or null + * @throws IllegalArgumentException if no match + */ + public static Boolean toBooleanObject(Integer value, Integer trueValue, Integer falseValue, Integer nullValue) { + if (value == null) { + if (trueValue == null) { + return Boolean.TRUE; + } else if (falseValue == null) { + return Boolean.FALSE; + } else if (nullValue == null) { + return null; + } + } else if (value.equals(trueValue)) { + return Boolean.TRUE; + } else if (value.equals(falseValue)) { + return Boolean.FALSE; + } else if (value.equals(nullValue)) { + return null; + } + // no match + throw new IllegalArgumentException("The Integer did not match any specified value"); + } + + // Boolean to Integer methods + //----------------------------------------------------------------------- + /** + *

Converts a boolean to an int using the convention that + * 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; + } + + /** + *

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; + } + + /** + *

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; + } + + /** + *

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; + } + + /** + *

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 + * @param nullValue the value to return if null + * @return the appropriate value + */ + public static int toInteger(Boolean bool, int trueValue, int falseValue, int nullValue) { + if (bool == null) { + return nullValue; + } + return bool.booleanValue() ? trueValue : falseValue; + } + + /** + *

Converts a boolean to an Integer specifying the conversion values.

+ * + *
+     *   BooleanUtils.toIntegerObject(true, 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 + * @param falseValue the value to return if false, + * may be null + * @return the appropriate value + */ + public static Integer toIntegerObject(boolean bool, Integer trueValue, Integer 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 + * @param falseValue the value to return if false, + * may be null + * @param nullValue the value to return if null, + * may be null + * @return the appropriate value + */ + public static Integer toIntegerObject(Boolean bool, Integer trueValue, Integer falseValue, Integer nullValue) { + if (bool == null) { + return nullValue; + } + return bool.booleanValue() ? trueValue : falseValue; + } + + // String to Boolean methods + //----------------------------------------------------------------------- + /** + *

Converts a String to a Boolean.

+ * + *

'true', 'on' or 'yes' + * (case insensitive) will return true. + * 'false', 'off' or 'no' + * (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)) { + 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 + 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 + * @param falseString the String to match for false + * (case sensitive), may be null + * @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 + */ + public static Boolean toBooleanObject(String str, String trueString, String falseString, String nullString) { + if (str == null) { + if (trueString == null) { + return Boolean.TRUE; + } else if (falseString == null) { + return Boolean.FALSE; + } else if (nullString == null) { + return null; + } + } else if (str.equals(trueString)) { + return Boolean.TRUE; + } else if (str.equals(falseString)) { + return Boolean.FALSE; + } else if (str.equals(nullString)) { + return null; + } + // no match + throw new IllegalArgumentException("The String did not match any specified value"); + } + + // String to boolean methods + //----------------------------------------------------------------------- + /** + *

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 + */ + public static boolean toBoolean(String 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 true; + } + if (str == null) { + return false; + } + switch (str.length()) { + case 2: { + char ch0 = str.charAt(0); + char ch1 = str.charAt(1); + return + (ch0 == 'o' || ch0 == 'O') && + (ch1 == 'n' || ch1 == 'N'); + } + case 3: { + char ch = str.charAt(0); + if (ch == 'y') { + return + (str.charAt(1) == 'e' || str.charAt(1) == 'E') && + (str.charAt(2) == 's' || str.charAt(2) == 'S'); + } + if (ch == 'Y') { + return + (str.charAt(1) == 'E' || str.charAt(1) == 'e') && + (str.charAt(2) == 'S' || str.charAt(2) == 's'); + } + } + case 4: { + char ch = str.charAt(0); + if (ch == 't') { + return + (str.charAt(1) == 'r' || str.charAt(1) == 'R') && + (str.charAt(2) == 'u' || str.charAt(2) == 'U') && + (str.charAt(3) == 'e' || str.charAt(3) == 'E'); + } + if (ch == 'T') { + return + (str.charAt(1) == 'R' || str.charAt(1) == 'r') && + (str.charAt(2) == 'U' || str.charAt(2) == 'u') && + (str.charAt(3) == 'E' || str.charAt(3) == 'e'); + } + } + } + return false; + } + +// public static void main(String[] args) { +// long start = System.currentTimeMillis(); +// boolean flag = true; +// int count = 0; +// for (int i = 0; i < 100000000; i++) { +// flag = toBoolean("YES"); +// } +// long end = System.currentTimeMillis(); +// System.out.println((end - start) + " " + flag + " " + count); +// } + + /** + *

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 + * @param falseString the String to match for false + * (case sensitive), may be null + * @return the boolean value of the string + * @throws IllegalArgumentException if the String doesn't match + */ + public static boolean toBoolean(String str, String trueString, String falseString) { + if (str == null) { + if (trueString == null) { + return true; + } else if (falseString == null) { + return false; + } + } else if (str.equals(trueString)) { + return true; + } else if (str.equals(falseString)) { + return false; + } + // no match + throw new IllegalArgumentException("The String did not match either specified value"); + } + + // Boolean to String methods + //----------------------------------------------------------------------- + /** + *

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 + */ + public static String toStringTrueFalse(Boolean bool) { + return toString(bool, "true", "false", null); + } + + /** + *

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 + */ + public static String toStringOnOff(Boolean bool) { + return toString(bool, "on", "off", null); + } + + /** + *

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 + */ + public static String toStringYesNo(Boolean bool) { + return toString(bool, "yes", "no", null); + } + + /** + *

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 + * @param falseString the String to return if false, + * may be null + * @param nullString the String to return if null, + * may be null + * @return one of the three input Strings + */ + public static String toString(Boolean bool, String trueString, String falseString, String nullString) { + if (bool == null) { + return nullString; + } + return bool.booleanValue() ? trueString : falseString; + } + + // boolean to String methods + //----------------------------------------------------------------------- + /** + *

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 + */ + public static String toStringTrueFalse(boolean bool) { + return toString(bool, "true", "false"); + } + + /** + *

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 + */ + public static String toStringOnOff(boolean bool) { + return toString(bool, "on", "off"); + } + + /** + *

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 + */ + public static String toStringYesNo(boolean bool) { + return toString(bool, "yes", "no"); + } + + /** + *

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 + * @param falseString the String to return if false, + * may be null + * @return one of the two input Strings + */ + public static String toString(boolean bool, String trueString, String 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 + * @throws IllegalArgumentException if array is empty. + */ + public static boolean xor(boolean[] array) { + // Validates input + if (array == null) { + throw new IllegalArgumentException("The Array must not be null"); + } else if (array.length == 0) { + throw new IllegalArgumentException("Array is empty"); + } + + // Loops through array, comparing each item + int trueCount = 0; + for (int i = 0; i < array.length; i++) { + // If item is true, and trueCount is < 1, increments count + // Else, xor fails + if (array[i]) { + if (trueCount < 1) { + trueCount++; + } else { + return false; + } + } + } + + // Returns true if there was exactly 1 true item + return trueCount == 1; + } + + /** + *

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 + * @throws IllegalArgumentException if array is empty. + * @throws IllegalArgumentException if array contains a null + */ + public static Boolean xor(Boolean[] array) { + if (array == null) { + throw new IllegalArgumentException("The Array must not be null"); + } else if (array.length == 0) { + throw new IllegalArgumentException("Array is empty"); + } + boolean[] primitive = null; + try { + primitive = ArrayUtils.toPrimitive(array); + } catch (NullPointerException ex) { + throw new IllegalArgumentException("The array must not contain any null elements"); + } + return xor(primitive) ? Boolean.TRUE : Boolean.FALSE; + } + +} Propchange: directory/sandbox/trustin/mina-spi/core/src/main/java/org/apache/mina/common/support/lang/BooleanUtils.java ------------------------------------------------------------------------------ svn:keywords = HeadURL Id LastChangedBy LastChangedDate LastChangedRevision Added: directory/sandbox/trustin/mina-spi/core/src/main/java/org/apache/mina/common/support/lang/CharEncoding.java URL: http://svn.apache.org/viewcvs/directory/sandbox/trustin/mina-spi/core/src/main/java/org/apache/mina/common/support/lang/CharEncoding.java?rev=370807&view=auto ============================================================================== --- directory/sandbox/trustin/mina-spi/core/src/main/java/org/apache/mina/common/support/lang/CharEncoding.java (added) +++ directory/sandbox/trustin/mina-spi/core/src/main/java/org/apache/mina/common/support/lang/CharEncoding.java Fri Jan 20 05:47:50 2006 @@ -0,0 +1,152 @@ +/* + * Copyright 2001-2005 The Apache Software Foundation. + * + * Licensed 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.mina.common.support.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$ + */ +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; + } + +} Propchange: directory/sandbox/trustin/mina-spi/core/src/main/java/org/apache/mina/common/support/lang/CharEncoding.java ------------------------------------------------------------------------------ svn:keywords = HeadURL Id LastChangedBy LastChangedDate LastChangedRevision Added: directory/sandbox/trustin/mina-spi/core/src/main/java/org/apache/mina/common/support/lang/CharRange.java URL: http://svn.apache.org/viewcvs/directory/sandbox/trustin/mina-spi/core/src/main/java/org/apache/mina/common/support/lang/CharRange.java?rev=370807&view=auto ============================================================================== --- directory/sandbox/trustin/mina-spi/core/src/main/java/org/apache/mina/common/support/lang/CharRange.java (added) +++ directory/sandbox/trustin/mina-spi/core/src/main/java/org/apache/mina/common/support/lang/CharRange.java Fri Jan 20 05:47:50 2006 @@ -0,0 +1,228 @@ +/* + * Copyright 2002-2005 The Apache Software Foundation. + * + * Licensed 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.mina.common.support.lang; + +import java.io.Serializable; + +/** + *

A contiguous range of characters, optionally negated.

+ * + *

Instances are immutable.

+ * + * @author Henri Yandell + * @author Stephen Colebourne + * @author Chris Feldhacker + * @author Gary Gregory + * @since 1.0 + * @version $Id$ + */ +public final class CharRange implements Serializable { + + /** Serialization lock, Lang version 2.0. */ + private static final long serialVersionUID = 8270183163158333422L; + + /** The first character, inclusive, in the range. */ + private final char start; + /** The last character, inclusive, in the range. */ + private final char end; + /** True if the range is everything except the characters specified. */ + private final boolean negated; + + /** Cached toString. */ + private transient String iToString; + + //----------------------------------------------------------------------- + /** + *

Constructs a CharRange over a single character.

+ * + * @param ch only character in this range + */ + public CharRange(char ch) { + this(ch, ch, false); + } + + /** + *

Constructs a CharRange over a single character, + * optionally negating the range.

+ * + *

A negated range includes everything except the specified char.

+ * + * @param ch only character in this range + * @param negated true to express everything except the range + */ + public CharRange(char ch, boolean negated) { + this(ch, ch, negated); + } + + /** + *

Constructs a CharRange over a set of characters.

+ * + * @param start first character, inclusive, in this range + * @param end last character, inclusive, in this range + */ + public CharRange(char start, char end) { + this(start, end, false); + } + + /** + *

Constructs a CharRange over a set of characters, + * optionally negating the range.

+ * + *

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

+ * + *

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

+ * + * @param start first character, inclusive, in this range + * @param end last character, inclusive, in this range + * @param negated true to express everything except the range + */ + public CharRange(char start, char end, boolean negated) { + super(); + if (start > end) { + char temp = start; + start = end; + end = temp; + } + + this.start = start; + this.end = end; + this.negated = negated; + } + + // Accessors + //----------------------------------------------------------------------- + /** + *

Gets the start character for this character range.

+ * + * @return the start char (inclusive) + */ + public char getStart() { + return this.start; + } + + /** + *

Gets the end character for this character range.

+ * + * @return the end char (inclusive) + */ + public char getEnd() { + return this.end; + } + + /** + *

Is this CharRange negated.

+ * + *

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

+ * + * @return true is negated + */ + public boolean isNegated() { + return negated; + } + + // Contains + //----------------------------------------------------------------------- + /** + *

Is the character specified contained in this range.

+ * + * @param ch the character to check + * @return true if this range contains the input character + */ + public boolean contains(char ch) { + return (ch >= start && ch <= end) != negated; + } + + /** + *

Are all the characters of the passed in range contained in + * this range.

+ * + * @param range the range to check against + * @return true if this range entirely contains the input range + * @throws IllegalArgumentException if null input + */ + public boolean contains(CharRange range) { + if (range == null) { + throw new IllegalArgumentException("The Range must not be null"); + } + if (negated) { + if (range.negated) { + return start >= range.start && end <= range.end; + } else { + return range.end < start || range.start > end; + } + } else { + if (range.negated) { + return start == 0 && end == Character.MAX_VALUE; + } else { + return start <= range.start && end >= range.end; + } + } + } + + // Basics + //----------------------------------------------------------------------- + /** + *

Compares two CharRange objects, returning true if they represent + * exactly the same range of characters defined in the same way.

+ * + * @param obj the object to compare to + * @return true if equal + */ + public boolean equals(Object obj) { + if (obj == this) { + return true; + } + if (obj instanceof CharRange == false) { + return false; + } + CharRange other = (CharRange) obj; + return start == other.start && end == other.end && negated == other.negated; + } + + /** + *

Gets a hashCode compatible with the equals method.

+ * + * @return a suitable hashCode + */ + public int hashCode() { + return 83 + start + 7 * end + (negated ? 1 : 0); + } + + /** + *

Gets a string representation of the character range.

+ * + * @return string representation of this range + */ + public String toString() { + if (iToString == null) { + StringBuffer buf = new StringBuffer(4); + if (isNegated()) { + buf.append('^'); + } + buf.append(start); + if (start != end) { + buf.append('-'); + buf.append(end); + } + iToString = buf.toString(); + } + return iToString; + } + +} Propchange: directory/sandbox/trustin/mina-spi/core/src/main/java/org/apache/mina/common/support/lang/CharRange.java ------------------------------------------------------------------------------ svn:keywords = HeadURL Id LastChangedBy LastChangedDate LastChangedRevision Added: directory/sandbox/trustin/mina-spi/core/src/main/java/org/apache/mina/common/support/lang/CharSet.java URL: http://svn.apache.org/viewcvs/directory/sandbox/trustin/mina-spi/core/src/main/java/org/apache/mina/common/support/lang/CharSet.java?rev=370807&view=auto ============================================================================== --- directory/sandbox/trustin/mina-spi/core/src/main/java/org/apache/mina/common/support/lang/CharSet.java (added) +++ directory/sandbox/trustin/mina-spi/core/src/main/java/org/apache/mina/common/support/lang/CharSet.java Fri Jan 20 05:47:50 2006 @@ -0,0 +1,279 @@ +/* + * Copyright 2002-2005 The Apache Software Foundation. + * + * Licensed 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.mina.common.support.lang; + +import java.io.Serializable; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; + +/** + *

A set of characters.

+ * + *

Instances are immutable, but instances of subclasses may not be.

+ * + * @author Henri Yandell + * @author Stephen Colebourne + * @author Phil Steitz + * @author Pete Gieser + * @author Gary Gregory + * @since 1.0 + * @version $Id$ + */ +public class CharSet implements Serializable { + + /** Serialization lock, Lang version 2.0. */ + private static final long serialVersionUID = 5947847346149275958L; + + /** + * A CharSet defining no characters. + * @since 2.0 + */ + public static final CharSet EMPTY = new CharSet((String) null); + + /** + * A CharSet defining ASCII alphabetic characters "a-zA-Z". + * @since 2.0 + */ + public static final CharSet ASCII_ALPHA = new CharSet("a-zA-Z"); + + /** + * A CharSet defining ASCII alphabetic characters "a-z". + * @since 2.0 + */ + public static final CharSet ASCII_ALPHA_LOWER = new CharSet("a-z"); + + /** + * A CharSet defining ASCII alphabetic characters "A-Z". + * @since 2.0 + */ + public static final CharSet ASCII_ALPHA_UPPER = new CharSet("A-Z"); + + /** + * A CharSet defining ASCII alphabetic characters "0-9". + * @since 2.0 + */ + public static final CharSet ASCII_NUMERIC = new CharSet("0-9"); + + /** + * A Map of the common cases used in the factory. + * Subclasses can add more common patterns if desired. + * @since 2.0 + */ + protected static final Map COMMON = new HashMap(); + + static { + COMMON.put(null, EMPTY); + COMMON.put("", EMPTY); + COMMON.put("a-zA-Z", ASCII_ALPHA); + COMMON.put("A-Za-z", ASCII_ALPHA); + COMMON.put("a-z", ASCII_ALPHA_LOWER); + COMMON.put("A-Z", ASCII_ALPHA_UPPER); + COMMON.put("0-9", ASCII_NUMERIC); + } + + /** The set of CharRange objects. */ + private Set set = new HashSet(); + + //----------------------------------------------------------------------- + /** + *

Factory method to create a new CharSet using a special syntax.

+ * + *
    + *
  • null or empty string ("") + * - set containing no characters
  • + *
  • Single character, such as "a" + * - set containing just that character
  • + *
  • Multi character, such as "a-e" + * - set containing characters from one character to the other
  • + *
  • Negated, such as "^a" or "^a-e" + * - set containing all characters except those defined
  • + *
  • Combinations, such as "abe-g" + * - set containing all the characters from the individual sets
  • + *
+ * + *

The matching order is:

+ *
    + *
  1. Negated multi character range, such as "^a-e" + *
  2. Ordinary multi character range, such as "a-e" + *
  3. Negated single character, such as "^a" + *
  4. Ordinary single character, such as "a" + *
+ *

Matching works left to right. Once a match is found the + * search starts again from the next character.

+ * + *

If the same range is defined twice using the same syntax, only + * one range will be kept. + * Thus, "a-ca-c" creates only one range of "a-c".

+ * + *

If the start and end of a range are in the wrong order, + * they are reversed. Thus "a-e" is the same as "e-a". + * As a result, "a-ee-a" would create only one range, + * as the "a-e" and "e-a" are the same.

+ * + *

The set of characters represented is the union of the specified ranges.

+ * + *

All CharSet objects returned by this method will be immutable.

+ * + * @param setStr the String describing the set, may be null + * @return a CharSet instance + * @since 2.0 + */ + public static CharSet getInstance(String setStr) { + Object set = COMMON.get(setStr); + if (set != null) { + return (CharSet) set; + } + return new CharSet(setStr); + } + + //----------------------------------------------------------------------- + /** + *

Constructs a new CharSet using the set syntax.

+ * + * @param setStr the String describing the set, may be null + * @since 2.0 + */ + protected CharSet(String setStr) { + super(); + add(setStr); + } + + /** + *

Constructs a new CharSet using the set syntax. + * Each string is merged in with the set.

+ * + * @param set Strings to merge into the initial set + * @throws NullPointerException if set is null + */ + protected CharSet(String[] set) { + super(); + int sz = set.length; + for (int i = 0; i < sz; i++) { + add(set[i]); + } + } + + //----------------------------------------------------------------------- + /** + *

Add a set definition string to the CharSet.

+ * + * @param str set definition string + */ + protected void add(String str) { + if (str == null) { + return; + } + + int len = str.length(); + int pos = 0; + while (pos < len) { + 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)); + pos += 4; + } else if (remainder >= 3 && str.charAt(pos + 1) == '-') { + // range + set.add(new CharRange(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)); + pos += 2; + } else { + // char + set.add(new CharRange(str.charAt(pos))); + pos += 1; + } + } + } + + //----------------------------------------------------------------------- + /** + *

Gets the internal set as an array of CharRange objects.

+ * + * @return an array of immutable CharRange objects + * @since 2.0 + */ + public CharRange[] getCharRanges() { + return (CharRange[]) set.toArray(new CharRange[set.size()]); + } + + //----------------------------------------------------------------------- + /** + *

Does the CharSet contain the specified + * character ch.

+ * + * @param ch the character to check for + * @return true if the set contains the characters + */ + public boolean contains(char ch) { + for (Iterator it = set.iterator(); it.hasNext();) { + CharRange range = (CharRange) it.next(); + if (range.contains(ch)) { + return true; + } + } + return false; + } + + // Basics + //----------------------------------------------------------------------- + /** + *

Compares two CharSet objects, returning true if they represent + * exactly the same set of characters defined in the same way.

+ * + *

The two sets abc and a-c are not + * equal according to this method.

+ * + * @param obj the object to compare to + * @return true if equal + * @since 2.0 + */ + public boolean equals(Object obj) { + if (obj == this) { + return true; + } + if (obj instanceof CharSet == false) { + return false; + } + CharSet other = (CharSet) obj; + return set.equals(other.set); + } + + /** + *

Gets a hashCode compatible with the equals method.

+ * + * @return a suitable hashCode + * @since 2.0 + */ + public int hashCode() { + return 89 + set.hashCode(); + } + + /** + *

Gets a string representation of the set.

+ * + * @return string representation of the set + */ + public String toString() { + return set.toString(); + } + +} Propchange: directory/sandbox/trustin/mina-spi/core/src/main/java/org/apache/mina/common/support/lang/CharSet.java ------------------------------------------------------------------------------ svn:keywords = HeadURL Id LastChangedBy LastChangedDate LastChangedRevision Added: directory/sandbox/trustin/mina-spi/core/src/main/java/org/apache/mina/common/support/lang/CharSetUtils.java URL: http://svn.apache.org/viewcvs/directory/sandbox/trustin/mina-spi/core/src/main/java/org/apache/mina/common/support/lang/CharSetUtils.java?rev=370807&view=auto ============================================================================== --- directory/sandbox/trustin/mina-spi/core/src/main/java/org/apache/mina/common/support/lang/CharSetUtils.java (added) +++ directory/sandbox/trustin/mina-spi/core/src/main/java/org/apache/mina/common/support/lang/CharSetUtils.java Fri Jan 20 05:47:50 2006 @@ -0,0 +1,389 @@ +/* + * Copyright 2002-2005 The Apache Software Foundation. + * + * Licensed 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.mina.common.support.lang; + +/** + *

Operations on CharSets.

+ * + *

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

+ * + * @see CharSet + * @author Henri Yandell + * @author Stephen Colebourne + * @author Phil Steitz + * @author Gary Gregory + * @since 1.0 + * @version $Id$ + */ +public class CharSetUtils { + + /** + *

CharSetUtils instances should NOT be constructed in standard programming. + * Instead, the class should be used as CharSetUtils.evaluateSet(null);.

+ * + *

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

+ */ + public CharSetUtils() { + } + + // Factory + //----------------------------------------------------------------------- + /** + *

Creates a CharSet instance which allows a certain amount of + * set logic to be performed.

+ *

The syntax is:

+ *
    + *
  • "aeio" which implies 'a','e',..
  • + *
  • "^e" implies not e.
  • + *
  • "ej-m" implies e,j->m. e,j,k,l,m.
  • + *
+ * + *
+     * CharSetUtils.evaluateSet(null)    = null
+     * CharSetUtils.evaluateSet([])      = CharSet matching nothing
+     * CharSetUtils.evaluateSet(["a-e"]) = CharSet matching a,b,c,d,e
+     * 
+ * + * @param set the set, may be null + * @return a CharSet instance, null if null input + * @deprecated Use {@link CharSet#getInstance(String)}. + * Method will be removed in Commons Lang 3.0. + */ + public static CharSet evaluateSet(String[] set) { + if (set == null) { + return null; + } + return new CharSet(set); + } + + // Squeeze + //----------------------------------------------------------------------- + /** + *

Squeezes any repetitions of a character that is mentioned in the + * supplied set.

+ * + *
+     * CharSetUtils.squeeze(null, *)        = null
+     * CharSetUtils.squeeze("", *)          = ""
+     * CharSetUtils.squeeze(*, null)        = *
+     * CharSetUtils.squeeze(*, "")          = *
+     * CharSetUtils.squeeze("hello", "k-p") = "helo"
+     * CharSetUtils.squeeze("hello", "a-e") = "hello"
+     * 
+ * + * @see #evaluateSet(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 (StringUtils.isEmpty(str) || StringUtils.isEmpty(set)) { + return str; + } + String[] strs = new String[1]; + strs[0] = set; + return squeeze(str, strs); + } + + /** + *

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. + * @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 (StringUtils.isEmpty(str) || ArrayUtils.isEmpty(set)) { + return str; + } + CharSet chars = evaluateSet(set); + StringBuffer buffer = new StringBuffer(str.length()); + char[] chrs = str.toCharArray(); + int sz = chrs.length; + char lastChar = ' '; + char ch = ' '; + for (int i = 0; i < sz; i++) { + ch = chrs[i]; + if (chars.contains(ch)) { + if ((ch == lastChar) && (i != 0)) { + continue; + } + } + buffer.append(ch); + lastChar = ch; + } + return buffer.toString(); + } + + // Count + //----------------------------------------------------------------------- + /** + *

Takes an argument in set-syntax, see evaluateSet, + * and returns the number of characters present in the specified string.

+ * + *
+     * CharSetUtils.count(null, *)        = 0
+     * CharSetUtils.count("", *)          = 0
+     * CharSetUtils.count(*, null)        = 0
+     * CharSetUtils.count(*, "")          = 0
+     * CharSetUtils.count("hello", "k-p") = 3
+     * CharSetUtils.count("hello", "a-e") = 1
+     * 
+ * + * @see #evaluateSet(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 (StringUtils.isEmpty(str) || StringUtils.isEmpty(set)) { + return 0; + } + String[] strs = new String[1]; + strs[0] = set; + return count(str, strs); + } + + /** + *

Takes an argument in set-syntax, see evaluateSet, + * and returns the number of characters present in the specified string.

+ * + *

An example would be:

+ *
    + *
  • count("hello", {"c-f", "o"}) returns 2.
  • + *
+ * + * @see #evaluateSet(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 (StringUtils.isEmpty(str) || ArrayUtils.isEmpty(set)) { + return 0; + } + CharSet chars = evaluateSet(set); + int count = 0; + char[] chrs = str.toCharArray(); + int sz = chrs.length; + for(int i=0; iTakes an argument in set-syntax, see evaluateSet, + * and keeps any of characters present in the specified string.

+ * + *
+     * CharSetUtils.keep(null, *)        = null
+     * CharSetUtils.keep("", *)          = ""
+     * CharSetUtils.keep(*, null)        = ""
+     * CharSetUtils.keep(*, "")          = ""
+     * CharSetUtils.keep("hello", "hl")  = "hll"
+     * CharSetUtils.keep("hello", "le")  = "ell"
+     * 
+ * + * @see #evaluateSet(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 + * @since 2.0 + */ + public static String keep(String str, String set) { + if (str == null) { + return null; + } + if (str.length() == 0 || StringUtils.isEmpty(set)) { + return ""; + } + String[] strs = new String[1]; + strs[0] = set; + return keep(str, strs); + } + + /** + *

Takes an argument in set-syntax, see evaluateSet, + * and keeps any of characters present in the specified string.

+ * + *

An example would be:

+ *
    + *
  • keep("hello", {"c-f", "o"}) + * returns "eo"
  • + *
+ * + * @see #evaluateSet(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 + * @since 2.0 + */ + public static String keep(String str, String[] set) { + if (str == null) { + return null; + } + if (str.length() == 0 || ArrayUtils.isEmpty(set)) { + return ""; + } + return modify(str, set, true); + } + + // Delete + //----------------------------------------------------------------------- + /** + *

Takes an argument in set-syntax, see evaluateSet, + * and deletes any of characters present in the specified string.

+ * + *
+     * CharSetUtils.delete(null, *)        = null
+     * CharSetUtils.delete("", *)          = ""
+     * CharSetUtils.delete(*, null)        = *
+     * CharSetUtils.delete(*, "")          = *
+     * CharSetUtils.delete("hello", "hl")  = "eo"
+     * CharSetUtils.delete("hello", "le")  = "ho"
+     * 
+ * + * @see #evaluateSet(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 (StringUtils.isEmpty(str) || StringUtils.isEmpty(set)) { + return str; + } + String[] strs = new String[1]; + strs[0] = set; + return delete(str, strs); + } + + /** + *

Takes an argument in set-syntax, see evaluateSet, + * and deletes any of characters present in the specified string.

+ * + *

An example would be:

+ *
    + *
  • delete("hello", {"c-f", "o"}) returns + * "hll"
  • + *
+ * + * @see #evaluateSet(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 (StringUtils.isEmpty(str) || ArrayUtils.isEmpty(set)) { + return str; + } + return modify(str, set, false); + } + + //----------------------------------------------------------------------- + /** + * 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()); + char[] chrs = str.toCharArray(); + int sz = chrs.length; + for(int i=0; iTranslate characters in a String. + * This is a multi character search and replace routine.

+ * + *

An example is:

+ *
    + *
  • translate("hello", "ho", "jy") + * => jelly
  • + *
+ * + *

If the length of characters to search for is greater than the + * length of characters to replace, then the last character is + * used.

+ * + *
+     * CharSetUtils.translate(null, *, *) = null
+     * 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 ("") + * @return translated String, null if null string input + * @throws NullPointerException if searchChars or replaceChars + * is null + * @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 (StringUtils.isEmpty(str)) { + return str; + } + StringBuffer buffer = new StringBuffer(str.length()); + char[] chrs = str.toCharArray(); + char[] withChrs = replaceChars.toCharArray(); + int sz = chrs.length; + int withMax = replaceChars.length() - 1; + for(int i=0; i withMax) { + idx = withMax; + } + buffer.append(withChrs[idx]); + } else { + buffer.append(chrs[i]); + } + } + return buffer.toString(); + } + +} Propchange: directory/sandbox/trustin/mina-spi/core/src/main/java/org/apache/mina/common/support/lang/CharSetUtils.java ------------------------------------------------------------------------------ svn:keywords = HeadURL Id LastChangedBy LastChangedDate LastChangedRevision