FileDocCategorySizeDatePackage
PersistString.javaAPI DocExample2911Sat Sep 12 03:01:00 BST 1998borland.samples.apps.chess.client

PersistString.java

/*
 * Copyright (c) 1997-1998 Borland International, Inc. All Rights Reserved.
 * 
 * This SOURCE CODE FILE, which has been provided by Borland as part
 * of a Borland product for use ONLY by licensed users of the product,
 * includes CONFIDENTIAL and PROPRIETARY information of Borland.  
 *
 * USE OF THIS SOFTWARE IS GOVERNED BY THE TERMS AND CONDITIONS 
 * OF THE LICENSE STATEMENT AND LIMITED WARRANTY FURNISHED WITH
 * THE PRODUCT.
 *
 * IN PARTICULAR, YOU WILL INDEMNIFY AND HOLD BORLAND, ITS RELATED
 * COMPANIES AND ITS SUPPLIERS, HARMLESS FROM AND AGAINST ANY CLAIMS
 * OR LIABILITIES ARISING OUT OF THE USE, REPRODUCTION, OR DISTRIBUTION
 * OF YOUR PROGRAMS, INCLUDING ANY CLAIMS OR LIABILITIES ARISING OUT OF
 * OR RESULTING FROM THE USE, MODIFICATION, OR DISTRIBUTION OF PROGRAMS
 * OR FILES CREATED FROM, BASED ON, AND/OR DERIVED FROM THIS SOURCE
 * CODE FILE.
 */
package borland.samples.apps.chess.client;
import java.io.*;
import java.util.Vector;

/**re-invent the wheel: Concatenate an array of Strings in such a way that they can hold any data
* and be parsed back into the array of strings they were created from
* Simplifies passing multiparameter messages between client and server
*/
public class PersistString {
  static public String concat(String[] data ) {
    String retVal = "";
    for (int i=0;i < data.length && data[i] != null ;i++)
       retVal = retVal + i + "\"" + PersistString.padQuotes(data[i])+ "\"" ;
    return  retVal;
  }
  
  static public String [] parse(String infoData) {
    Vector output = new Vector(10);
    StringReader stream = new StringReader(infoData);
    //StringBufferInputStream stream  = new StringBufferInputStream(infoData);
    //StreamTokenizer st = new StreamTokenizer(new BufferedInputStream(stream, 1000));
    StreamTokenizer st = new StreamTokenizer(stream);

    try {
      st.nextToken();
      while(true) {
        String data = null;
        while (st.nextToken() == '"') {
          if (data == null)
            data = st.sval;
          else
            data = data + "\"" + st.sval;
        }
        output.addElement(data);
        if (st.ttype == StreamTokenizer.TT_EOF)
          break;
      }
    }
    catch (Exception e) {
      System.out.println("PersistStream error " + e);
    }
    String [] outputArray = new String [output.size()];
    for (int i=0;i<output.size();i++)
      outputArray[i] = (String) output.elementAt(i);
    return outputArray;
  }

  static String padQuotes(String data) {
    int index = 0 ;
    int oldIndex = 0;
    while (index >= 0) {
      index = data.indexOf('\"',oldIndex);
      if (index > 0) {
        data = data.substring(0,index) + "\"" + data.substring(index );
        //System.out.println ("Found a quote in the data " + data);
        oldIndex = index + 2;
      }
    }
    return data;
  }
}