[Mulgara-svn] r483 - branches/nw-interface/src/jar/util/java/org/mulgara/util

pag at mulgara.org pag at mulgara.org
Thu Oct 18 18:33:46 UTC 2007


Author: pag
Date: 2007-10-18 13:33:45 -0500 (Thu, 18 Oct 2007)
New Revision: 483

Modified:
   branches/nw-interface/src/jar/util/java/org/mulgara/util/StringUtil.java
Log:
Cleaned up formatting, added generics, and created a strackTraceToString method.

Modified: branches/nw-interface/src/jar/util/java/org/mulgara/util/StringUtil.java
===================================================================
--- branches/nw-interface/src/jar/util/java/org/mulgara/util/StringUtil.java	2007-10-17 16:46:02 UTC (rev 482)
+++ branches/nw-interface/src/jar/util/java/org/mulgara/util/StringUtil.java	2007-10-18 18:33:45 UTC (rev 483)
@@ -27,6 +27,8 @@
 
 package org.mulgara.util;
 
+import java.io.PrintWriter;
+import java.io.StringWriter;
 import java.util.*;
 
 /**
@@ -49,16 +51,10 @@
  */
 public class StringUtil {
 
-  /**
-   * Back slash and quote char used by {@link #quoteString(String)}.
-   *
-   */
+  /** Back slash and quote char used by {@link #quoteString(String)}. */
   private final static String TOKENS = "\\'";
 
-  /**
-   * Quote chars and space char used by {@link #parseString(String)}.
-   *
-   */
+  /** Quote chars and space char used by {@link #parseString(String)}. */
   private final static String SEPARATORS = "\\\"' ";
 
   /**
@@ -68,7 +64,7 @@
    * <code>"a.b"</code>.
    *
    * @param prefix  The string to get the prefix elements from.
-   * @param n  PARAMETER TO DO
+   * @param n  The number of prefix elements.
    * @return The first n prefix elements, or the original string if there
    *         weren't n elements. If n <= 0 an empty string is returned.
    */
@@ -76,24 +72,17 @@
 
     int dotIndex = 0;
 
-    if (n <= 0) {
+    if (n <= 0) return "";
 
-      return "";
-    }
-
     //Try to get all n elements.
     while (n > 0) {
 
       //May be more keep going
       if (dotIndex != -1) {
-
         dotIndex = prefix.indexOf(".", dotIndex + 1);
         n--;
-
         //Not enough
-      }
-      else {
-
+      } else {
         return prefix;
       }
     }
@@ -102,6 +91,7 @@
     return prefix.substring(0, dotIndex);
   }
 
+
   /**
    * Checks to see if a wildcard string pattern matches a string.
    *
@@ -114,109 +104,85 @@
    */
   public static boolean isMatch(String wildcardString, String matchString) {
 
-    //The portion of the string that has not been matched with the pattern.
+    // The portion of the string that has not been matched with the pattern.
     String notYetMatched = matchString;
 
-    //Tokenizer will throw away * characters.
+    // Tokenizer will throw away * characters.
     StringTokenizer strTok = new StringTokenizer(wildcardString, "*", false);
 
-    //Store the tokens
-    Vector tokens = new Vector();
+    // Store the tokens
+    Vector<String> tokens = new Vector<String>();
 
     String token = "";
 
     int matchIndex = -1;
 
-    //Always match same string.
-    if (wildcardString.equals(matchString)) {
+    // Always match same string.
+    if (wildcardString.equals(matchString)) return true;
 
-      return true;
-    }
+    // Never match empty string
+    // (if matchString is empty will return true above)
+    if (wildcardString.equals("")) return false;
 
-    //Never match empty string
-    //(if matchString is empty will return true above)
-    if (wildcardString.equals("")) {
+    // No wildcards and strings are not equal.
+    if (wildcardString.indexOf('*') == -1) return false;
 
-      return false;
-    }
+    // Get all the tokens
+    while (strTok.hasMoreTokens()) tokens.add(strTok.nextToken());
 
-    //No wildcards and strings are not equal.
-    if (wildcardString.indexOf('*') == -1) {
-
-      return false;
-    }
-
-    //Get all the tokens
-    while (strTok.hasMoreTokens()) {
-
-      tokens.add(strTok.nextToken());
-    }
-
-    //If there were characters to match - do they have to match the start or end?
+    // If there were characters to match - do they have to match the start or end?
     if (tokens.size() > 0) {
 
       if (!wildcardString.startsWith("*") &&
           !matchString.startsWith( (String) tokens.firstElement())) {
-
         return false;
       }
 
       if (!wildcardString.endsWith("*") &&
           !matchString.endsWith( (String) tokens.lastElement())) {
-
         return false;
       }
     }
 
-    //Loop through the tokens.
+    // Loop through the tokens.
     while (tokens.size() > 0) {
 
       token = (String) tokens.remove(0);
 
-      //Find the token
+      // Find the token
       matchIndex = notYetMatched.indexOf(token);
 
-      //Not found
-      if (matchIndex < 0) {
+      // Not found
+      if (matchIndex < 0) return false;
 
-        return false;
-      }
-
       //Reduce the not matched portion up to the end of the token  match.
       notYetMatched = notYetMatched.substring(matchIndex + token.length());
     }
 
-    //We matched all the tokens successfully.
+    // We matched all the tokens successfully.
     return true;
   }
 
+
   /**
    * Determines if the string is null or does not contain any characters.
    *
    * @param valueStr String that is to be checked
-       * @param allowSpaces boolean indicating whether empty spaces are valid or not
+   * @param allowSpaces boolean indicating whether empty spaces are valid or not
    * @return true if empty, false if not
    */
   public static boolean isEmpty(String valueStr, boolean allowSpaces) {
 
     boolean isEmpty = false;
 
-    if (valueStr == null) {
+    if (valueStr == null) isEmpty = true;
+    else if (valueStr.length() == 0) isEmpty = true;
+    else if (!allowSpaces && (valueStr.trim().length() == 0)) isEmpty = true;
 
-      isEmpty = true;
-    }
-    else if (valueStr.length() == 0) {
-
-      isEmpty = true;
-    }
-    else if (!allowSpaces && (valueStr.trim().length() == 0)) {
-
-      isEmpty = true;
-    }
-
     return isEmpty;
   }
 
+
   /**
    * Determines if the string is null or does not contain any characters
    *
@@ -228,8 +194,9 @@
     return isEmpty(valueStr, false);
   }
 
+
   /**
-       * Splits a String into a String array. The String is split at every separator
+   * Splits a String into a String array. The String is split at every separator
    * character. The separator characters do not appear in the String objects in
    * the String array.
    *
@@ -243,7 +210,6 @@
     String[] tokens = new String[st.countTokens()];
 
     for (int i = 0; i < tokens.length; ++i) {
-
       tokens[i] = st.nextToken();
     }
 
@@ -267,21 +233,16 @@
       String s = strings[i];
 
       // Add a separator.
-      if (i > 0) {
+      if (i > 0) sb.append(' ');
 
-        sb.append(' ');
-      }
-
       // Quote the URI if it contains a space or a quote.
-      if ( (s.indexOf(' ') != -1) ||
+      if ((s.indexOf(' ') != -1) ||
           (s.indexOf('"') != -1) ||
           (s.indexOf('\'') != -1) ||
           (s.indexOf('\\') != -1)) {
 
         sb.append(quoteString(s));
-      }
-      else {
-
+      } else {
         sb.append(s);
       }
     }
@@ -289,6 +250,7 @@
     return sb.toString();
   }
 
+
   /**
    * Quotes a String by enclosing it in single quotes and escaping all single
    * quotes and back slashes.
@@ -308,12 +270,11 @@
       String token = st.nextToken();
       char firstChar = token.charAt(0);
 
-      if ( (token.length() == 1) && (TOKENS.indexOf(firstChar) != -1)) {
+      if ((token.length() == 1) && (TOKENS.indexOf(firstChar) != -1)) {
 
         sb.append('\\');
         sb.append(firstChar);
-      }
-      else {
+      } else {
 
         // Token does not contain a back slash or quote char.
         sb.append(token);
@@ -325,6 +286,7 @@
     return sb.toString();
   }
 
+
   /**
    * Quotes a String by enclosing it in single quotes and escaping all single
    * quotes and back slashes.
@@ -344,11 +306,8 @@
       char firstChar = token.charAt(0);
 
       if (!escaped && (token.length() == 1) && (firstChar == '\\')) {
-
         escaped = true;
-      }
-      else {
-
+      } else {
         // Token does not contain a back slash or is an escaped back slash.
         sb.append(token);
         escaped = false;
@@ -358,6 +317,7 @@
     return sb.toString();
   }
 
+
   /**
    * Separates a String consisting of a space-separated list of substrings into
    * an array of Strings. Substrings in the input String may be quoted with
@@ -369,7 +329,7 @@
   public static String[] parseString(String string) {
 
     StringTokenizer st = new StringTokenizer(string.trim(), SEPARATORS, true);
-    List strings = new ArrayList();
+    List<String> strings = new ArrayList<String>();
     StringBuffer sb = new StringBuffer(string.length());
     boolean inQuotedString = false;
     boolean escaped = false;
@@ -388,47 +348,34 @@
         if (firstChar == ' ') {
 
           if (inQuotedString) {
-
             // Space in quoted string.
             sb.append(firstChar);
-          }
-          else if (sb.length() > 0) {
-
+          } else if (sb.length() > 0) {
             // Output string to List.
             strings.add(sb.toString());
             sb.setLength(0);
           }
-        }
-        else {
+        } else {
 
           if (inQuotedString) {
 
             if (firstChar == '\\') {
-
               // Escape the next character
               escaped = true;
-            }
-            else if (firstChar == quoteChar) {
-
+            } else if (firstChar == quoteChar) {
               // End quote.
               inQuotedString = false;
-            }
-            else {
-
+            } else {
               // Quote within quoted string.
               sb.append(firstChar);
             }
-          }
-          else {
-
+          } else {
             // Begin quote.
             quoteChar = firstChar;
             inQuotedString = true;
           }
         }
-      }
-      else {
-
+      } else {
         // Token does not contain a space or quote char.
         sb.append(token);
         escaped = false;
@@ -436,15 +383,15 @@
     }
 
     if (sb.length() > 0) {
-
       // Output final string to List.
       strings.add(sb.toString());
       sb.setLength(0);
     }
 
-    return (String[]) strings.toArray(new String[strings.size()]);
+    return strings.toArray(new String[strings.size()]);
   }
 
+
   /**
    * Quotes chars in the attribute value source string by replacing them with
    * the corresponding XML entities.
@@ -453,10 +400,10 @@
    * @param sb the StringBuffer to append to.
    */
   public static void quoteAV(String str, StringBuffer sb) {
-
     quoteXML(str, sb, "&<>'\"");
   }
 
+
   /**
    * Quotes chars in the attribute value source string by replacing them with
    * the corresponding XML entities.
@@ -472,6 +419,7 @@
     return sb.toString();
   }
 
+
   /**
    * Quotes chars in the CDATA source string by replacing them with the
    * corresponding XML entities.
@@ -480,10 +428,10 @@
    * @param sb the StringBuffer to append to.
    */
   public static void quoteCDATA(String str, StringBuffer sb) {
-
     quoteXML(str, sb, "&<");
   }
 
+
   /**
    * Quotes chars in the CDATA source string by replacing them with the
    * corresponding XML entities.
@@ -492,15 +440,15 @@
    * @return the quoted string.
    */
   public static String quoteCDATA(String str) {
-
     StringBuffer sb = new StringBuffer();
     quoteCDATA(str, sb);
 
     return sb.toString();
   }
 
+
   /**
-       * Removes a substring from a string. Only the first instance of the substring
+   * Removes a substring from a string. Only the first instance of the substring
    * will be removed. Returns the original string if it does not contain the
    * substring.
    *
@@ -521,29 +469,27 @@
       buffer.delete(beginIndex, endIndex);
 
       return buffer.toString();
-    }
-    else {
+    } else {
 
       return string;
     }
   }
 
+
   /**
    * Left justify a string, inserting newlines at appropriate places to get
    * lines approximately the requested length.
    *
-   * @param source PARAMETER TO DO
-   * @param width PARAMETER TO DO
-   * @return RETURNED VALUE TO DO
+   * @param source The string data to re-format.
+   * @param width The requested lenght of the lines.
+   * @return The re-formatted text.
    */
   public static String justifyLeft(String source, int width) {
 
     // Check for null param or string length less than given width, there is
     // nothing to do for these cases.
     if ( (source == null) || (source.length() <= width)) {
-
       return source;
-
       // Exit - nothing to do
     }
 
@@ -559,13 +505,11 @@
 
       // Keep track of the last whitespace seen.
       if (result.charAt(charPosition) == ' ') {
-
         lastSpace = charPosition;
       }
 
       // Restart counting if we find a newline already in the string.
       if (result.charAt(charPosition) == '\n') {
-
         lastSpace = -1;
         lineStart = charPosition + 1;
       }
@@ -575,14 +519,11 @@
 
         // Did we pass some whitespace on the way here?
         if (lastSpace != -1) {
-
           // Yes - set the last space to be a linefeed and reset counters
           result.setCharAt(lastSpace, '\n');
           lineStart = lastSpace + 1;
           lastSpace = -1;
-        }
-        else {
-
+        } else {
           // No - insert the linefeed right here, right now.
           result.insert(charPosition, '\n');
           lineStart = charPosition + 1;
@@ -595,6 +536,7 @@
     return result.toString();
   }
 
+
   /**
    * Substitutes text in inputStr from values in substituteArray.
    *
@@ -604,8 +546,7 @@
    * @return inputStr with tags replaced by the appropriate index from
    *      substituteArray.
    */
-  public static String substituteStrings(String inputStr,
-      String[] substituteArray) {
+  public static String substituteStrings(String inputStr, String[] substituteArray) {
 
     String resultStr = inputStr;
 
@@ -615,13 +556,12 @@
       // the array element.
       for (int tagInt = 0; tagInt < substituteArray.length; tagInt++) {
 
-        if ( (tagInt + 1) > 9) {
+        if ((tagInt + 1) > 9) {
 
           resultStr =
               replaceStringWithString(resultStr, "~" + (tagInt + 1),
               substituteArray[tagInt]);
-        }
-        else {
+        } else {
 
           resultStr =
               replaceStringWithString(resultStr, "~0" + (tagInt + 1),
@@ -639,15 +579,13 @@
    * @param sourceStr the string that contains the tokens
    * @param tokenStr the string that acts as the token to be replaced
    * @param replacementStr the string containing the value to be substituted
-   * @param ignoreCase boolean indicating whether to ignore the case during the
-   *      compare
+   * @param ignoreCase boolean indicating whether to ignore the case during the compare
    * @return String containing the string with all the values replaced
    */
   public static String replaceStringWithString(String sourceStr,
       String tokenStr, String replacementStr, boolean ignoreCase) {
 
-    if ( (sourceStr == null) || (tokenStr == null) || tokenStr.equals("")) {
-
+    if ((sourceStr == null) || (tokenStr == null) || tokenStr.equals("")) {
       return sourceStr;
     }
 
@@ -658,13 +596,11 @@
     int pos = 0;
 
     if (ignoreCase) {
-
       tokenStr = tokenStr.toUpperCase();
       indexStr = sourceStr.toUpperCase();
     }
 
-    while ( (tokenStrIndex = indexStr.indexOf(tokenStr, pos)) != -1) {
-
+    while ((tokenStrIndex = indexStr.indexOf(tokenStr, pos)) != -1) {
       resultStr.append(sourceStr.substring(pos, tokenStrIndex));
       resultStr.append(replacementStr);
       pos = tokenStrIndex + tokenStrLength;
@@ -675,6 +611,7 @@
     return resultStr.toString();
   }
 
+
   /**
    * Substitutes one value with another throughout the string
    *
@@ -683,12 +620,11 @@
    * @param replacementStr the string containing the value to be substituted
    * @return String containing the string with all the values replaced
    */
-  public static String replaceStringWithString(String sourceStr,
-      String tokenStr, String replacementStr) {
-
+  public static String replaceStringWithString(String sourceStr, String tokenStr, String replacementStr) {
     return replaceStringWithString(sourceStr, tokenStr, replacementStr, false);
   }
 
+
   /**
    * Quotes the specified chars in the source string by replacing them with the
    * corresponding XML entities.
@@ -706,61 +642,61 @@
       String token = st.nextToken();
       char firstCh = token.charAt(0);
 
-      if ( (token.length() == 1) && (chars.indexOf(firstCh) != -1)) {
+      if ((token.length() == 1) && (chars.indexOf(firstCh) != -1)) {
 
         switch (firstCh) {
 
           case '&':
             sb.append("&amp;");
-
             break;
 
           case '<':
             sb.append("&lt;");
-
             break;
 
           case '\'':
             sb.append("&apos;");
-
             break;
 
           case '"':
             sb.append("&quot;");
-
             break;
 
           case '>':
             sb.append("&gt;");
-
             break;
 
           default:
             sb.append(token);
-
             break;
         }
-      }
-      else {
+      } else {
 
         int pos;
 
         while ( (pos = token.indexOf("]]>")) != -1) {
+          if (pos > 0) sb.append(token.substring(0, pos));
 
-          if (pos > 0) {
-
-            sb.append(token.substring(0, pos));
-          }
-
           sb.append("]]&gt;");
           token = token.substring(pos + 3);
         }
 
-        if (token.length() > 0) {
-
-          sb.append(token);
-        }
+        if (token.length() > 0) sb.append(token);
       }
     }
   }
+
+
+  /**
+   * Returns a stack trace of a Throwable as a string, rather than the
+   * default behaviour of sending it to stderr.
+   * 
+   * @param t The Throwable containing the stack trace.
+   * @return A string containing the stack trace.
+   */
+  public static String strackTraceToString(Throwable t) {
+    StringWriter strWriter = new StringWriter();
+    t.printStackTrace(new PrintWriter(strWriter));
+    return strWriter.toString();
+  }
 }




More information about the Mulgara-svn mailing list