home *** CD-ROM | disk | FTP | other *** search
/ The Net: Ultimate Internet Guide / WWLCD1.ISO / pc / java / dek17tau / classes / spt / util / stringutil.java < prev   
Encoding:
Java Source  |  1996-08-14  |  9.2 KB  |  356 lines

  1.  
  2. /*
  3.  * StringUtil.java
  4.  *
  5.  * Copyright (C) 1996 Shaun Terry. All Rights Reserved.
  6.  */
  7.  
  8. package spt.util;
  9.  
  10. import java.util.StringTokenizer;
  11. import java.util.Hashtable;
  12. import java.lang.String;
  13. import java.lang.StringBuffer;
  14. import java.lang.Integer;
  15. import java.lang.NumberFormatException;
  16. import java.lang.System;
  17. import java.io.InputStream;
  18. import java.io.DataInput;
  19. import java.io.DataOutput;
  20. import java.io.IOException;
  21. import java.io.File;
  22. import java.io.FileInputStream;
  23. import java.io.FileOutputStream;
  24. import java.awt.Color;
  25.  
  26.  
  27. /**
  28.  * A variety of String related utility functions.
  29.  *
  30.  * @author Shaun Terry
  31.  */
  32.  
  33. public class StringUtil {
  34.  
  35.     /** Convert a delimited String to an array of elements
  36.      *  using the specified delimiter set.
  37.      * @see java.util.StringTokenizer
  38.      */
  39.     static public String[] split(String s, String delimSet) {
  40.         StringTokenizer tok = new StringTokenizer(s, delimSet);
  41.         String s_array[] = new String[ tok.countTokens() ];
  42.         for (int i=0; tok.hasMoreTokens(); ++i) {
  43.             s_array[i] = tok.nextToken();
  44.         }
  45.         return s_array;
  46.     }
  47.  
  48.     /** Convert a pipe delimited String to an array of elements.
  49.      * @see java.util.StringTokenizer
  50.      */
  51.     static public String[] split(String s) {
  52.         return split(s, "|");
  53.     }
  54.  
  55.     /** Parse a String and return a Color. The following formats
  56.      *    are recognized: "#FFFFFF", "r,g,b" and one of a number
  57.      *    known case-independent strings (e.g. "red", "black", etc.).
  58.      * @see java.awt.Color
  59.      */
  60.     static public Color stringToColor(String s) {
  61.         if (s.startsWith("#")) {
  62.             // Formatted like #FFFFFF
  63.             try {
  64.                 int i = Integer.parseInt(s.substring(1), 16);
  65.                 return new Color((i>>16) & 0xFF, (i>>8) & 0xFF, i & 0xFF);
  66.             }
  67.             catch (NumberFormatException e) {
  68.                 return null;
  69.             }
  70.         }
  71.         else if (s.length() > 0 && s.charAt(0) >= '0' &&
  72.                                 s.charAt(0) <= '9') {
  73.             // Formatted like rrr,ggg,bbb
  74.             String rgb[] = StringUtil.split(s, ",");
  75.             if (rgb.length != 3) return null;
  76.             int c[] = new int[3];
  77.             for (int i=0; i < 3; ++i) {
  78.                 try {
  79.                     c[i] = Integer.parseInt(rgb[i].trim());
  80.                 }
  81.                 catch (NumberFormatException e) {
  82.                     return null;
  83.                 }
  84.             }
  85.             return new Color(c[0], c[1], c[2]);
  86.         }
  87.         else if (s.equalsIgnoreCase("white")) return Color.white;
  88.         else if (s.equalsIgnoreCase("lightGray")) return Color.lightGray;
  89.         else if (s.equalsIgnoreCase("gray")) return Color.gray;
  90.         else if (s.equalsIgnoreCase("darkGray")) return Color.darkGray;
  91.         else if (s.equalsIgnoreCase("red")) return Color.red;
  92.         else if (s.equalsIgnoreCase("pink")) return Color.pink;
  93.         else if (s.equalsIgnoreCase("yellow")) return Color.yellow;
  94.         else if (s.equalsIgnoreCase("green")) return Color.green;
  95.         else if (s.equalsIgnoreCase("magenta")) return Color.magenta;
  96.         else if (s.equalsIgnoreCase("cyan")) return Color.cyan;
  97.         else if (s.equalsIgnoreCase("orange")) return Color.orange;
  98.         else if (s.equalsIgnoreCase("black")) return Color.black;
  99.         else if (s.equalsIgnoreCase("blue")) return Color.blue;
  100.  
  101.         return null;
  102.     }
  103.  
  104.     /** Convert single string in CGI parameter format to an
  105.      *    array of 2 strings. The 0th element is the parameter name
  106.      *    and the 1st element is the parameter value.
  107.      * @see #cgiParams
  108.      */
  109.     static public String[] cgiParamToStrings(String s) {
  110.         s = s.replace('+', ' ');
  111.  
  112.         String sn[] = split(s, "=");
  113.         StringBuffer sb[] = new StringBuffer[2];
  114.  
  115.         for (int i=0; i < 2; ++i) {
  116.             sb[i] = new StringBuffer("");
  117.  
  118.             int j=0, k;
  119.             while ((k = sn[i].indexOf('%', j)) >= 0) {
  120.                 sb[i].append(sn[i].substring(j, k));
  121.                 try sb[i].append(
  122.                     (char) Integer.parseInt(sn[i].substring(k+1, k+3), 16));
  123.                 catch (NumberFormatException e) {}
  124.                 j = k + 3;
  125.             }
  126.             sb[i].append(sn[i].substring(j, sn[i].length()));
  127.         }
  128.  
  129.         sn[0] = sb[0].toString();
  130.         sn[1] = sb[1].toString();
  131.  
  132.         return sn;
  133.     }
  134.  
  135.     /** Read System.in and convert CGI-format parameters to a
  136.      *    Hashtable of name/value pairs. The length of the data to
  137.      *    be read is determined by the property
  138.      *    <strong>CONTENT_LENGTH</strong> (preferably) or, if not
  139.      *    present, by the number of bytes available to read.
  140.      * @see java.util.Hashtable
  141.      * @see java.lang.System#getProperty
  142.      */
  143.     static public Hashtable cgiParams() {
  144.         String s = System.getProperty("CONTENT_LENGTH", "0");
  145.         int cl;
  146.         try cl = Integer.parseInt(s);
  147.         catch (NumberFormatException e) { cl = 0; }
  148.  
  149.         // if no content length, this *should* work
  150.         if (cl == 0) {
  151.             try cl = System.in.available();
  152.             catch (IOException e) {}
  153.         }
  154.  
  155.         if (cl > 0) return cgiParams(cl);
  156.         else return null;
  157.     }
  158.  
  159.     /** Read System.in and convert CGI-format parameters to a
  160.      *    Hashtable of name/value pairs. The length of the data to
  161.      *    be read is determined by content_length.
  162.      * @see java.util.Hashtable
  163.      */
  164.     static public Hashtable cgiParams(int content_length) {
  165.         Hashtable hash = new Hashtable();
  166.  
  167.         char b[] = new char[content_length];
  168.  
  169.         for (int i=0; i < content_length; ++i) {
  170.             int c;
  171.             try c = System.in.read();
  172.             catch (IOException e) { continue; }
  173.             if (c < 0) { break; }
  174.             b[i] = (char) c;
  175.         }
  176.  
  177.         String p = new String(b);
  178.         String params[] = split(p, "&");
  179.  
  180.         String ss[] = new String[2];
  181.         for (int i=0; i < params.length; ++i) {
  182.             ss = cgiParamToStrings(params[i]);
  183.             hash.put(ss[0], ss[1]);
  184.         }
  185.  
  186.         return hash;
  187.     }
  188.  
  189.     /** Write a String to a DataOutput source. Strings are transmitted
  190.      *    as an int, the length, followed by the bytes of the String itself.
  191.      * @see java.io.DataOutput
  192.      */
  193.     static public void writeString(DataOutput d, String s) throws IOException {
  194.         d.writeInt(s.length());
  195.         d.writeBytes(s);
  196.     }
  197.  
  198.     /** Read a String from a DataInput source. The String must have
  199.      *    been sent by StringUtil.writeString.
  200.      * @see java.io.DataInput
  201.      */
  202.     static public String readString(DataInput d) throws IOException {
  203.         int len = d.readInt();
  204.         if (len == 0) return "";
  205.         byte b[] = new byte[len];
  206.         d.readFully(b);
  207.         return new String(b, 0);
  208.     }
  209.  
  210.     /** Convert a fractional String to it's decimal
  211.      *    equivalent. e.g. "2 1/4".
  212.      */
  213.     static public float fractionalToFloat(String s) throws NumberFormatException {
  214.         StringTokenizer tok = new StringTokenizer(s, " ");
  215.         float whole = 0;
  216.         if (!tok.hasMoreTokens()) throw new NumberFormatException();
  217.  
  218.         String p = tok.nextToken();
  219.         if (p.indexOf("/") < 0) {
  220.             whole = Float.valueOf(p).floatValue();
  221.             if (!tok.hasMoreTokens()) return whole;
  222.             p = tok.nextToken();
  223.         }
  224.  
  225.         StringTokenizer tok2 = new StringTokenizer(p, "/");
  226.         float frac = 0;
  227.         if (tok2.countTokens() != 2) throw new NumberFormatException();
  228.  
  229.         p = tok2.nextToken();
  230.         frac = Float.valueOf(p).floatValue();
  231.         p = tok2.nextToken();
  232.         frac /= Float.valueOf(p).floatValue();
  233.  
  234.         if (whole < 0) return whole - frac;
  235.         else return whole + frac;
  236.     }
  237.  
  238.     /** Create a string initialized with the contents of a file.
  239.      */
  240.     static public String stringFromFile(String file) throws IOException {
  241.         File f = new File(file);
  242.  
  243.         int len = (int) f.length();
  244.         if (len == 0) return "";
  245.  
  246.         byte b[] = new byte[len];
  247.  
  248.         FileInputStream is = new FileInputStream(f);
  249.  
  250.         is.read(b);
  251.  
  252.         String s = new String(b, 0);
  253.  
  254.         is.close();
  255.  
  256.         return s;
  257.     }
  258.  
  259.     /** Store a String in its own file.
  260.      */
  261.     static public void toFile(String s, String file) throws IOException {
  262.         FileOutputStream os = new FileOutputStream(file);
  263.  
  264.         byte b[] = new byte[s.length()];
  265.  
  266.         s.getBytes(0, s.length(), b, 0);
  267.  
  268.         os.write(b);
  269.  
  270.         os.close();
  271.     }
  272.  
  273.     /** Returns the index of the matching '{', '[' or '(' character
  274.      *    in the given String. The char to be matched must be in
  275.      *    position <code>startAt</code> in the string.
  276.      */
  277.     static public int indexOfMatched(String s, int startAt) {
  278.         int cnt=0;
  279.         char matchChar, c = s.charAt(startAt);
  280.  
  281.         if (c == '{') matchChar = '}';
  282.         else if (c == '[') matchChar = ']';
  283.         else /*if (c == '(')*/ matchChar = ')';
  284.  
  285.         for (int i=startAt+1; i < s.length(); ++i) {
  286.             if (s.charAt(i) == matchChar) {
  287.                 if (cnt == 0) return i;
  288.                 else --cnt;
  289.             }
  290.             else if (s.charAt(i) == c) ++cnt;
  291.         }
  292.  
  293.         return -1;
  294.     }
  295.  
  296.     /** Converts a String to a Hashtable. The String must have been
  297.      *    produced by Hastable.toString(). This method converts both
  298.      *    the <em>key</em> and <em>value</em> to objects of type String.
  299.      *    Useful for writing out Hashtables to permanent storage and then
  300.      *    reading them back in.<p>
  301.      *    Warning: This will fail miserably if any of the keys or values have
  302.      *    '=' chars in them.
  303.      * @see java.util.Hashtable#toString()
  304.      */
  305.     static public Hashtable hashtableFromString(String s) {
  306.         Hashtable h = new Hashtable();
  307.  
  308.         // 5 is the minimum length of a correctly formatted string
  309.         // (e.g. "{A=1}")
  310.         if (s.length() < 5) return h;
  311.  
  312.         int a=1, b;
  313.  
  314.         while (true) {
  315.             // Search for the next '='
  316.             b = s.indexOf('=', a);
  317.             String key = s.substring(a, b);
  318.  
  319.             a = b+1;
  320.  
  321.             if (s.charAt(a) == '{') {
  322.                 // This is a sub-list, parse it out and recursively call
  323.                 // ourself
  324.  
  325.                 b = indexOfMatched(s, a);
  326.                 h.put(key, hashtableFromString(s.substring(a, b+1)));
  327.  
  328.                 if (s.charAt(b+1) == '}') break;
  329.  
  330.                 a = b+3;
  331.                 continue;
  332.             }
  333.  
  334.             // Search for the last ',' before the next '=' (this way
  335.             // we can handle commas embedded in the string).
  336.             b = s.indexOf('=', a);
  337.  
  338.             // If there is no next ',' then we're at the end of the list
  339.             // so we just need to find the next '}'
  340.             if (b < 0) b = s.indexOf('}', a);
  341.             else b = s.lastIndexOf(',', b);
  342.  
  343.             String val = s.substring(a, b);
  344.  
  345.             h.put(key, val);
  346.  
  347.             if (s.charAt(b) == '}') break;
  348.  
  349.             a = b+2;
  350.         }
  351.  
  352.         return h;
  353.     }
  354. }
  355.  
  356.