KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > tests > jfun > parsec > mssql > Encoder


1 /*
2  * Created on 2004-11-15
3  *
4  * Author Ben Yu
5  */

6 package tests.jfun.parsec.mssql;
7
8 /**
9  * Utility class that provides some common string encoding algorithm.
10  * @author Ben Yu
11  *
12  * 2004-11-15
13  */

14 public final class Encoder {
15   /**
16    * Encode a string to a T-Sql string literal.
17    * It replaces any single quote to two single quotes.
18    * The encoded string is quoted with single quotes.
19    * @param s the string to encode.
20    * @return the encoded string.
21    */

22   public static String JavaDoc encodeSqlString(final String JavaDoc s){
23     final StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
24     buf.append('\'');
25     for(int i=0; i<s.length(); i++){
26       final char c = s.charAt(i);
27       if(c=='\'') buf.append("''");
28       else buf.append(c);
29     }
30     buf.append('\'');
31     return buf.toString();
32   }
33   /**
34    * Encode a string to a c++/java style string literal.
35    * It escapes double quote and backslash with a backslash.
36    * The encoded string is quoted with double quotes.
37    * @param s the string to encode.
38    * @return the encoded string.
39    */

40   public static String JavaDoc encodeEscapedString(final String JavaDoc s){
41     final StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
42     buf.append('"');
43     for(int i=0; i<s.length(); i++){
44       final char c = s.charAt(i);
45       if(c=='\\' || c=='"')
46         buf.append('\\');
47       buf.append(c);
48     }
49     buf.append('"');
50     return buf.toString();
51   }
52   /**
53    * To encode a character to a c++/java style character literal.
54    * It escapes single quote and backslash with a backslash.
55    * The encoded string is quoted with single quotes.
56    * @param c the character to encode.
57    * @return the encoded string.
58    */

59   public static String JavaDoc encodeEscapedChar(final char c){
60     if(c=='\\' || c=='\'') return "\\"+c;
61     else return ""+c;
62   }
63 }
64
Popular Tags