Author: shawkins
Date: 2009-09-29 10:23:43 -0400 (Tue, 29 Sep 2009)
New Revision: 1490
Removed:
trunk/test-integration/db/src/main/java/org/teiid/test/util/ArgCheck.java
trunk/test-integration/db/src/main/java/org/teiid/test/util/ChecksumUtil.java
trunk/test-integration/db/src/main/java/org/teiid/test/util/FileUtils.java
trunk/test-integration/db/src/main/java/org/teiid/test/util/StringUtil.java
Modified:
trunk/test-integration/db/src/main/java/org/teiid/test/framework/datasource/DataSourceMgr.java
Log:
removing duplicate classes
Modified:
trunk/test-integration/db/src/main/java/org/teiid/test/framework/datasource/DataSourceMgr.java
===================================================================
---
trunk/test-integration/db/src/main/java/org/teiid/test/framework/datasource/DataSourceMgr.java 2009-09-29
13:52:23 UTC (rev 1489)
+++
trunk/test-integration/db/src/main/java/org/teiid/test/framework/datasource/DataSourceMgr.java 2009-09-29
14:23:43 UTC (rev 1490)
@@ -22,10 +22,10 @@
import org.teiid.test.framework.ConfigPropertyNames;
import org.teiid.test.framework.exception.QueryTestFailedException;
import org.teiid.test.framework.exception.TransactionRuntimeException;
-import org.teiid.test.util.StringUtil;
import com.metamatrix.common.xml.XMLReaderWriter;
import com.metamatrix.common.xml.XMLReaderWriterImpl;
+import com.metamatrix.core.util.StringUtil;
/**
* The DataSourceMgr is responsible for loading and managing datasources defined by the
datasource
Deleted: trunk/test-integration/db/src/main/java/org/teiid/test/util/ArgCheck.java
===================================================================
--- trunk/test-integration/db/src/main/java/org/teiid/test/util/ArgCheck.java 2009-09-29
13:52:23 UTC (rev 1489)
+++ trunk/test-integration/db/src/main/java/org/teiid/test/util/ArgCheck.java 2009-09-29
14:23:43 UTC (rev 1490)
@@ -1,534 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership. Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
-package org.teiid.test.util;
-
-import java.util.Collection;
-import java.util.Map;
-
-/**
- * This class contains a set of static utility methods for checking method arguments.
- * It contains many of the common checks that are done, such as checking that an
- * Object is non-null, checking the range of a value, etc. All of these methods
- * throw {@link #java.lang.IllegalArgumentException}.
- */
-public class ArgCheck {
-
- /**
- * Can't construct - utility class
- */
- private ArgCheck() {
- }
-
- /**
- * Check that the boolean condition is true; throw an
- * IllegalArgumentException if not.
- * @param condition The boolean condition to check
- * @param message Exception message if check fails
- * @throws IllegalArgumentException if condition is false
- */
- public static final void isTrue(boolean condition, String message){
- if(!condition) {
- throw new IllegalArgumentException(message);
- }
- }
-
- // ########################## int METHODS ###################################
-
- /**
- * Check that the value is non-negative (>=0).
- * @param value Value
- * @throws IllegalArgumentException If value is negative (<0)
- */
- public static final void isNonNegative(int value) {
- isNonNegative(value,null);
- }
-
- /**
- * Check that the value is non-negative (>=0).
- * @param value Value
- * @param message Exception message if check fails
- * @throws IllegalArgumentException If value is negative (<0)
- */
- public static final void isNonNegative(int value, String message) {
- if(value < 0) {
- final String msg = message != null ?
- message :
- "ArgCheck.isNonNegativeInt"; //$NON-NLS-1$
- throw new IllegalArgumentException(msg);
- }
- }
-
- /**
- * Check that the value is non-positive (<=0).
- * @param value Value
- * @throws IllegalArgumentException If value is positive (>0)
- */
- public static final void isNonPositive(int value) {
- isNonPositive(value,null);
- }
-
- /**
- * Check that the value is non-positive (<=0).
- * @param value Value
- * @param message Exception message if check fails
- * @throws IllegalArgumentException If value is positive (>0)
- */
- public static final void isNonPositive(int value, String message) {
- if(value > 0) {
- final String msg = message != null ?
- message :
- "ArgCheck.isNonPositiveInt"; //$NON-NLS-1$
- throw new IllegalArgumentException(msg);
- }
- }
-
- /**
- * Check that the value is negative (<0).
- * @param value Value
- * @throws IllegalArgumentException If value is non-negative (>=0)
- */
- public static final void isNegative(int value) {
- isNegative(value,null);
- }
-
- /**
- * Check that the value is negative (<0).
- * @param value Value
- * @param message Exception message if check fails
- * @throws IllegalArgumentException If value is non-negative (>=0)
- */
- public static final void isNegative(int value, String message) {
- if(value >= 0) {
- final String msg = message != null ?
- message :
- "ArgCheck.isNegativeInt"; //$NON-NLS-1$
- throw new IllegalArgumentException(msg);
- }
- }
-
- /**
- * Check that the value is positive (>0).
- * @param value Value
- * @throws IllegalArgumentException If value is non-positive (<=0)
- */
- public static final void isPositive(int value) {
- isPositive(value,null);
- }
-
- /**
- * Check that the value is positive (>0).
- * @param value Value
- * @param message Exception message if check fails
- * @throws IllegalArgumentException If value is non-positive (<=0)
- */
- public static final void isPositive(int value, String message) {
- if(value <= 0) {
- final String msg = message != null ?
- message :
- "ArgCheck.isPositiveInt"; //$NON-NLS-1$
- throw new IllegalArgumentException(msg);
- }
- }
-
- // ########################## long METHODS ###################################
-
- /**
- * Check that the value is non-negative (>=0).
- * @param value Value
- * @throws IllegalArgumentException If value is negative (<0)
- */
- public static final void isNonNegative(long value) {
- isNonNegative(value,null);
- }
-
- /**
- * Check that the value is non-negative (>=0).
- * @param value Value
- * @param message Exception message if check fails
- * @throws IllegalArgumentException If value is negative (<0)
- */
- public static final void isNonNegative(long value, String message) {
- if(value < 0) {
- final String msg = message != null ?
- message :
- "ArgCheck.isNonNegativeInt"; //$NON-NLS-1$
- throw new IllegalArgumentException(msg);
- }
- }
-
- /**
- * Check that the value is non-positive (<=0).
- * @param value Value
- * @throws IllegalArgumentException If value is positive (>0)
- */
- public static final void isNonPositive(long value) {
- isNonPositive(value,null);
- }
-
- /**
- * Check that the value is non-positive (<=0).
- * @param value Value
- * @param message Exception message if check fails
- * @throws IllegalArgumentException If value is positive (>0)
- */
- public static final void isNonPositive(long value, String message) {
- if(value > 0) {
- final String msg = message != null ?
- message :
- "ArgCheck.isNonPositiveInt"; //$NON-NLS-1$
- throw new IllegalArgumentException(msg);
- }
- }
-
- /**
- * Check that the value is negative (<0).
- * @param value Value
- * @throws IllegalArgumentException If value is non-negative (>=0)
- */
- public static final void isNegative(long value) {
- isNegative(value,null);
- }
-
- /**
- * Check that the value is negative (<0).
- * @param value Value
- * @param message Exception message if check fails
- * @throws IllegalArgumentException If value is non-negative (>=0)
- */
- public static final void isNegative(long value, String message) {
- if(value >= 0) {
- final String msg = message != null ?
- message :
- "ArgCheck.isNegativeInt"; //$NON-NLS-1$
- throw new IllegalArgumentException(msg);
- }
- }
-
- /**
- * Check that the value is positive (>0).
- * @param value Value
- * @throws IllegalArgumentException If value is non-positive (<=0)
- */
- public static final void isPositive(long value) {
- isPositive(value,null);
- }
-
- /**
- * Check that the value is positive (>0).
- * @param value Value
- * @param message Exception message if check fails
- * @throws IllegalArgumentException If value is non-positive (<=0)
- */
- public static final void isPositive(long value, String message) {
- if(value <= 0) {
- final String msg = message != null ?
- message :
- "ArgCheck.isPositiveInt"; //$NON-NLS-1$
- throw new IllegalArgumentException(msg);
- }
- }
-
- // ########################## String METHODS ###################################
-
- /**
- * Check that the string is non-null and has length > 0
- * @param value Value
- * @throws IllegalArgumentException If value is null or length == 0
- */
- public static final void isNotZeroLength(String value) {
- isNotZeroLength(value,null);
- }
-
- /**
- * Check that the string is non-null and has length > 0
- * @param value Value
- * @param message Exception message if check fails
- * @throws IllegalArgumentException If value is null or length == 0
- */
- public static final void isNotZeroLength(String value, String message) {
- isNotNull(value);
- if(value.length() <= 0) {
- final String msg = message != null ?
- message :
- "ArgCheck.isStringNonZeroLength"; //$NON-NLS-1$
- throw new IllegalArgumentException(msg);
- }
- }
-
- // ########################## Object METHODS ###################################
-
- /**
- * Check that the object is non-null
- * @param value Value
- * @throws IllegalArgumentException If value is null
- */
- public static final void isNotNull(Object value) {
- isNotNull(value,null);
- }
-
- /**
- * Check that the object is non-null
- * @param value Value
- * @param message Exception message if check fails
- * @throws IllegalArgumentException If value is null
- */
- public static final void isNotNull(Object value, String message) {
- if(value == null) {
- final String msg = message != null ?
- message :
- "ArgCheck.isNonNull"; //$NON-NLS-1$
- throw new IllegalArgumentException(msg);
- }
- }
-
- /**
- * Check that the object is null
- * @param value Value
- * @throws IllegalArgumentException If value is non-null
- */
- public static final void isNull(Object value) {
- isNull(value,null);
- }
-
- /**
- * Check that the object is null
- * @param value Value
- * @param message Exception message if check fails
- * @throws IllegalArgumentException If value is non-null
- */
- public static final void isNull(Object value, String message) {
- if(value != null) {
- final String msg = message != null ?
- message :
- "ArgCheck.isNull"; //$NON-NLS-1$
- throw new IllegalArgumentException(msg);
- }
- }
-
- /**
- * Check that the object is an instance of the specified Class
- * @param theClass Class
- * @param value Value
- * @throws IllegalArgumentException If value is null
- */
- public static final void isInstanceOf(Class theClass, Object value) {
- isInstanceOf(theClass,value,null);
- }
-
- /**
- * Check that the object is an instance of the specified Class
- * @param theClass Class
- * @param value Value
- * @param message Exception message if check fails
- * @throws IllegalArgumentException If value is null
- */
- public static final void isInstanceOf(Class theClass, Object value, String message) {
- isNotNull(value);
- if( ! theClass.isInstance(value) ) {
- final String msg = message != null ?
- message :
- "ArgCheck.isInstanceOf "; //$NON-NLS-1$
- throw new IllegalArgumentException(msg);
- }
- }
-
- // ########################## COLLECTION METHODS ###################################
-
- /**
- * Check that the collection is not empty
- * @param collection Collection
- * @throws IllegalArgumentException If collection is null or empty
- */
- public static final void isNotEmpty(Collection collection) {
- isNotEmpty(collection,null);
- }
-
- /**
- * Check that the collection is not empty
- * @param collection Collection
- * @param message Exception message if check fails
- * @throws IllegalArgumentException If collection is null or empty
- */
- public static final void isNotEmpty(Collection collection, String message) {
- isNotNull(collection);
- if(collection.isEmpty()) {
- final String msg = message != null ?
- message :
- "ArgCheck.isCollectionNotEmpty"; //$NON-NLS-1$
- throw new IllegalArgumentException(msg);
- }
- }
-
- /**
- * Check that the map is not empty
- * @param map Map
- * @throws IllegalArgumentException If map is null or empty
- */
- public static final void isNotEmpty(Map map) {
- isNotEmpty(map,null);
- }
-
- /**
- * Check that the map is not empty
- * @param map Map
- * @param message Exception message if check fails
- * @throws IllegalArgumentException If map is null or empty
- */
- public static final void isNotEmpty(Map map, String message) {
- isNotNull(map);
- if(map.isEmpty()) {
- final String msg = message != null ?
- message :
- "ArgCheck.isMapNotEmpty"; //$NON-NLS-1$
- throw new IllegalArgumentException(msg);
- }
- }
-
- /**
- * Check that the array is not empty
- * @param array Array
- * @throws IllegalArgumentException If array is null or empty
- * @since 3.1
- */
- public static final void isNotEmpty(Object[] array) {
- isNotEmpty(array,null);
- }
-
- /**
- * Check that the array is not empty
- * @param array Array
- * @param message Exception message if check fails
- * @throws IllegalArgumentException If array is null or empty
- * @since 3.1
- */
- public static final void isNotEmpty(Object[] array, String message) {
- isNotNull(array);
- if(array.length == 0) {
- final String msg = message != null ?
- message :
- "ArgCheck.isArrayNotEmpty"; //$NON-NLS-1$
- throw new IllegalArgumentException(msg);
- }
- }
-
- /**
- * Check that the string is not empty
- * @param string String
- * @throws IllegalArgumentException If string is null or empty
- * @since 3.1
- */
- public static final void isNotEmpty(String string) {
- isNotZeroLength(string,null);
- }
-
- /**
- * Check that the string is not empty
- * @param string String
- * @param message Exception message if check fails
- * @throws IllegalArgumentException If string is null or empty
- * @since 3.1
- */
- public static final void isNotEmpty(String string, String message) {
- isNotZeroLength(string,message);
- }
-
- /**
- * Asserts that the specified first object is not the same as (==) the specified
second object.
- * @param firstObject The first object to assert as not the same as the second
object.
- * @param firstName The name that will be used within the exception message for
the first object, should an exception be
- * thrown; if null and <code>firstObject</code> is
not null, <code>firstObject.toString()</code> will be
- * used.
- * @param secondObject The second object to assert as not the same as the first
object.
- * @param secondName The name that will be used within the exception message for
the second object, should an exception be
- * thrown; if null and <code>secondObject</code> is
not null, <code>secondObject.toString()</code> will
- * be used.
- * @throws IllegalArgumentException If the specified objects are the same.
- * @since 3.1
- */
- public static void isNotSame(final Object firstObject, String firstName, final Object
secondObject, String secondName) {
- if (firstObject == secondObject) {
- if (firstName == null && firstObject != null) {
- firstName = firstObject.toString();
- }
- if (secondName == null && secondObject != null) {
- secondName = secondObject.toString();
- }
- throw new IllegalArgumentException("ArgCheck.isNotSame");
//$NON-NLS-1$
- }
- }
-
- /**
- * Check that the collection contains the value
- * @param collection Collection to check
- * @param value Value to check for, may be null
- * @throws IllegalArgumentException If collection is null or doesn't contain
value
- */
- public static final void contains(Collection collection, Object value) {
- contains(collection, value, null);
- }
-
- /**
- * Check that the collection contains the value
- * @param collection Collection to check
- * @param value Value to check for, may be null
- * @param message Exception message if check fails
- * @throws IllegalArgumentException If collection is null or doesn't contain
value
- */
- public static final void contains(Collection collection, Object value, String
message) {
- isNotNull(collection);
- if(! collection.contains(value)) {
- final String msg = message != null ?
- message :
- "ArgCheck.contains"; //$NON-NLS-1$
- throw new IllegalArgumentException(msg);
- }
- }
-
- /**
- * Check that the map contains the key
- * @param map Map to check
- * @param key Key to check for, may be null
- * @throws IllegalArgumentException If map is null or doesn't contain key
- */
- public static final void containsKey(Map map, Object key) {
- containsKey(map, key, null);
- }
-
- /**
- * Check that the map contains the key
- * @param map Map to check
- * @param key Key to check for, may be null
- * @param message Exception message if check fails
- * @throws IllegalArgumentException If map is null or doesn't contain key
- */
- public static final void containsKey(Map map, Object key, String message) {
- isNotNull(map);
- if(! map.containsKey(key)) {
- final String msg = message != null ?
- message :
- "ArgCheck.containsKey"; //$NON-NLS-1$
- throw new IllegalArgumentException(msg);
- }
- }
-
-}
Deleted: trunk/test-integration/db/src/main/java/org/teiid/test/util/ChecksumUtil.java
===================================================================
---
trunk/test-integration/db/src/main/java/org/teiid/test/util/ChecksumUtil.java 2009-09-29
13:52:23 UTC (rev 1489)
+++
trunk/test-integration/db/src/main/java/org/teiid/test/util/ChecksumUtil.java 2009-09-29
14:23:43 UTC (rev 1490)
@@ -1,97 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership. Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
-package org.teiid.test.util;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.zip.CRC32;
-import java.util.zip.Checksum;
-
-/**
- * This utility class provides mechanisms for computing the checksum.
- */
-public class ChecksumUtil {
-
- protected static final int BUFFER_SIZE = 1024;
-
- /**
- * Compute and return the checksum (using the default CRC-32 algorithm)
- * of the contents on the specified stream.
- * This method closes the stream upon completion.
- * @param stream the stream containing the contents for which
- * the checksum is to be computed; may not be null
- * @return the Checksum for the contents
- * @throws AssertionError if <code>stream</code> is null
- * @throws IOException if there is an error reading the stream
- */
- public static Checksum computeChecksum( InputStream stream ) throws IOException {
- Checksum checksum = new CRC32();
- computeChecksum(stream,checksum);
- return checksum;
- }
-
- /**
- * Compute the checksum of the contents on the specified stream
- * using the supplied Checksum algorithm, and modify that
- * Checksum instance with the checksum value.
- * This method closes the stream upon completion.
- * @param stream the stream containing the contents for which
- * the checksum is to be computed; may not be null
- * @param algorithm the checksum algorithm to be used.
- * @return the number of bytes from <code>stream</code>
- * that were processed
- * @throws AssertionError if <code>stream</code> or
- * <code>algorithm</code> is null
- * @throws IOException if there is an error reading the stream
- */
- public static long computeChecksum( InputStream stream, Checksum algorithm ) throws
IOException {
- byte[] buffer = new byte[BUFFER_SIZE];
- int n = 0;
- long sizeInBytes = 0;
-
- // Compute the checksum ...
- IOException ioe = null;
- try {
- while ((n = stream.read(buffer)) > -1){
- algorithm.update(buffer, 0, n);
- sizeInBytes += n;
- }
- } catch ( IOException e ) {
- ioe = e;
- } finally {
- try {
- stream.close();
- } catch ( IOException e ) {
- //Throw this only if there was no IOException from processing above
- if ( ioe == null ) {
- ioe = e;
- }
- }
- }
- if ( ioe != null ) {
- throw ioe;
- }
- return sizeInBytes;
- }
-
-}
Deleted: trunk/test-integration/db/src/main/java/org/teiid/test/util/FileUtils.java
===================================================================
--- trunk/test-integration/db/src/main/java/org/teiid/test/util/FileUtils.java 2009-09-29
13:52:23 UTC (rev 1489)
+++ trunk/test-integration/db/src/main/java/org/teiid/test/util/FileUtils.java 2009-09-29
14:23:43 UTC (rev 1490)
@@ -1,871 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership. Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
-package org.teiid.test.util;
-
-import java.io.BufferedInputStream;
-import java.io.BufferedOutputStream;
-import java.io.ByteArrayInputStream;
-import java.io.File;
-import java.io.FileFilter;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.util.ArrayList;
-import java.util.List;
-
-
-public final class FileUtils {
-
- public interface Constants {
- char CURRENT_FOLDER_SYMBOL_CHAR = '.';
- char DRIVE_SEPARATOR_CHAR = ':';
- char FILE_EXTENSION_SEPARATOR_CHAR = '.';
- char FILE_NAME_WILDCARD_CHAR = '*';
-
- String CURRENT_FOLDER_SYMBOL = String.valueOf(CURRENT_FOLDER_SYMBOL_CHAR);
- String DRIVE_SEPARATOR = String.valueOf(DRIVE_SEPARATOR_CHAR);
- String FILE_EXTENSION_SEPARATOR = String.valueOf(FILE_EXTENSION_SEPARATOR_CHAR);
- String FILE_NAME_WILDCARD = String.valueOf(FILE_NAME_WILDCARD_CHAR);
- String PARENT_FOLDER_SYMBOL = ".."; //$NON-NLS-1$
- }
-
- public static final char SEPARATOR = '/';
-
- public static int DEFAULT_BUFFER_SIZE = 2048;
- public static String TEMP_DIRECTORY;
- public static String LINE_SEPARATOR = System.getProperty("line.separator");
//$NON-NLS-1$
- public static char[] LINE_SEPARATOR_CHARS = LINE_SEPARATOR.toCharArray();
-
- public final static String JAVA_IO_TEMP_DIR="java.io.tmpdir";//$NON-NLS-1$
- public final static char[] SUFFIX_class = ".class".toCharArray();
//$NON-NLS-1$
- public final static char[] SUFFIX_CLASS = ".CLASS".toCharArray();
//$NON-NLS-1$
- public final static char[] SUFFIX_java = ".java".toCharArray();
//$NON-NLS-1$
- public final static char[] SUFFIX_JAVA = ".JAVA".toCharArray();
//$NON-NLS-1$
- public final static char[] SUFFIX_jar = ".jar".toCharArray();
//$NON-NLS-1$
- public final static char[] SUFFIX_JAR = ".JAR".toCharArray();
//$NON-NLS-1$
- public final static char[] SUFFIX_zip = ".zip".toCharArray();
//$NON-NLS-1$
- public final static char[] SUFFIX_ZIP = ".ZIP".toCharArray();
//$NON-NLS-1$
-
-
- private static final String TEMP_FILE = "delete.me"; //$NON-NLS-1$
- private static final String TEMP_FILE_RENAMED = "delete.me.old";
//$NON-NLS-1$
-
-
-
- static {
- String tempDirPath = System.getProperty(JAVA_IO_TEMP_DIR);
- TEMP_DIRECTORY = (tempDirPath.endsWith(File.separator) ? tempDirPath :
tempDirPath + File.separator);
- }
-
- private FileUtils() {}
-
- /**<p>
- * Convert the specified file name to end with the specified extension if it
doesn't already end with an extension.
- * </p>
- * @param name
- * The file name.
- * @param extension
- * The extension to append to the file name.
- * @return The file name with an extension.
- * @since 4.0
- */
- public static String toFileNameWithExtension(final String name,
- final String extension) {
- return toFileNameWithExtension(name, extension, false);
- }
-
- /**<p>
- * Convert the specified file name to end with the specified extension if it
doesn't already end with an extension. If force
- * is true, the specified extension will be appended to the name if the name
doesn't end with that particular extension.
- * </p>
- * @param name
- * The file name.
- * @param extension
- * The extension to append to the file name.
- * @param force
- * Indicates whether to force the specified extension as the extension
of the file name.
- * @return The file name with an extension.
- * @since 4.0
- */
- public static String toFileNameWithExtension(final String name,
- final String extension,
- final boolean force) {
- if (name == null) {
- final String msg =
"FileUtils.The_name_of_the_file_may_not_be_null"; //$NON-NLS-1$
- throw new IllegalArgumentException(msg);
- }
- if (extension == null) {
- final String msg = "FileUtils.The_file_extension_may_not_be_null";
//$NON-NLS-1$
- throw new IllegalArgumentException(msg);
- }
- if (name.endsWith(extension)) {
- return name;
- }
- if (!force && name.indexOf(Constants.FILE_EXTENSION_SEPARATOR_CHAR)
>= 0) {
- return name;
- }
- final int nameLen = name.length() - 1;
- final int extLen = extension.length();
- final boolean nameEndsWithExtChr = (nameLen >= 0 &&
name.charAt(nameLen) == Constants.FILE_EXTENSION_SEPARATOR_CHAR);
- final boolean extBeginsWithExtChr = (extLen > 0 &&
extension.charAt(0) == Constants.FILE_EXTENSION_SEPARATOR_CHAR);
- if (nameEndsWithExtChr && extBeginsWithExtChr) {
- return name.substring(0, nameLen) + extension;
- }
- if (!nameEndsWithExtChr && !extBeginsWithExtChr) {
- return name + Constants.FILE_EXTENSION_SEPARATOR + extension;
- }
- return name + extension;
- }
-
- /**
- * Determine whether the specified name is valid for a file or folder on the current
file system.
- * @param newName the new name to be checked
- * @return true if the name is null or contains no invalid characters for a folder or
file, or false otherwise
- */
- public static boolean isFilenameValid( String newName ) {
- return true; //TODO: just catch an exception when the file is accessed or created
- }
-
- /**
- * Copy a file. Overwrites the destination file if it exists.
- * @param fromFileName
- * @param toFileName
- * @throws Exception
- * @since 4.3
- */
- public static void copy(String fromFileName, String toFileName) throws IOException {
- copy(fromFileName, toFileName, true);
- }
-
- /**
- * Copy a file
- * @param fromFileName
- * @param toFileName
- * @param overwrite whether to overwrite the destination file if it exists.
- * @throws MetaMatrixCoreException
- * @since 4.3
- */
- public static void copy(String fromFileName, String toFileName, boolean overwrite)
throws IOException {
- File toFile = new File(toFileName);
-
- if (toFile.exists()) {
- if (overwrite) {
- toFile.delete();
- } else {
- final String msg = "FileUtils.File_already_exists " +
toFileName; //$NON-NLS-1$
- throw new IOException(msg);
- }
- }
-
- File fromFile = new File(fromFileName);
- if (!fromFile.exists()) {
- throw new FileNotFoundException("FileUtils.File_does_not_exist " +
fromFileName); //$NON-NLS-1$
- }
-
- FileInputStream fis = null;
- try {
- fis = new FileInputStream(fromFile);
- write(fis, toFileName);
- } finally {
- if (fis != null) {
- fis.close();
- }
- }
- }
-
- /**
- * Copy recursively the contents of <code>sourceDirectory</code> to
- * the <code>targetDirectory</code>. Note that
<code>sourceDirectory</code>
- * will <b>NOT</b> be copied. If
<code>targetDirectory</code> does not exist, it will be created.
- * @param sourceDirectory The source directory to copy
- * @param targetDirectory The target directory to copy to
- * @throws Exception If the source directory does not exist.
- * @since 4.3
- */
- public static void copyDirectoryContentsRecursively(File sourceDirectory, File
targetDirectory) throws Exception {
- copyRecursively(sourceDirectory, targetDirectory, false);
- }
-
- /**
- * Copy file from orginating directory to the destination directory.
- *
- * @param orginDirectory
- * @param destDirectory
- * @param fileName
- * @throws Exception
- * @since 4.4
- */
- public static void copyFile(String orginDirectory,
- String destDirectory,
- String fileName) throws Exception {
-
- copyFile(orginDirectory, fileName, destDirectory, fileName);
- }
-
- /**
- * Copy file from orginating directory to the destination directory.
- *
- * @param orginDirectory
- * @param orginFileName
- * @param destDirectory
- * @param destFileName
- * @throws Exception
- * @since 4.4
- */
- public static void copyFile(String orginDirectory,
- String orginFileName,
- String destDirectory,
- String destFileName) throws Exception {
-
- FileUtils.copy(orginDirectory + File.separator + orginFileName, destDirectory +
File.separator + destFileName);
- }
-
- /**
- * Copy recursively the <code>sourceDirectory</code> and all its contents
- * to the <code>targetDirectory</code>. If
<code>targetDirectory</code>
- * does not exist, it will be created.
- * @param sourceDirectory The source directory to copy
- * @param targetDirectory The target directory to copy to
- * @throws Exception If the source directory does not exist.
- * @since 4.3
- */
- public static void copyDirectoriesRecursively(File sourceDirectory, File
targetDirectory) throws Exception {
- copyRecursively(sourceDirectory, targetDirectory, true);
- }
-
- /**
- * Copy recursively from the <code>sourceDirectory</code> all its
contents
- * to the <code>targetDirectory</code>. if
- * <code>includeSourceRoot<code> == <code>true</code>, copy
<code>sourceDirectory</code>
- * itself, else only copy <code>sourceDirectory</code>'s contents.
- * If <code>targetDirectory</code> does not exist, it will be created.
- * @param sourceDirectory
- * @param targetDirectory
- * @throws FileNotFoundException
- * @throws Exception
- * @since 4.3
- */
- private static void copyRecursively(File sourceDirectory,
- File targetDirectory,
- boolean includeSourceRoot) throws
FileNotFoundException,
- Exception {
- if (!sourceDirectory.exists()) {
- throw new FileNotFoundException("FileUtils.File_does_not_exist " +
sourceDirectory); //$NON-NLS-1$
- }
-
- if (!sourceDirectory.isDirectory()) {
- throw new FileNotFoundException("FileUtils.Not_a_directory " +
sourceDirectory); //$NON-NLS-1$
- }
-
- File targetDir = new File(targetDirectory.getAbsolutePath() + File.separatorChar
+ sourceDirectory.getName());
- if (includeSourceRoot) {
- // copy source directory
- targetDir.mkdir();
- } else {
- // copy only source directory contents
- targetDir = new File(targetDirectory.getAbsolutePath() +
File.separatorChar);
- }
- File[] sourceFiles = sourceDirectory.listFiles();
- for (int i = 0; i < sourceFiles.length; i++) {
- File srcFile = sourceFiles[i];
- if (srcFile.isDirectory()) {
- File childTargetDir = new File(targetDir.getAbsolutePath());
- copyRecursively(srcFile, childTargetDir, true);
- } else {
- copy(srcFile.getAbsolutePath(), targetDir.getAbsolutePath() +
File.separatorChar + srcFile.getName());
- }
- }
- }
-
- /**
- * Write an InputStream to a file.
- */
- public static void write(InputStream is, String fileName) throws IOException {
- File f = new File(fileName);
- write(is,f);
- }
-
- /**
- * Write an InputStream to a file.
- */
- public static void write(InputStream is, File f) throws IOException {
- write(is, f, DEFAULT_BUFFER_SIZE);
- }
-
- /**
- * Write an InputStream to a file.
- */
- public static void write(InputStream is, File f, int bufferSize) throws IOException {
- f.delete();
- final File parentDir = f.getParentFile();
- if (parentDir !=null) {
- parentDir.mkdirs();
- }
-
- FileOutputStream fio = null;
- BufferedOutputStream bos = null;
- try {
- fio = new FileOutputStream(f);
- bos = new BufferedOutputStream(fio);
- if (bufferSize > 0) {
- byte[] buff = new byte[bufferSize];
- int bytesRead;
-
- // Simple read/write loop.
- while(-1 != (bytesRead = is.read(buff, 0, buff.length))) {
- bos.write(buff, 0, bytesRead);
- }
- }
- bos.flush();
- } finally {
- if (bos != null) {
- bos.close();
- }
- if (fio != null) {
- fio.close();
- }
- }
- }
-
-
- /**
- * Write an File to an OutputStream
- * Note: this will not close the outputStream;
- */
- public static void write(File f, OutputStream outputStream) throws IOException {
- write(f, outputStream, DEFAULT_BUFFER_SIZE);
- }
-
- /**
- * Write an File to an OutputStream
- * Note: this will not close the outputStream;
- */
- public static void write(File f, OutputStream outputStream, int bufferSize)
throws IOException {
- FileInputStream fis = null;
- try {
- fis = new FileInputStream(f);
- write(fis, outputStream, bufferSize);
- } finally {
- if (fis != null) {
- fis.close();
- }
- }
- }
-
- /**
- * Write the given input stream to outputstream
- * Note: this will not close in/out streams
- */
- public static void write(InputStream fis, OutputStream outputStream, int
bufferSize) throws IOException {
- byte[] buff = new byte[bufferSize];
- int bytesRead;
-
- // Simple read/write loop.
- while(-1 != (bytesRead = fis.read(buff, 0, buff.length))) {
- outputStream.write(buff, 0, bytesRead);
- }
- outputStream.flush();
- }
-
- /**
- * Write a byte array to a file.
- */
- public static void write(byte[] data, String fileName) throws IOException {
- ByteArrayInputStream bais = null;
- InputStream is = null;
- try {
- bais = new ByteArrayInputStream(data);
- is = new BufferedInputStream(bais);
-
- write(is, fileName);
- } finally {
- if (is != null) {
- is.close();
- }
- if (bais != null) {
- bais.close();
- }
- }
- }
-
- /**
- * Write a byte array to a file.
- */
- public static void write(byte[] data, File file) throws IOException {
- ByteArrayInputStream bais = null;
- InputStream is = null;
- try {
- bais = new ByteArrayInputStream(data);
- is = new BufferedInputStream(bais);
-
- write(is, file);
- } finally {
- if (is != null) {
- is.close();
- }
- if (bais != null) {
- bais.close();
- }
- }
- }
-
- /**
- * Returns a <code>File</code> array that will contain all the files that
- * exist in the specified directory or any nested directories
- * @return File[] of files in the directory
- */
- public static File[] findAllFilesInDirectoryRecursively(final String dir) {
-
- // Recursively navigate through the contents of this directory
- // gathering up all the files
- List allFiles = new ArrayList();
- File directory = new File(dir);
- addFilesInDirectoryRecursively(directory, allFiles);
-
- return (File[])allFiles.toArray(new File[allFiles.size()]);
-
- }
-
- private static void addFilesInDirectoryRecursively(final File directory, final List
allFiles) {
- File[] files = directory.listFiles();
- if (files != null) {
- for (int i=0; i < files.length; i++) {
- File file = files[i];
- if (file.isDirectory()) {
- addFilesInDirectoryRecursively(file, allFiles);
- } else {
- allFiles.add(file);
- }
- }
- }
- }
-
- /**
- * Returns a <code>File</code> array that will contain all the files that
exist in the directory
- *
- * @return File[] of files in the directory
- */
- public static File[] findAllFilesInDirectory(String dir) {
-
- // Find all files in the specified directory
- File modelsDirFile = new File(dir);
- FileFilter fileFilter = new FileFilter() {
-
- public boolean accept(File file) {
- if (file.isDirectory()) {
- return false;
- }
-
- String fileName = file.getName();
-
- if (fileName == null || fileName.length() == 0) {
- return false;
- }
-
- return true;
-
- }
- };
-
- File[] modelFiles = modelsDirFile.listFiles(fileFilter);
-
- return modelFiles;
-
- }
-
- /**
- * Returns a <code>File</code> array that will contain all the files
that
- * exist in the directory that have the specified extension.
- * @return File[] of files having a certain extension
- */
- public static File[] findAllFilesInDirectoryHavingExtension(String dir, final
String extension) {
-
- // Find all files in that directory that end in XML and attempt to
- // load them into the runtime metadata database.
- File modelsDirFile = new File(dir);
- FileFilter fileFilter = new FileFilter() {
- public boolean accept(File file) {
- if(file.isDirectory()) {
- return false;
- }
-
-
- String fileName = file.getName();
-
- if (fileName==null || fileName.length()==0) {
- return false;
- }
-
- return (fileName.endsWith(extension));
- // here we check to see if the file is an .xml file...
-// int index = fileName.lastIndexOf("."); //$NON-NLS-1$
-//
-// if (index<0 || index==fileName.length()) {
-// return false;
-// }
-//
-// if (fileName.substring(index,
fileName.length()).equalsIgnoreCase(extension)) {
-// return true;
-// }
-// return false;
- }
- };
-
- File[] modelFiles = modelsDirFile.listFiles(fileFilter);
-
- return modelFiles;
-
- }
-
- /**
- * @param string
- * @return
- */
- public static String getFilenameWithoutExtension( final String filename ) {
- if ( filename == null || filename.length() == 0 ) {
- return filename;
- }
- final int extensionIndex =
filename.lastIndexOf(Constants.FILE_EXTENSION_SEPARATOR_CHAR);
- if ( extensionIndex == -1 ) {
- return filename; // not found
- }
- if ( extensionIndex == 0 ) {
- return ""; //$NON-NLS-1$
- }
- return filename.substring(0,extensionIndex);
- }
-
- public static String getBaseFileNameWithoutExtension(String path) {
- return StringUtil.getFirstToken(StringUtil.getLastToken(path, "/"),
"."); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- /**
- * Obtains the file extension of the specified <code>File</code>. The
extension is considered to be all the
- * characters after the last occurrence of {@link
Constants#FILE_EXTENSION_SEPARATOR_CHAR} in the pathname
- * of the input.
- * @param theFile the file whose extension is being requested
- * @return the extension or <code>null</code> if not found
- * @since 4.2
- */
- public static String getExtension(File theFile) {
- return getExtension(theFile.getPath());
- }
-
- /**
- * Obtains the file extension of the specified file name. The extension is considered
to be all the
- * characters after the last occurrence of {@link
Constants#FILE_EXTENSION_SEPARATOR_CHAR}.
- * @param theFileName the file whose extension is being requested
- * @return the extension or <code>null</code> if not found
- * @since 4.2
- */
- public static String getExtension(String theFileName) {
- String result = null;
- final int index =
theFileName.lastIndexOf(Constants.FILE_EXTENSION_SEPARATOR_CHAR);
-
- // make sure extension char is found and is not the last char in the path
- if ((index != -1) && ((index + 1) != theFileName.length())) {
- result = theFileName.substring(index + 1);
- }
-
- return result;
- }
-
- /**
- * Returns true iff str.toLowerCase().endsWith(".jar") ||
str.toLowerCase().endsWith(".zip")
- * implementation is not creating extra strings.
- */
- public final static boolean isArchiveFileName(String name) {
- int nameLength = name == null ? 0 : name.length();
- int suffixLength = SUFFIX_JAR.length;
- if (nameLength < suffixLength) return false;
-
- // try to match as JAR file
- for (int i = 0; i < suffixLength; i++) {
- char c = name.charAt(nameLength - i - 1);
- int suffixIndex = suffixLength - i - 1;
- if (c != SUFFIX_jar[suffixIndex] && c != SUFFIX_JAR[suffixIndex]) {
-
- // try to match as ZIP file
- suffixLength = SUFFIX_ZIP.length;
- if (nameLength < suffixLength) return false;
- for (int j = 0; j < suffixLength; j++) {
- c = name.charAt(nameLength - j - 1);
- suffixIndex = suffixLength - j - 1;
- if (c != SUFFIX_zip[suffixIndex] && c !=
SUFFIX_ZIP[suffixIndex]) return false;
- }
- return true;
- }
- }
- return true;
- }
-
- /**
- * Returns true iff str.toLowerCase().endsWith(".class")
- * implementation is not creating extra strings.
- */
- public final static boolean isClassFileName(String name) {
- int nameLength = name == null ? 0 : name.length();
- int suffixLength = SUFFIX_CLASS.length;
- if (nameLength < suffixLength) return false;
-
- for (int i = 0; i < suffixLength; i++) {
- char c = name.charAt(nameLength - i - 1);
- int suffixIndex = suffixLength - i - 1;
- if (c != SUFFIX_class[suffixIndex] && c != SUFFIX_CLASS[suffixIndex])
return false;
- }
- return true;
- }
-
- /**
- * Returns true iff str.toLowerCase().endsWith(".java")
- * implementation is not creating extra strings.
- */
- public final static boolean isJavaFileName(String name) {
- int nameLength = name == null ? 0 : name.length();
- int suffixLength = SUFFIX_JAVA.length;
- if (nameLength < suffixLength) return false;
-
- for (int i = 0; i < suffixLength; i++) {
- char c = name.charAt(nameLength - i - 1);
- int suffixIndex = suffixLength - i - 1;
- if (c != SUFFIX_java[suffixIndex] && c != SUFFIX_JAVA[suffixIndex])
return false;
- }
- return true;
- }
-
-
- public static File convertByteArrayToFile(final byte[] contents, final String
parentDirectoryPath, final String fileName) {
- if (contents != null) {
- FileOutputStream os = null;
- try {
- final File temp = new File(parentDirectoryPath,fileName);
- os = new FileOutputStream(temp);
- os.write(contents);
- return temp;
- } catch (Exception e) {
- throw new RuntimeException(e);
- } finally {
- if (os != null) {
- try {
- os.close();
- } catch (IOException e1) {
- // do nothing
- }
- }
- }
- }
- return null;
- }
-
- public static void removeDirectoryAndChildren(File directory) {
- removeChildrenRecursively(directory);
- if(!directory.delete()) {
- directory.deleteOnExit();
- }
- }
-
- public static void removeChildrenRecursively(File directory) {
- File[] files = directory.listFiles();
- if(files != null) {
- for(int i=0; i < files.length; i++) {
- File file = files[i];
- if (file.isDirectory()) {
- removeDirectoryAndChildren(file);
- } else {
- if(!file.delete()) {
- file.deleteOnExit();
- }
- }
- }
- }
- }
-
- /**
- * Builds a file directory path from a physical location and a location that needs
- * to be appended to the physical. This is used so that the correct File.separator
- * is used and that no additional separator is added when not needed.
- * @param physicalDirectory
- * @param appendLocation
- * @return
- * @since 4.3
- */
- public static String buildDirectoryPath(String[] paths) {
-// String physicalDirectory, String appendLocation) {
-
- if (paths == null || paths.length == 0) {
- return ""; //$NON-NLS-1$
- }
- if (paths.length == 1) {
- return (paths[0]!=null?paths[0]:"");//$NON-NLS-1$
- }
- int l = paths.length;
- StringBuffer sb = new StringBuffer();
- for (int cur=0;cur<l; cur++) {
- int next = cur+1;
-
- String value = paths[cur]!=null?paths[cur]:"";//$NON-NLS-1$
- if (value.equals("")) {//$NON-NLS-1$
- continue;
- }
- sb.append(value);
-
- if (next < l) {
- String nextValue =
paths[next]!=null?paths[next]:"";//$NON-NLS-1$
- if (value.endsWith(File.separator)) {
-
- } else if (!nextValue.startsWith(File.separator)) {
- sb.append(File.separator);
- }
-
- }
- }
-
- return sb.toString();
- }
-
- /**
- * Compute checksum for the given file.
- * @param f The file for which checksum needs to be computed
- * @return The checksum
- * @since 4.3
- */
- public static long getCheckSum(final File f) throws Exception {
- ArgCheck.isNotNull(f);
- FileInputStream is = null;
- try {
- is = new FileInputStream(f);
- return ChecksumUtil.computeChecksum(is).getValue();
- } finally {
- if (is != null) {
- try {
- is.close();
- } catch (IOException err1) {
- }
- }
- }
- }
-
-
- /**
- * Test whether it's possible to read and write files in the specified directory.
- * @param dirPath Name of the directory to test
- * @throws MetaMatrixException
- * @since 4.3
- */
- public static void testDirectoryPermissions(String dirPath) throws Exception {
-
- //try to create a file
- File tmpFile = new File(dirPath + File.separatorChar + TEMP_FILE);
- boolean success = false;
- try {
- success = tmpFile.createNewFile();
- } catch (IOException e) {
- }
- if (!success) {
- final String msg = "FileUtils.Unable_to_create_file_in " + dirPath;
//$NON-NLS-1$
- throw new Exception(msg);
- }
-
-
- //test if file can be written to
- if (!tmpFile.canWrite()) {
- final String msg = "FileUtils.Unable_to_write_file_in " + dirPath;
//$NON-NLS-1$
- throw new Exception(msg);
- }
-
- //test if file can be read
- if (!tmpFile.canRead()) {
- final String msg = "FileUtils.Unable_to_read_file_in " + dirPath;
//$NON-NLS-1$
- throw new Exception(msg);
- }
-
- //test if file can be renamed
- File newFile = new File(dirPath + File.separatorChar + TEMP_FILE_RENAMED);
- success = false;
- try {
- success = tmpFile.renameTo(newFile);
- } catch (Exception e) {
- }
- if (!success) {
- final String msg = "FileUtils.Unable_to_rename_file_in " + dirPath;
//$NON-NLS-1$
- throw new Exception(msg);
- }
-
- //test if file can be deleted
- success = false;
- try {
- success = newFile.delete();
- } catch (Exception e) {
- }
- if (!success) {
- final String msg = "FileUtils.Unable_to_delete_file_in " + dirPath;
//$NON-NLS-1$
- throw new Exception(msg);
- }
- }
-
- /**
- * Rename a file.
- * @param oldFilePath
- * @param newFilePath
- * @param overwrite If true, overwrite the old file if it exists. If false, throw an
exception if the old file exists.
- * @throws MetaMatrixCoreException
- * @since 4.3
- */
- public static void rename(String oldFilePath, String newFilePath, boolean overwrite)
throws IOException {
- File oldFile = new File(oldFilePath);
- File newFile = new File(newFilePath);
-
- if (newFile.exists()) {
- if (overwrite) {
- newFile.delete();
- } else {
- final String msg = "FileUtils.File_already_exists " +
newFilePath; //$NON-NLS-1$
- throw new IOException(msg);
- }
- }
-
- boolean renamed = oldFile.renameTo(newFile);
-
- //Sometimes file.renameTo will silently fail, for example attempting to rename
from different UNIX partitions.
- //Try to copy instead.
- if (!renamed) {
- copy(oldFilePath, newFilePath);
- oldFile.delete();
- }
- }
-
-
-
-
-
- public static void remove(String filePath) throws IOException {
- File file = new File(filePath);
- if (file.exists()) {
- file.delete();
- }
- }
-
-}
\ No newline at end of file
Deleted: trunk/test-integration/db/src/main/java/org/teiid/test/util/StringUtil.java
===================================================================
--- trunk/test-integration/db/src/main/java/org/teiid/test/util/StringUtil.java 2009-09-29
13:52:23 UTC (rev 1489)
+++ trunk/test-integration/db/src/main/java/org/teiid/test/util/StringUtil.java 2009-09-29
14:23:43 UTC (rev 1490)
@@ -1,906 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership. Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- *
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * All rights reserved.
- * This code is made available under the terms of the Eclipse Public
- * License, version 1.0.
- */
-
-package org.teiid.test.util;
-
-import java.io.ByteArrayOutputStream;
-import java.io.PrintWriter;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Comparator;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.StringTokenizer;
-import java.util.regex.Pattern;
-
-/**
- * This is a common place to put String utility methods.
- */
-public final class StringUtil {
-
- public interface Constants {
- char CARRIAGE_RETURN_CHAR = '\r';
- char LINE_FEED_CHAR = '\n';
- char NEW_LINE_CHAR = LINE_FEED_CHAR;
- char SPACE_CHAR = ' ';
- char DOT_CHAR = '.';
- char TAB_CHAR = '\t';
-
- String CARRIAGE_RETURN = String.valueOf(CARRIAGE_RETURN_CHAR);
- String EMPTY_STRING = ""; //$NON-NLS-1$
- String DBL_SPACE = " "; //$NON-NLS-1$
- String LINE_FEED = String.valueOf(LINE_FEED_CHAR);
- String NEW_LINE = String.valueOf(NEW_LINE_CHAR);
- String SPACE = String.valueOf(SPACE_CHAR);
- String DOT = String.valueOf(DOT_CHAR);
- String TAB = String.valueOf(TAB_CHAR);
-
- String[] EMPTY_STRING_ARRAY = new String[0];
-
- // all patterns below copied from Eclipse's PatternConstructor class.
- final Pattern PATTERN_BACK_SLASH = Pattern.compile("\\\\");
//$NON-NLS-1$
- final Pattern PATTERN_QUESTION = Pattern.compile("\\?"); //$NON-NLS-1$
- final Pattern PATTERN_STAR = Pattern.compile("\\*"); //$NON-NLS-1$
- }
-
- /**
- * The String "'"
- */
- public static final String SINGLE_QUOTE = "'"; //$NON-NLS-1$
-
- /**
- * The name of the System property that specifies the string that should be used to
separate
- * lines. This property is a standard environment property that is usually set
automatically.
- */
- public static final String LINE_SEPARATOR_PROPERTY_NAME = "line.separator";
//$NON-NLS-1$
-
- /**
- * The String that should be used to separate lines; defaults to
- * {@link #NEW_LINE}
- */
- public static final String LINE_SEPARATOR =
System.getProperty(LINE_SEPARATOR_PROPERTY_NAME, Constants.NEW_LINE);
-
- public static final Comparator CASE_INSENSITIVE_ORDER =
String.CASE_INSENSITIVE_ORDER;
-
- public static final Comparator CASE_SENSITIVE_ORDER = new Comparator() {
- /**
- * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
- * @since 4.2
- */
- public int compare(Object o1, Object o2) {
- if ( o1 == o2 ) {
- return 0;
- }
- return ((String)o1).compareTo((String)o2);
- }
- };
-
- public static String getLineSeparator() {
- return LINE_SEPARATOR;
- }
-
- /**
- * Utility to return a string enclosed in ''.
- * Creation date: (12/2/99 12:05:10 PM)
- */
- public static String enclosedInSingleQuotes(String aString) {
- StringBuffer sb = new StringBuffer();
- sb.append(SINGLE_QUOTE);
- sb.append(aString);
- sb.append(SINGLE_QUOTE);
- return sb.toString();
- }
-
- public static String removeChars(final String value, final char[] chars) {
- final StringBuffer result = new StringBuffer();
- if (value != null && chars != null && chars.length > 0) {
- final String removeChars = String.valueOf(chars);
- for (int i = 0; i < value.length(); i++) {
- final String character = value.substring(i, i + 1);
- if (removeChars.indexOf(character) == -1) {
- result.append(character);
- }
- }
- } else {
- result.append(value);
- }
- return result.toString();
- }
-
- /**
- * Join string pieces and separate with a delimiter. Similar to the perl function of
- * the same name. If strings or delimiter are null, null is returned. Otherwise, at
- * least an empty string will be returned.
- * @see #split
- *
- * @param strings String pieces to join
- * @param delimiter Delimiter to put between string pieces
- * @return One merged string
- */
- public static String join(List strings, String delimiter) {
- if(strings == null || delimiter == null) {
- return null;
- }
-
- StringBuffer str = new StringBuffer();
-
- // This is the standard problem of not putting a delimiter after the last
- // string piece but still handling the special cases. A typical way is to check every
- // iteration if it is the last one and skip the delimiter - this is avoided by
- // looping up to the last one, then appending just the last one.
-
- // First we loop through all but the last one (if there are at least 2) and
- // put the piece and a delimiter after it. An iterator is used to walk the list.
- int most = strings.size()-1;
- if(strings.size() > 1) {
- Iterator iter = strings.iterator();
- for(int i=0; i<most; i++) {
- str.append(iter.next());
- str.append(delimiter);
- }
- }
-
- // If there is at least one element, put the last one on with no delimiter after.
- if(strings.size() > 0) {
- str.append(strings.get(most));
- }
-
- return str.toString();
- }
-
- /**
- * Return a stringified version of the array.
- * @param array the array
- * @param delim the delimiter to use between array components
- * @return the string form of the array
- */
- public static String toString( final Object[] array, final String delim ) {
- if ( array == null ) {
- return ""; //$NON-NLS-1$
- }
- if ( array.length == 0 ) {
- return "[]"; //$NON-NLS-1$
- }
- final StringBuffer sb = new StringBuffer();
- sb.append('[');
- for (int i = 0; i < array.length; ++i) {
- if ( i != 0 ) {
- sb.append(delim);
- }
- sb.append(array[i]);
- }
- sb.append(']');
- return sb.toString();
- }
-
- /**
- * Return a stringified version of the array, using a ',' as a delimiter
- * @param array the array
- * @return the string form of the array
- * @see #toString(Object[], String)
- */
- public static String toString( final Object[] array ) {
- return toString(array,","); //$NON-NLS-1$
- }
-
- /**
- * Split a string into pieces based on delimiters. Similar to the perl function of
- * the same name. The delimiters are not included in the returned strings.
- * @see #join
- *
- * @param str Full string
- * @param splitter Characters to split on
- * @return List of String pieces from full string
- */
- public static List split(String str, String splitter) {
- StringTokenizer tokens = new StringTokenizer(str, splitter);
- ArrayList l = new ArrayList(tokens.countTokens());
- while(tokens.hasMoreTokens()) {
- l.add(tokens.nextToken());
- }
- return l;
- }
-
- /**
- * Break a string into pieces based on matching the full delimiter string in the
text.
- * The delimiter is not included in the returned strings.
- * @param target The text to break up.
- * @param delimiter The sub-string which is used to break the target.
- * @return List of String from the target.
- */
- public static List splitOnEntireString(String target, String delimiter) {
- ArrayList result = new ArrayList();
- if (delimiter.length() > 0) {
- int index = 0;
- int indexOfNextMatch = target.indexOf(delimiter);
- while (indexOfNextMatch > -1) {
- result.add(target.substring(index, indexOfNextMatch));
- index = indexOfNextMatch + delimiter.length();
- indexOfNextMatch = target.indexOf(delimiter, index);
- }
- if (index <= target.length()) {
- result.add(target.substring(index));
- }
- } else {
- result.add(target);
- }
- return result;
- }
-
- /**
- * Split a string into pieces based on delimiters preserving spaces in
- * quoted substring as on element in the returned list. The delimiters are
- * not included in the returned strings.
- * @see #join
- *
- * @param str Full string
- * @param splitter Characters to split on
- * @return List of String pieces from full string
- */
- public static List splitPreservingQuotedSubstring(String str, String splitter) {
- ArrayList l = new ArrayList();
- StringTokenizer tokens = new StringTokenizer(str, splitter);
- StringBuffer token = new StringBuffer();
- while(tokens.hasMoreTokens()) {
- token.setLength(0);
- token.append(tokens.nextToken());
- if ( token.charAt(0) == '"' ) {
- token.deleteCharAt(0);
- while ( tokens.hasMoreTokens() ) {
- token.append(Constants.SPACE + tokens.nextToken());
- if ( token.charAt(token.length() -1) == '"' ) {
- token.deleteCharAt(token.length() - 1);
- break;
- }
- }
- }
- l.add(token.toString().trim());
- }
- return l;
- }
-
- /*
- * Replace a single occurrence of the search string with the replace string
- * in the source string. If any of the strings is null or the search string
- * is zero length, the source string is returned.
- * @param source the source string whose contents will be altered
- * @param search the string to search for in source
- * @param replace the string to substitute for search if present
- * @return source string with the *first* occurrence of the search string
- * replaced with the replace string
- */
- public static String replace(String source, String search, String replace) {
- if (source != null && search != null && search.length() > 0
&& replace != null) {
- int start = source.indexOf(search);
- if (start > -1) {
- return new StringBuffer(source).replace(start, start + search.length(),
replace).toString();
- }
- }
- return source;
- }
-
- /*
- * Replace all occurrences of the search string with the replace string
- * in the source string. If any of the strings is null or the search string
- * is zero length, the source string is returned.
- * @param source the source string whose contents will be altered
- * @param search the string to search for in source
- * @param replace the string to substitute for search if present
- * @return source string with *all* occurrences of the search string
- * replaced with the replace string
- */
- public static String replaceAll(String source, String search, String replace) {
- if (source != null && search != null && search.length() > 0
&& replace != null) {
- int start = source.indexOf(search);
- if (start > -1) {
- StringBuffer newString = new StringBuffer(source);
- replaceAll(newString, search, replace);
- return newString.toString();
- }
- }
- return source;
- }
-
- public static void replaceAll(StringBuffer source, String search, String replace) {
- if (source != null && search != null && search.length() > 0
&& replace != null) {
- int start = source.toString().indexOf(search);
- while (start > -1) {
- int end = start + search.length();
- source.replace(start, end, replace);
- start = source.toString().indexOf(search, start + replace.length());
- }
- }
- }
-
- /**
- * Simple static method to tuncate Strings to given length.
- * @param in the string that may need tuncating.
- * @param len the lenght that the string should be truncated to.
- * @return a new String containing chars with length <= len or
<code>null</code>
- * if input String is <code>null</code>.
- */
- public static String truncString(String in, int len) {
- String out = in;
- if ( in != null && len > 0 && in.length() > len ) {
- out = in.substring(0, len);
- }
- return out;
- }
-
- /**
- * Simple utility method to wrap a string by inserting line separators creating
- * multiple lines each with length no greater than the user specified maximum.
- * The method parses the given string into tokens using a space delimiter then
- * reassembling the tokens into the resulting string while inserting separators
- * when required. If the number of characters in a single token is greater
- * than the specified maximum, the token will not be split but instead the
- * maximum will be exceeded.
- * @param str the string that may need tuncating.
- * @param maxCharPerLine the max number of characters per line
- * @return a new String containing line separators or the original string
- * if its length was less than the maximum.
- */
- public static String wrap(String str, int maxCharPerLine) {
- int strLength = str.length();
- if (strLength > maxCharPerLine) {
- StringBuffer sb = new
StringBuffer(str.length()+(strLength/maxCharPerLine)+1);
- strLength = 0;
- List tokens = StringUtil.split(str,Constants.SPACE);
- Iterator itr = tokens.iterator();
- while (itr.hasNext()) {
- String token = (String) itr.next();
- if ( strLength+token.length() > maxCharPerLine ) {
-// sb.append(getLineSeparator());
- sb.append(Constants.NEW_LINE);
- strLength = 0;
- }
- sb.append(token);
- sb.append(Constants.SPACE);
- strLength += token.length()+1;
- }
- return sb.toString();
- }
- return str;
- }
-
- /**
- * Return the tokens in a string in a list. This is particularly
- * helpful if the tokens need to be processed in reverse order. In that case,
- * a list iterator can be acquired from the list for reverse order traversal.
- *
- * @param str String to be tokenized
- * @param delimiter Characters which are delimit tokens
- * @return List of string tokens contained in the tokenized string
- */
- public static List getTokens(String str, String delimiter) {
- ArrayList l = new ArrayList();
- StringTokenizer tokens = new StringTokenizer(str, delimiter);
- while(tokens.hasMoreTokens()) {
- l.add(tokens.nextToken());
- }
- return l;
- }
-
- /**
- * Return the number of tokens in a string that are seperated by the delimiter.
- *
- * @param str String to be tokenized
- * @param delimiter Characters which are delimit tokens
- * @return Number of tokens seperated by the delimiter
- */
- public static int getTokenCount(String str, String delimiter) {
- StringTokenizer tokens = new StringTokenizer(str, delimiter);
- return tokens.countTokens();
- }
-
- /**
- * Return the number of occurrences of token string that occurs in input string.
- * Note: token is case sensitive.
- *
- * @param input
- * @param token
- * @return int
- */
- public static int occurrences(String input, String token) {
- int num = 0;
- int index = input.indexOf(token);
- while (index >= 0) {
- num++;
- index = input.indexOf(token, index+1);
- }
- return num;
- }
-
- /**
- * Return the last token in the string.
- *
- * @param str String to be tokenized
- * @param delimiter Characters which are delimit tokens
- * @return the last token contained in the tokenized string
- */
- public static String getLastToken(String str, String delimiter) {
- if (str == null) {
- return Constants.EMPTY_STRING;
- }
- int beginIndex = 0;
- if (str.lastIndexOf(delimiter) > 0) {
- beginIndex = str.lastIndexOf(delimiter)+1;
- }
- return str.substring(beginIndex,str.length());
- }
-
-
- /**
- * Return the first token in the string.
- *
- * @param str String to be tokenized
- * @param delimiter Characters which are delimit tokens
- * @return the first token contained in the tokenized string
- */
- public static String getFirstToken(String str, String delimiter) {
- if (str == null) {
- return Constants.EMPTY_STRING;
- }
- int endIndex = str.indexOf(delimiter);
- if (endIndex < 0) {
- endIndex = str.length();
- }
- return str.substring(0,endIndex);
- }
-
-
- public static String computePluralForm(String str) {
- return computePluralForm(str, Constants.EMPTY_STRING);
- }
-
- public static String computePluralForm(String str, String defaultValue ) {
- if ( str == null || str.length() == 0 ) {
- return defaultValue;
- }
- String result = str;
- if ( result.endsWith("es") ) { //$NON-NLS-1$
- // do nothing
- } else if ( result.endsWith("ss") || //$NON-NLS-1$
- result.endsWith("x") || //$NON-NLS-1$
- result.endsWith("ch") || //$NON-NLS-1$
- result.endsWith("sh") ) { //$NON-NLS-1$
- result = result + "es"; //$NON-NLS-1$
- } else if ( result.endsWith("y") && ! ( //$NON-NLS-1$
- result.endsWith("ay") || //$NON-NLS-1$
- result.endsWith("ey") || //$NON-NLS-1$
- result.endsWith("iy") || //$NON-NLS-1$
- result.endsWith("oy") || //$NON-NLS-1$
- result.endsWith("uy") || //$NON-NLS-1$
- result.equalsIgnoreCase("any") ) ) { //$NON-NLS-1$
- result = result.substring(0, result.length()-1) + "ies";
//$NON-NLS-1$
- } else {
- result += "s"; //$NON-NLS-1$
- }
- return result;
- }
-
- public static String getStackTrace( final Throwable t ) {
- final ByteArrayOutputStream bas = new ByteArrayOutputStream();
- final PrintWriter pw = new PrintWriter(bas);
- t.printStackTrace(pw);
- pw.close();
- return bas.toString();
- }
-
- /**
- * Returns whether the specified text represents a boolean value, i.e., whether it
equals "true" or "false"
- * (case-insensitive).
- * @since 4.0
- */
- public static boolean isBoolean(final String text) {
- return (Boolean.TRUE.toString().equalsIgnoreCase(text) ||
Boolean.FALSE.toString().equalsIgnoreCase(text));
- }
-
- /**<p>
- * Returns whether the specified text is either empty or null.
- * </p>
- * @param text The text to check; may be null;
- * @return True if the specified text is either empty or null.
- * @since 4.0
- */
- public static boolean isEmpty(final String text) {
- return (text == null || text.length() == 0);
- }
-
- /**
- * Returns the index within this string of the first occurrence of the
- * specified substring. The integer returned is the smallest value
- * <i>k</i> such that:
- * <blockquote><pre>
- * this.startsWith(str, <i>k</i>)
- * </pre></blockquote>
- * is <code>true</code>.
- *
- * @param text any string.
- * @param str any string.
- * @return if the str argument occurs as a substring within text,
- * then the index of the first character of the first
- * such substring is returned; if it does not occur as a
- * substring, <code>-1</code> is returned. If the text or
- * str argument is null or empty then <code>-1</code> is
returned.
- */
- public static int indexOfIgnoreCase(final String text, final String str) {
- if (isEmpty(text)) {
- return -1;
- }
- if (isEmpty(str)) {
- return -1;
- }
- final String lowerText = text.toLowerCase();
- final String lowerStr = str.toLowerCase();
- return lowerText.indexOf(lowerStr);
- }
-
- /**
- * Tests if the string starts with the specified prefix.
- *
- * @param text the string to test.
- * @param prefix the prefix.
- * @return <code>true</code> if the character sequence represented by
the
- * argument is a prefix of the character sequence represented by
- * this string; <code>false</code> otherwise.
- * Note also that <code>true</code> will be returned if the
- * prefix is an empty string or is equal to the text
- * <code>String</code> object as determined by the
- * {@link #equals(Object)} method. If the text or
- * prefix argument is null <code>false</code> is returned.
- * @since JDK1. 0
- */
- public static boolean startsWithIgnoreCase(final String text, final String prefix) {
- if (isEmpty(text)) {
- return false;
- }
- if (prefix == null) {
- return false;
- }
- int textLength = text.length();
- int prefixLength = prefix.length();
- if (prefixLength == 0) {
- return true;
- }
- if (prefixLength > textLength) {
- return false;
- }
- char[] chArray = prefix.toCharArray();
- for (int i = 0; i != chArray.length; ++i) {
- char ch1 = chArray[i];
- char ch2 = text.charAt(i);
- if (ch1 == ch2 || Character.toLowerCase(ch1) == Character.toLowerCase(ch2))
{
- // continue
- } else {
- return false;
- }
- }
- return true;
- }
-
- /**
- * Tests if the string ends with the specified suffix.
- *
- * @param text the string to test.
- * @param suffix the suffix.
- * @return <code>true</code> if the character sequence represented by
the
- * argument is a suffix of the character sequence represented by
- * this object; <code>false</code> otherwise. Note that the
- * result will be <code>true</code> if the suffix is the
- * empty string or is equal to this <code>String</code> object
- * as determined by the {@link #equals(Object)} method. If the text or
- * suffix argument is null <code>false</code> is returned.
- */
- public static boolean endsWithIgnoreCase(final String text, final String suffix) {
- if (isEmpty(text)) {
- return false;
- }
- if (suffix == null) {
- return false;
- }
- int textLength = text.length();
- int suffixLength = suffix.length();
- if (suffixLength == 0) {
- return true;
- }
- if (suffixLength > textLength) {
- return false;
- }
- int offset = textLength - suffixLength;
- char[] chArray = suffix.toCharArray();
- for (int i = 0; i != chArray.length; ++i) {
- char ch1 = chArray[i];
- char ch2 = text.charAt(offset + i);
- if (ch1 == ch2 || Character.toLowerCase(ch1) == Character.toLowerCase(ch2))
{
- // continue
- } else {
- return false;
- }
- }
- return true;
- }
-
- /**
- * Determine if the string passed in has all digits as its contents
- * @param str
- * @return true if digits; false otherwise
- */
- public static boolean isDigits(String str) {
- for(int i=0; i<str.length(); i++) {
- if(!StringUtil.isDigit(str.charAt(i))) {
- return false;
- }
- }
- return true;
- }
-
//============================================================================================================================
- // Constructors
-
- /**<p>
- * Prevents instantiation.
- * </p>
- * @since 4.0
- */
- private StringUtil() {
- }
-
- /*
- * Converts user string to regular expres '*' and '?' to regEx
variables.
- * copied from eclipse's PatternConstructor
- */
- static String asRegEx(String pattern) {
- // Replace \ with \\, * with .* and ? with .
- // Quote remaining characters
- String result1 = Constants.PATTERN_BACK_SLASH.matcher(pattern).replaceAll(
- "\\\\E\\\\\\\\\\\\Q"); //$NON-NLS-1$
- String result2 = Constants.PATTERN_STAR.matcher(result1).replaceAll(
- "\\\\E.*\\\\Q"); //$NON-NLS-1$
- String result3 = Constants.PATTERN_QUESTION.matcher(result2).replaceAll(
- "\\\\E.\\\\Q"); //$NON-NLS-1$
- return "\\Q" + result3 + "\\E"; //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- /**
- * Creates a regular expression pattern from the pattern string (which is
- * our old 'StringMatcher' format). Copied from Eclipse's
PatternConstructor class.
- *
- * @param pattern
- * The search pattern
- * @param isCaseSensitive
- * Set to <code>true</code> to create a case insensitve
pattern
- * @return The created pattern
- */
- public static Pattern createPattern(String pattern, boolean isCaseSensitive) {
- if (isCaseSensitive)
- return Pattern.compile(asRegEx(pattern));
- return Pattern.compile(asRegEx(pattern), Pattern.CASE_INSENSITIVE
- | Pattern.UNICODE_CASE);
- }
-
- /**
- * Removes extraneous whitespace from a string. By it's nature, it will be
trimmed also.
- * @param raw
- * @return
- * @since 5.0
- */
- public static String collapseWhitespace(String raw) {
- StringBuffer rv = new StringBuffer(raw.length());
-
- StringTokenizer izer = new StringTokenizer(raw, " "); //$NON-NLS-1$
- while (izer.hasMoreTokens()) {
- String tok = izer.nextToken();
- // Added one last check here so we don't append a "space" on
the end of the string
- rv.append(tok);
- if( izer.hasMoreTokens() ) {
- rv.append(' ');
- }
- } // endwhile
-
- return rv.toString();
- }
-
- /**
- * If input == null OR input.length() < desiredLength, pad to desiredLength with
spaces.
- * If input.length() > desiredLength, chop at desiredLength.
- * @param input Input text
- * @param desiredLength Desired length
- * @return
- * @since 5.0
- */
- public static String toFixedLength(String input, int desiredLength) {
- if(input == null) {
- input = ""; //$NON-NLS-1$
- }
-
- if(input.length() == desiredLength) {
- return input;
- }
-
- if(input.length() < desiredLength) {
- StringBuffer str = new StringBuffer(input);
- int needSpaces = desiredLength - input.length();
- for(int i=0; i<needSpaces; i++) {
- str.append(' ');
- }
- return str.toString();
- }
-
- // Else too long - chop
- return input.substring(0, desiredLength);
- }
-
-
- public static boolean isLetter(char c) {
- return isBasicLatinLetter(c) || Character.isLetter(c);
- }
- public static boolean isDigit(char c) {
- return isBasicLatinDigit(c) || Character.isDigit(c);
- }
- public static boolean isLetterOrDigit(char c) {
- return isBasicLatinLetter(c) || isBasicLatinDigit(c) ||
Character.isLetterOrDigit(c);
- }
-
- public static String toUpperCase(String str) {
- String newStr = convertBasicLatinToUpper(str);
- if (newStr == null) {
- return str.toUpperCase();
- }
- return newStr;
- }
-
- public static String toLowerCase(String str) {
- String newStr = convertBasicLatinToLower(str);
- if (newStr == null) {
- return str.toLowerCase();
- }
- return newStr;
- }
-
- /**
- * Create a valid filename from the given String.
- *
- * @param str The String to convert to a valid filename.
- * @param defaultName The default name to use if only special characters exist.
- * @return String A valid filename.
- */
- public static String createFileName(String str) {
-
- /** Replace some special chars */
- str = str.replaceAll(" \\| ", "_"); //$NON-NLS-1$
//$NON-NLS-2$
- str = str.replaceAll(">", "_"); //$NON-NLS-1$ //$NON-NLS-2$
- str = str.replaceAll(": ", "_"); //$NON-NLS-1$ //$NON-NLS-2$
- str = str.replaceAll(" ", "_"); //$NON-NLS-1$ //$NON-NLS-2$
- str = str.replaceAll("\\?", "_"); //$NON-NLS-1$ //$NON-NLS-2$
- str = str.replaceAll("/", "_"); //$NON-NLS-1$ //$NON-NLS-2$
-
- /** If filename only contains of special chars */
- if (str.matches("[_]+")) //$NON-NLS-1$
- str = "file"; //$NON-NLS-1$
-
- return str;
- }
-
-
- /**
- * Make the first letter uppercase
- * @param str
- * @return The string with the first letter being changed to uppercase
- * @since 5.5
- */
- public static String firstLetterUppercase(String str) {
- if(str == null || str.length() == 0) {
- return null;
- }
- if(str.length() == 1) {
- return str.toUpperCase();
- }
- return str.substring(0, 1).toUpperCase() + str.substring(1);
- }
-
- private static String convertBasicLatinToUpper(String str) {
- char[] chars = str.toCharArray();
- for (int i = 0; i < chars.length; i++) {
- if (isBasicLatinLowerCase(chars[i])) {
- chars[i] = (char)('A' + (chars[i] - 'a'));
- } else if (!isBasicLatinChar(chars[i])) {
- return null;
- }
- }
- return new String(chars);
- }
-
- private static String convertBasicLatinToLower(String str) {
- char[] chars = str.toCharArray();
- for (int i = 0; i < chars.length; i++) {
- if (isBasicLatinUpperCase(chars[i])) {
- chars[i] = (char)('a' + (chars[i] - 'A'));
- } else if (!isBasicLatinChar(chars[i])) {
- return null;
- }
- }
- return new String(chars);
- }
-
- private static boolean isBasicLatinUpperCase(char c) {
- return c >= 'A' && c <= 'Z';
- }
- private static boolean isBasicLatinLowerCase(char c) {
- return c >= 'a' && c <= 'z';
- }
- private static boolean isBasicLatinLetter(char c) {
- return (c >= 'a' && c <= 'z') || (c >=
'A' && c <= 'Z');
- }
- private static boolean isBasicLatinDigit(char c) {
- return c >= '0' && c <= '9';
- }
- private static boolean isBasicLatinChar(char c) {
- return c <= '\u007F';
- }
-
- /**
- * Convert the given value to specified type.
- * @param value
- * @param type
- * @return
- */
- @SuppressWarnings("unchecked")
- public static <T> T valueOf(String value, Class type){
-
- if(type == String.class) {
- return (T) value;
- }
- else if(type == Boolean.class || type == Boolean.TYPE) {
- return (T) Boolean.valueOf(value);
- }
- else if (type == Integer.class || type == Integer.TYPE) {
- return (T) Integer.decode(value);
- }
- else if (type == Float.class || type == Float.TYPE) {
- return (T) Float.valueOf(value);
- }
- else if (type == Double.class || type == Double.TYPE) {
- return (T) Double.valueOf(value);
- }
- else if (type == Long.class || type == Long.TYPE) {
- return (T) Long.decode(value);
- }
- else if (type == Short.class || type == Short.TYPE) {
- return (T) Short.decode(value);
- }
- else if (type.isAssignableFrom(List.class)) {
- return (T)new ArrayList<String>(Arrays.asList(value.split(",")));
//$NON-NLS-1$
- }
- else if (type == Void.class) {
- return null;
- }
- else if (type.isEnum()) {
- return (T)Enum.valueOf(type, value);
- }
-
- else if (type.isAssignableFrom(Map.class)) {
- List<String> l = Arrays.asList(value.split(",")); //$NON-NLS-1$
- Map m = new HashMap<String, String>();
- for(String key: l) {
- int index = key.indexOf('=');
- if (index != -1) {
- m.put(key.substring(0, index), key.substring(index+1));
- }
- }
- return (T)m;
- }
-
- throw new IllegalArgumentException("Conversion from String to "+
type.getName() + " is not supported"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-}