Package org.jpox.util

Source Code of org.jpox.util.StringUtils

/**********************************************************************
Copyright (c) 2003 Andy Jefferson and others. All rights reserved.
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.

Contributors:
2003 Erik Bengtson - moved replaceAll from Column class to here
2004 Andy Jefferson - moved intArrayToString, booleanArrayToString from SM
2007 Xuan Baldauf - toJVMIDString hex fix
    ...
**********************************************************************/
package org.jpox.util;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URLDecoder;
import java.util.Collection;
import java.util.Iterator;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.jar.JarFile;

/**
* Utilities for String manipulation.
*
* @version $Revision: 1.23 $  
**/
public class StringUtils
{
    /**
     * Convert an exception to a String with full stack trace
     * @param ex the exception
     * @return a String with the full stacktrace error text
     */
    public static String getStringFromStackTrace(Throwable ex)
    {
        if (ex==null)
        {
            return "";
        }
        StringWriter str = new StringWriter();
        PrintWriter writer = new PrintWriter(str);
        try
        {
            ex.printStackTrace(writer);
            return str.getBuffer().toString();
        }
        finally
        {
            try
            {
                str.close();
                writer.close();
            }
            catch (IOException e)
            {
                //ignore
            }
        }
    }
   
    /**
     * Convenience method to get a File for the specified filename.
     * Caters for URL-encoded characters in the filename (treatment of spaces on Windows etc)
     * @param filename Name of file
     * @return The File
     */
    public static File getFileForFilename(String filename)
    {
        return new File(getDecodedStringFromURLString(filename));
    }

    /**
     * Convenience method to get a JarFile for the specified filename.
     * Caters for URL-encoded characters in the filename (treatment of spaces on Windows etc)
     * @param filename Name of file
     * @return The JarFile
     */
    public static JarFile getJarFileForFilename(String filename)
    throws IOException
    {
        return new JarFile(getDecodedStringFromURLString(filename));
    }

    /**
     * Convenience method to decode a URL string for use (so spaces are allowed)
     * @param urlString The URL string
     * @return The string
     */
    public static String getDecodedStringFromURLString(String urlString)
    {
        return URLDecoder.decode(urlString);
    }

    /**
     * Replaces each substring of this string that matches toReplace.
     * Used to replace replaceAll when using J2SDK 1.3.1.
     * This method is available at String.replaceAll in J2SDK 1.4
     * @param theString The string to use
     * @param toReplace The string to replace.
     * @param replacement The replacement string.
     * @return The updated string after replacing.
     */
    public static String replaceAll(String theString, String toReplace, String replacement)
    {
        if (theString == null)
        {
            return null;
        }
        if (theString.indexOf(toReplace) == -1)
        {
            return theString;
        }

        StringBuffer stringBuffer = new StringBuffer(theString);
        int index = theString.length();
        int offset = toReplace.length();
        while ((index=theString.lastIndexOf(toReplace, index-1)) > -1)
        {
            stringBuffer.replace(index,index+offset, replacement);
        }

        return stringBuffer.toString();
    }

    /**
     * Utility to check if a string is whitespace.
     * If the string is null, returns true also.
     * @param str The string to check
     * @return Whether the string is just whitespace
     */
    public static boolean isWhitespace(String str)
    {
        return str==null || (str.trim().length()==0);
    }

    /**
     * Utility to tell if two strings are the same. Extends the basic
     * String 'equals' method by allowing for nulls.
     * @param str1 The first string
     * @param str2 The second string
     * @return Whether the strings are equal.
     */
    public static boolean areStringsEqual(String str1,String str2)
    {
        if (str1 == null && str2 == null)
        {
            return true;
        }
        else if (str1 == null && str2 != null)
        {
            return false;
        }
        else if (str1 != null && str2 == null)
        {
            return false;
        }
        else
        {
            return str1.equals(str2);
        }
    }

    /** Utility to return a left-aligned version of a string padded to the
     * number of characters specified.
     * @param input The input string
     * @param length The length desired
     * @return The updated string
     **/
    public static String leftAlignedPaddedString(String input,int length)
    {
        if (length <= 0)
        {
            return null;
        }

        StringBuffer output=new StringBuffer();
        char         space=' ';

        if (input != null)
        {
            if (input.length() < length)
            {
                output.append(input);
                for (int i=input.length();i<length;i++)
                {
                    output.append(space);
                }
            }
            else
            {
                output.append(input.substring(0,length));
            }
        }
        else
        {
            for (int i=0;i<length;i++)
            {
                output.append(space);
            }
        }

        return output.toString();
    }

    /** Utility to return a right-aligned version of a string padded to the
     * number of characters specified.
     * @param input The input string
     * @param length The length desired
     * @return The updated string
     **/
    public static String rightAlignedPaddedString(String input,int length)
    {
        if (length <= 0)
        {
            return null;
        }

        StringBuffer output=new StringBuffer();
        char         space=' ';

        if (input != null)
        {
            if (input.length() < length)
            {
                for (int i=input.length();i<length;i++)
                {
                    output.append(space);
                }
                output.append(input);
            }
            else
            {
                output.append(input.substring(0,length));
            }
        }
        else
        {
            for (int i=0;i<length;i++)
            {
                output.append(space);
            }
        }

        return output.toString();
    }
   
    /**
     * Splits a list of values separated by a token
     * @param valuesString the text to be splited
     * @param token the token
     * @return an array with all values
     */
    public static String[] split(String valuesString, String token)
    {
        String[] values;
        if (valuesString != null)
        {
            StringTokenizer tokenizer = new StringTokenizer(valuesString,token);

            values = new String[tokenizer.countTokens()];
            int count = 0;
            while (tokenizer.hasMoreTokens())
            {
                values[count++] = tokenizer.nextToken();
            }          
        }
        else
        {
            values = null;
        }
        return values;
    }

    /**
     * Utility to convert an object to a JVM type string.
     * Returns the same as would have been output from Object.toString() if the class hadn't overridden it.
     * @param obj The object
     * @return The String version
     **/
    public static String toJVMIDString(Object obj)
    {
        if (obj == null)
        {
            return "null";
        }
        else
        {
            return obj.getClass().getName() + '@' + Integer.toHexString(System.identityHashCode(obj)); // we should align to the Java VM way of printing identity hash codes, that means: hexadecimal
        }
    }

    /**
     * Utility to convert a boolean[] to a String.
     * @param ba The boolean[]
     * @return String version
     **/
    public static String booleanArrayToString(boolean[] ba)
    {
        if (ba == null)
        {
            return "null";
        }

        StringBuffer sb = new StringBuffer("[");
        for (int i=0; i<ba.length; ++i)
        {
            sb.append(ba[i] ? 'Y' : 'N');
        }
        sb.append(']');

        return sb.toString();
    }

    /**
     * Utility to convert an int[] to a String.
     * @param ia The int[]
     * @return String version
     **/
    public static String intArrayToString(int[] ia)
    {
        if (ia == null)
        {
            return "null";
        }

        StringBuffer sb = new StringBuffer("[");
        for (int i=0; i<ia.length; ++i)
        {
            if (i > 0)
            {
                sb.append(", ");
            }

            sb.append(ia[i]);
        }
        sb.append(']');

        return sb.toString();
    }

    /**
     * Utility to convert an Object[] to a String.
     * @param arr The Object[]
     * @return String version
     **/
    public static String objectArrayToString(Object[] arr)
    {
        if (arr == null)
        {
            return "null";
        }

        StringBuffer sb = new StringBuffer("[");
        for (int i=0; i<arr.length; ++i)
        {
            if (i > 0)
            {
                sb.append(", ");
            }
            sb.append(arr[i]);
        }
        sb.append(']');

        return sb.toString();
    }

    /**
     * Converts the given collection of objects to string as a comma-separated
     * list.  If the list is empty the string "&lt;none&gt;" is returned.
     *
     * @param coll collection of objects to be converted
     * @return  A string containing each object in the given collection,
     *          converted toString() and separated by commas.
     */
    public static String collectionToString(Collection coll)
    {
        if (coll.isEmpty())
        {
            return "<none>";
        }
        else
        {
            StringBuffer s = new StringBuffer();
            Iterator iter = coll.iterator();
            while (iter.hasNext())
            {
                if (s.length() > 0)
                {
                    s.append(", ");
                }

                s.append(iter.next());
            }

            return s.toString();
        }
    }

    /**
     * Utility to check if a name is a valid Java identifier.
     * Used by JDOQL in validating the names of parameters/variables.
     * @param s The name
     * @return Whether it is a valid identifier in Java.
     **/
    public static boolean isValidJavaIdentifierForJDOQL(String s)
    {
        int len = s.length();

        if (len < 1)
        {
            return false;
        }

        if (s.equals("this"))
        {
            // Use of "this" is restricted in JDOQL
            return false;
        }

        char[] c = new char[len];
        s.getChars(0, len, c, 0);

        if (!Character.isJavaIdentifierStart(c[0]))
        {
            return false;
        }

        for (int i = 1; i < len; ++i)
        {
            if (!Character.isJavaIdentifierPart(c[i]))
            {
                return false;
            }
        }

        return true;
    }

    /**
     * Convenience method to extract an integer property value from a Properties file.
     * @param props The Properties
     * @param propName Name of the property
     * @param defaultValue The default value to use (in case not specified)
     * @return The value
     */
    public static int getIntValueForProperty(Properties props, String propName, int defaultValue)
    {
        int value = defaultValue;
        if (props != null && props.containsKey(propName))
        {
            try
            {
                value = (new Integer(props.getProperty(propName))).intValue();
            }
            catch (NumberFormatException nfe)
            {
                // Do nothing
            }
        }
        return value;
    }
   
    /**
     * check string is null or length is 0.
     * @param s check string
     * @return return true if string is null or length is 0. return false other case.
     */
    public static boolean isEmpty(String s)
    {
        return ((s == null) || (s.length() == 0));
    }

    /**
     * check string isnot null and length > 0.
     * @param s check string
     * @return return true if string isnot null and length greater than 0. return false other case.
     */
    public static boolean notEmpty(String s)
    {
        return ((s != null) && (s.length() > 0));
    }   
}
TOP

Related Classes of org.jpox.util.StringUtils

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.