Package ptolemy.util

Class StringUtilities


  • public class StringUtilities
    extends java.lang.Object
    A collection of utilities for manipulating strings. These utilities do not depend on any other ptolemy packages.
    Since:
    Ptolemy II 2.1
    Version:
    $Id$
    Author:
    Christopher Brooks, Contributors: Teale Fristoe
    Pt.AcceptedRating:
    Green (cxh)
    Pt.ProposedRating:
    Green (eal)
    • Method Summary

      All Methods Static Methods Concrete Methods Deprecated Methods 
      Modifier and Type Method Description
      static java.lang.String abbreviate​(java.lang.String longName)
      Abbreviate a string.
      static void addDirectoryToJavaLibraryPath​(java.lang.String directoryName)
      Add a directory to the java.library.path directory..
      static void addPtolemyLibraryDirectoryToJavaLibraryPath()
      Add the $PTII/lib directory to the java.library.path directory.
      static java.lang.String ellipsis​(java.lang.String string, int length)
      Return a string with a maximum line length of length characters, limited to the given number of characters.
      static java.lang.String escapeForXML​(java.lang.String string)
      Given a string, replace all the instances of XML special characters with their corresponding XML entities.
      static java.lang.String escapeForXML​(java.lang.String string, boolean escapeLinebreaks)
      Given a string, replace all the instances of XML special characters with their corresponding XML entities.
      static java.lang.String escapeString​(java.lang.String string)
      Given a string, return a string that when fed to the Ptolemy expression parser, will turn into the argument string.
      static void exit​(int returnValue)
      If the ptolemy.ptII.exitAfterWrapup or the ptolemy.ptII.doNotExit properties are not set, then call System.exit().
      static java.lang.String getIndentPrefix​(int level)
      Return a number of spaces that is proportional to the argument.
      static java.lang.String getProperty​(java.lang.String propertyName)
      Get the specified property from the environment.
      static boolean inApplet()
      Return true if we are in an applet.
      static boolean isValidIdentifier​(java.lang.String name)
      Test whether a string is a valid Java identifier.
      static void mergePropertiesFile()
      Merge the properties in lib/ptII.properties with the current properties.
      static java.lang.String objectToSourceFileName​(java.lang.Object object)
      Return a string representing the name of the file expected to contain the source code for the specified object.
      static java.lang.String preferencesDirectory()
      Return the preferences directory, creating it if necessary.
      static java.lang.String propertiesFileName()
      Return the name of the properties file.
      static java.util.LinkedList<java.lang.String> readLines​(java.lang.String lines)
      Return a LinkedList of the lines in a string that aren't comments.
      static java.lang.String sanitizeName​(java.lang.String name)
      Sanitize a String so that it can be used as a Java identifier.
      static java.lang.String split​(java.lang.String longName)
      If the string is longer than 79 characters, split it up by adding newlines in all newline delimited substrings that are longer than 79 characters.
      static java.lang.String split​(java.lang.String longName, int length)
      If the string is longer than length characters, split the string up by adding newlines in all newline delimited substrings that are longer than length characters.
      static java.net.URL stringToURL​(java.lang.String name, java.net.URI baseDirectory, java.lang.ClassLoader classLoader)
      Deprecated.
      Use FileUtilities.nameToURL instead.
      static java.lang.String substitute​(java.lang.String string, java.lang.String pattern, java.lang.String replacement)
      Replace all occurrences of pattern in the specified string with replacement.
      static java.lang.String substituteFilePrefix​(java.lang.String prefix, java.lang.String string, java.lang.String replacement)
      Perform file prefix substitution.
      static java.lang.String[] tokenizeForExec​(java.lang.String inputString)
      Tokenize a String to an array of Strings for use with Runtime.exec(String []).
      static java.lang.String truncateString​(java.lang.String string, int lineLength, int numberOfLines)
      Return a string with a maximum line length of lineLength and a maximum number of lines numberOfLines.
      static java.lang.String unescapeForXML​(java.lang.String string)
      Given a string, replace all the instances of XML entities with their corresponding XML special characters.
      static java.lang.String usageString​(java.lang.String commandTemplate, java.lang.String[][] commandOptions, java.lang.String[] commandFlags)
      Return a string that contains a description of how to use a class that calls this method.
      static java.lang.String usageString​(java.lang.String commandTemplate, java.lang.String[][] commandOptions, java.lang.String[][] commandFlagsWithDescriptions)
      Return a string that contains a description of how to use a class that calls this method.
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    • Field Detail

      • ELLIPSIS_LENGTH_LONG

        public static final int ELLIPSIS_LENGTH_LONG
        Maximum length in characters of a long string before ellipsis(String, int) truncates and add a trailing ". . .". This variable is used by callers of ellipsis(String, int).
        See Also:
        Constant Field Values
      • ELLIPSIS_LENGTH_SHORT

        public static final int ELLIPSIS_LENGTH_SHORT
        Maximum length in characters of a short string before ellipsis(String, int) truncates and add a trailing ". . .". This variable is used by callers of ellipsis(String, int).
        See Also:
        Constant Field Values
      • LINE_SEPARATOR

        public static final java.lang.String LINE_SEPARATOR
        The line separator string. Under Windows, this would be "\r\n"; under Unix, "\n"; Under Macintosh, "\r".
      • PREFERENCES_DIRECTORY

        public static final java.lang.String PREFERENCES_DIRECTORY
        Location of Application preferences such as the user library. This field is not final in case other applications want to set it to a different directory.
        See Also:
        preferencesDirectory(), Constant Field Values
    • Method Detail

      • abbreviate

        public static java.lang.String abbreviate​(java.lang.String longName)
        Abbreviate a string. If the string is longer than 80 characters, truncate it by displaying the first 37 chars, then ". . .", then the last 38 characters. If the longName argument is null, then the string ">Unnamed<" is returned.
        Parameters:
        longName - The string to be abbreviated.
        Returns:
        The possibly abbreviated name.
        See Also:
        split(String)
      • addDirectoryToJavaLibraryPath

        public static void addDirectoryToJavaLibraryPath​(java.lang.String directoryName)
                                                  throws java.io.IOException
        Add a directory to the java.library.path directory.. The java.library.path directory determines where the JVM looks for native shared libraries. It is typically read once when the JVM is started and no longer read after that.

        This code may only work on certain JVMs

        Based on code from http://forums.sun.com/thread.jspa?threadID=707176 and http://stackoverflow.com/questions/5419039/is-djava-library-path-equivalent-to-system-setpropertyjava-library-path

        Parameters:
        directoryName - The directory to be added.
        Throws:
        java.io.IOException - If there are insufficient permissions to get set the java.library.path environment variable or there is no such field as usr_paths in the ClassLoader.
      • addPtolemyLibraryDirectoryToJavaLibraryPath

        public static void addPtolemyLibraryDirectoryToJavaLibraryPath()
                                                                throws java.io.IOException
        Add the $PTII/lib directory to the java.library.path directory. The java.library.path directory determines where the JVM looks for native shared libraries. It is typically read once when the JVM is started and no longer read after that.

        This code may only work on certain JVMs

        Throws:
        java.io.IOException - If there are insufficient permissions to get set the java.library.path environment variable or there is no such field as usr_paths in the ClassLoader.
      • ellipsis

        public static java.lang.String ellipsis​(java.lang.String string,
                                                int length)
        Return a string with a maximum line length of length characters, limited to the given number of characters. If there are more than 10 newlines, then the string is truncated after 10 lines. If the string is truncated, an ellipsis (three periods in a row: "...") will be appended to the end of the string. Lines that are longer than 160 characters are split into lines that are shorter than 160 characters.
        Parameters:
        string - The string to truncate.
        length - The number of characters to which to truncate the string.
        Returns:
        The possibly truncated string with ellipsis possibly added.
      • escapeForXML

        public static java.lang.String escapeForXML​(java.lang.String string)
        Given a string, replace all the instances of XML special characters with their corresponding XML entities. This is necessary to allow arbitrary strings to be encoded within XML.

        In this method, we make the following translations:

          & becomes &amp;
          " becomes &quot;
          < becomes &lt;
          > becomes &gt;
          newline becomes &#10;
          carriage return becomes $amp;#13;
          
        Parameters:
        string - The string to escape.
        Returns:
        A new string with special characters replaced.
        See Also:
        unescapeForXML(String)
      • escapeForXML

        public static java.lang.String escapeForXML​(java.lang.String string,
                                                    boolean escapeLinebreaks)
        Given a string, replace all the instances of XML special characters with their corresponding XML entities. This is necessary to allow arbitrary strings to be encoded within XML.

        In this method, we make the following translations:

          & becomes &amp;
          " becomes &quot;
          < becomes &lt;
          > becomes &gt;
          newline becomes &#10;, if requested.
          carriage return becomes $amp;#13;, if requested.
          
        Parameters:
        string - The string to escape.
        string - Whether or not to escape line break characters.
        Returns:
        A new string with special characters replaced.
        See Also:
        unescapeForXML(String)
      • escapeString

        public static java.lang.String escapeString​(java.lang.String string)
        Given a string, return a string that when fed to the Ptolemy expression parser, will turn into the argument string. That is, replace all the instances of backslashes with double backslashes, all quotation marks with \", etc. For example
          x"y becomes x\"y;
          x\"y becomes x\\\"y;
          x\y"z becomes x\\y\"z;
          x\\y\"z becomes x\\\\y\\\"
          
        Similarly, this method replaces the following characters exactly as defined in Java strings: \n, \t, \b, \r, and \f.
        Parameters:
        string - The string to escape.
        Returns:
        A new string with that can be put between quotation marks.
      • exit

        public static void exit​(int returnValue)
        If the ptolemy.ptII.exitAfterWrapup or the ptolemy.ptII.doNotExit properties are not set, then call System.exit(). Ptolemy code should call this method instead of directly calling System.exit() so that we can test code that would usually exit.
        Parameters:
        returnValue - The return value of this process, where non-zero values indicate an error.
      • getIndentPrefix

        public static java.lang.String getIndentPrefix​(int level)
        Return a number of spaces that is proportional to the argument. If the argument is negative or zero, return an empty string.
        Parameters:
        level - The level of indenting represented by the spaces.
        Returns:
        A string with zero or more spaces.
      • getProperty

        public static java.lang.String getProperty​(java.lang.String propertyName)
        Get the specified property from the environment. An empty string is returned if the property named by the "propertyName" argument environment variable does not exist, though if certain properties are not defined, then we make various attempts to determine them and then set them. See the javadoc page for java.util.System.getProperties() for a list of system properties.

        The following properties are handled specially

        "ptolemy.ptII.dir"
        vergil usually sets the ptolemy.ptII.dir property to the value of $PTII. However, if we are running under Web Start, then this property might not be set, in which case we look for "ptolemy/util/StringUtilities.class" and set the property accordingly.
        "ptolemy.ptII.dirAsURL"
        Return $PTII as a URL. For example, if $PTII was c:\ptII, then return file:/c:/ptII/.
        "user.dir"
        Return the canonical path name to the current working directory. This is necessary because under Windows with JDK1.4.1, the System.getProperty() call returns c:/foo whereas most of the other methods that operate on path names return C:/foo.
        Parameters:
        propertyName - The name of property.
        Returns:
        A String containing the string value of the property. If the property is not found, then we return the empty string.
      • inApplet

        public static boolean inApplet()
        Return true if we are in an applet.
        Returns:
        True if we are running in an applet.
      • isValidIdentifier

        public static boolean isValidIdentifier​(java.lang.String name)
        Test whether a string is a valid Java identifier. Section 3.8 of the Java language spec says:
        "An identifier is an unlimited-length sequence of Java letters and Java digits, the first of which must be a Java letter. An identifier cannot have the same spelling (Unicode character sequence) as a keyword (3.9), boolean literal (3.10.3), or the null literal (3.10.7)."
        Java characters are A-Z, a-z, $ and _.

        Characters that are not permitted in a Java identifier are changed to underscores. This method does not check whether the string is a keyword or literal.

        Parameters:
        name - The name to be checked.
        Returns:
        True if the given name is a valid Java identifier, or false otherwise.
      • mergePropertiesFile

        public static void mergePropertiesFile()
                                        throws java.io.IOException
        Merge the properties in lib/ptII.properties with the current properties. lib/ptII.properties is searched for in the classpath. The value of properties listed in lib/ptII.properties do not override properties with the same name in the current properties.
        Throws:
        java.io.IOException - If thrown while looking for the $CLASSPATH/lib/ptII.properties file.
      • objectToSourceFileName

        public static java.lang.String objectToSourceFileName​(java.lang.Object object)
        Return a string representing the name of the file expected to contain the source code for the specified object. This method simply replaces "." with "/" and appends ".java" to the class name.
        Parameters:
        object - The object.
        Returns:
        The expected source file name.
      • preferencesDirectory

        public static java.lang.String preferencesDirectory()
                                                     throws java.io.IOException
        Return the preferences directory, creating it if necessary. If the PTOLEMYII_DOT environment variable is set, then that value is used, otherwise the Java user.home property is used The PTOLEMYII_DOT environment variable is used to support invoking multiple Kepler processes.
        Returns:
        A string naming the preferences directory. The last character of the string will have the file.separator character appended.
        Throws:
        java.io.IOException - If the directory could not be created.
        See Also:
        PREFERENCES_DIRECTORY
      • propertiesFileName

        public static java.lang.String propertiesFileName()
                                                   throws java.io.IOException
        Return the name of the properties file. The properties file is a file of a format suitable for java.util.properties.load(InputStream). The file is named "ptII.properties" and is found in the PREFERENCES_DIRECTORY directory that is returned by preferencesDirectory(). Typically, this value is "$HOME/.ptolemyII/ptII.properties".
        Returns:
        The name of the properties file.
        Throws:
        java.io.IOException - If preferencesDirectory() throws it.
        See Also:
        preferencesDirectory(), PREFERENCES_DIRECTORY
      • readLines

        public static java.util.LinkedList<java.lang.String> readLines​(java.lang.String lines)
                                                                throws java.io.IOException
        Return a LinkedList of the lines in a string that aren't comments.
        Parameters:
        lines - A String containing the lines to be separated.
        Returns:
        A LinkedList of the lines that aren't comments.
        Throws:
        java.io.IOException - If thrown when reading from the input String.
      • sanitizeName

        public static java.lang.String sanitizeName​(java.lang.String name)
        Sanitize a String so that it can be used as a Java identifier. Section 3.8 of the Java language spec says:
        "An identifier is an unlimited-length sequence of Java letters and Java digits, the first of which must be a Java letter. An identifier cannot have the same spelling (Unicode character sequence) as a keyword (3.9), boolean literal (3.10.3), or the null literal (3.10.7)."
        Java characters are A-Z, a-z, $ and _.

        Characters that are not permitted in a Java identifier are changed to underscores. This method does not check that the returned string is a keyword or literal. Note that two different strings can sanitize to the same string. This method is commonly used during code generation to map the name of a ptolemy object to a valid identifier name.

        Parameters:
        name - A string with spaces and other characters that cannot be in a Java name.
        Returns:
        A String that follows the Java identifier rules.
      • split

        public static java.lang.String split​(java.lang.String longName)
        If the string is longer than 79 characters, split it up by adding newlines in all newline delimited substrings that are longer than 79 characters. If the longName argument is null, then the string ">Unnamed<" is returned.
        Parameters:
        longName - The string to optionally split up
        Returns:
        Either the original string, or the string with newlines inserted.
        See Also:
        abbreviate(String), split(String, int)
      • split

        public static java.lang.String split​(java.lang.String longName,
                                             int length)
        If the string is longer than length characters, split the string up by adding newlines in all newline delimited substrings that are longer than length characters. If the longName argument is null, then the string ">Unnamed<" is returned.
        Parameters:
        longName - The string to optionally split.
        length - The maximum length of the sequence of characters before a newline is inserted.
        Returns:
        Either the original string, or the string with newlines inserted.
        See Also:
        abbreviate(String), split(String)
      • stringToURL

        @Deprecated
        public static java.net.URL stringToURL​(java.lang.String name,
                                               java.net.URI baseDirectory,
                                               java.lang.ClassLoader classLoader)
                                        throws java.io.IOException
        Deprecated.
        Use FileUtilities.nameToURL instead.
        Given a file or URL name, return as a URL. If the file name is relative, then it is interpreted as being relative to the specified base directory. If the name begins with "xxxxxxCLASSPATHxxxxxx" or "$CLASSPATH" then search for the file relative to the classpath. Note that this is the value of the globally defined constant $CLASSPATH available in the expression language. If no file is found, then throw an exception.
        Parameters:
        name - The name of a file or URL.
        baseDirectory - The base directory for relative file names, or null to specify none.
        classLoader - The class loader to use to locate system resources, or null to use the system class loader.
        Returns:
        A URL, or null if no file name or URL has been specified.
        Throws:
        java.io.IOException - If the file cannot be read, or if the file cannot be represented as a URL (e.g. System.in), or the name specification cannot be parsed.
        java.net.MalformedURLException - If the URL is malformed.
      • substitute

        public static java.lang.String substitute​(java.lang.String string,
                                                  java.lang.String pattern,
                                                  java.lang.String replacement)
        Replace all occurrences of pattern in the specified string with replacement. Note that the pattern is NOT a regular expression, and that relative to the String.replaceAll() method in jdk1.4, this method is extremely slow. This method does not work well with back slashes.
        Parameters:
        string - The string to edit.
        pattern - The string to replace.
        replacement - The string to replace it with.
        Returns:
        A new string with the specified replacements.
      • substituteFilePrefix

        public static java.lang.String substituteFilePrefix​(java.lang.String prefix,
                                                            java.lang.String string,
                                                            java.lang.String replacement)
        Perform file prefix substitution. If string starts with prefix, then we return a new string that consists of the value or replacement followed by the value of string with the value of prefix removed. For example, substituteFilePrefix("c:/ptII", "c:/ptII/ptolemy, "$PTII") will return "$PTII/ptolemy"

        If prefix is not a simple prefix of string, then we use the file system to find the canonical names of the files. For this to work, prefix and string should name files that exist, see java.io.File.getCanonicalFile() for details.

        If prefix is not a prefix of string, then we return string

        Parameters:
        prefix - The prefix string, for example, "c:/ptII".
        string - The string to be substituted, for example, "c:/ptII/ptolemy".
        replacement - The replacement to be substituted in, for example, "$PTII"
        Returns:
        The possibly substituted string.
      • tokenizeForExec

        public static java.lang.String[] tokenizeForExec​(java.lang.String inputString)
                                                  throws java.io.IOException
        Tokenize a String to an array of Strings for use with Runtime.exec(String []).

        Lines that begin with an octothorpe '#' are ignored. Substrings that start and end with a double quote are considered to be a single token and are returned as a single array element.

        Parameters:
        inputString - The String to tokenize
        Returns:
        An array of substrings.
        Throws:
        java.io.IOException - If StreamTokenizer.nextToken() throws it.
      • truncateString

        public static java.lang.String truncateString​(java.lang.String string,
                                                      int lineLength,
                                                      int numberOfLines)
        Return a string with a maximum line length of lineLength and a maximum number of lines numberOfLines. Each line that exceeds the line length is replaced with a line that ends with "...". If the number of lines exceeds numberOfLines, then the returned string will have exactly numberOfLines lines where the last line is "...".
        Parameters:
        string - The string to truncate.
        lineLength - The number of characters to which to truncate each line.
        numberOfLines - The maximum number of lines.
        Returns:
        The possibly truncated string with ellipsis possibly added.
      • unescapeForXML

        public static java.lang.String unescapeForXML​(java.lang.String string)
        Given a string, replace all the instances of XML entities with their corresponding XML special characters. This is necessary to allow arbitrary strings to be encoded within XML.

        In this method, we make the following translations:

          &amp; becomes &
          &quot; becomes "
          &lt; becomes <
          &gt; becomes >
          &#10; becomes newline
          &#13; becomes carriage return
          
        Parameters:
        string - The string to escape.
        Returns:
        A new string with special characters replaced.
        See Also:
        escapeForXML(String)
      • usageString

        public static java.lang.String usageString​(java.lang.String commandTemplate,
                                                   java.lang.String[][] commandOptions,
                                                   java.lang.String[] commandFlags)
        Return a string that contains a description of how to use a class that calls this method. For example, this method is called by "$PTII/bin/vergil -help".
        Parameters:
        commandTemplate - A string naming the command and the format of the arguments, for example "moml [options] [file . . .]"
        commandOptions - A 2xN array of Strings that list command-line options that take arguments where the first element is a String naming the command line option, and the second element is the argument, for example {"-class", "<classname>")
        commandFlags - An array of Strings that list command-line options that are either present or not.
        Returns:
        A string that describes the command.
      • usageString

        public static java.lang.String usageString​(java.lang.String commandTemplate,
                                                   java.lang.String[][] commandOptions,
                                                   java.lang.String[][] commandFlagsWithDescriptions)
        Return a string that contains a description of how to use a class that calls this method. For example, this method is called by "$PTII/bin/vergil -help".
        Parameters:
        commandTemplate - A string naming the command and the format of the arguments, for example "moml [options] [file . . .]"
        commandOptions - A 2xN array of Strings that list command-line options that take arguments where the first element is a String naming the command line option, and the second element is the argument, for example {"-class", "<classname>")
        commandFlagsWithDescriptions - A 2xM array of Strings that list command-line options that are either present or not and a description of what the command line option does.
        Returns:
        A string that describes the command.