KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > h2 > util > StringUtils


1 /*
2  * Copyright 2004-2006 H2 Group. Licensed under the H2 License, Version 1.0 (http://h2database.com/html/license.html).
3  * Initial Developer: H2 Group
4  */

5 package org.h2.util;
6
7 import java.io.UnsupportedEncodingException JavaDoc;
8 import java.net.URLEncoder JavaDoc;
9 import java.sql.SQLException JavaDoc;
10 import java.text.ParseException JavaDoc;
11 import java.text.SimpleDateFormat JavaDoc;
12 import java.util.ArrayList JavaDoc;
13 import java.util.Date JavaDoc;
14 import java.util.Locale JavaDoc;
15 import java.util.TimeZone JavaDoc;
16
17 import org.h2.engine.Constants;
18 import org.h2.message.Message;
19
20 /**
21  * @author Thomas
22  */

23
24 public class StringUtils {
25
26     // TODO hack for gcj
27
//#GCJHACK private static final Class[] gcjClasses = {
28
//#GCJHACK gnu.gcj.convert.Input_ASCII.class,
29
//#GCJHACK gnu.gcj.convert.Input_UTF8.class,
30
//#GCJHACK gnu.gcj.convert.Input_8859_1.class,
31
//#GCJHACK gnu.gcj.convert.Output_ASCII.class,
32
//#GCJHACK gnu.gcj.convert.Output_UTF8.class,
33
//#GCJHACK gnu.gcj.convert.UnicodeToBytes.class,
34
//#GCJHACK gnu.gcj.convert.BytesToUnicode.class,
35
//#GCJHACK gnu.java.locale.Calendar.class,
36
//#GCJHACK gnu.java.locale.LocaleInformation.class,
37
//#GCJHACK gnu.java.locale.LocaleInformation_de.class,
38
//#GCJHACK java.util.GregorianCalendar.class,
39
//#GCJHACK };
40

41     public static boolean equals(String JavaDoc a, String JavaDoc b) {
42         if(a==null) {
43             return b==null;
44         }
45         return a.equals(b);
46     }
47     
48     public static String JavaDoc toUpperEnglish(String JavaDoc s) {
49         return s.toUpperCase(Locale.ENGLISH);
50     }
51     
52     public static String JavaDoc toLowerEnglish(String JavaDoc s) {
53         return s.toLowerCase(Locale.ENGLISH);
54     }
55
56     public static String JavaDoc getDefaultCharset() {
57         return System.getProperty("file.encoding");
58     }
59
60     public static String JavaDoc quoteStringSQL(String JavaDoc s) {
61         StringBuffer JavaDoc buff = new StringBuffer JavaDoc(s.length()+2);
62         buff.append('\'');
63         for (int i = 0; i < s.length(); i++) {
64             char c = s.charAt(i);
65             if (c == '\'') {
66                 buff.append(c);
67             } else if(c < ' ' || c > 127) {
68                 // need to start from the beginning because maybe there was a \ that was not quoted
69
return "STRINGDECODE(" + quoteStringSQL(javaEncode(s)) + ")";
70             }
71             buff.append(c);
72         }
73         buff.append('\'');
74         return buff.toString();
75     }
76
77     public static String JavaDoc javaEncode(String JavaDoc s) {
78         StringBuffer JavaDoc buff = new StringBuffer JavaDoc(s.length());
79         for (int i = 0; i < s.length(); i++) {
80             char c = s.charAt(i);
81             switch (c) {
82 // case '\b':
83
// // BS backspace
84
// // not supported in properties files
85
// buff.append("\\b");
86
// break;
87
case '\t':
88                 // HT horizontal tab
89
buff.append("\\t");
90                 break;
91             case '\n':
92                 // LF linefeed
93
buff.append("\\n");
94                 break;
95             case '\f':
96                 // FF form feed
97
buff.append("\\f");
98                 break;
99             case '\r':
100                 // CR carriage return
101
buff.append("\\r");
102                 break;
103             case '"':
104                 // double quote
105
buff.append("\\\"");
106                 break;
107             case '\\':
108                 // backslash
109
buff.append("\\\\");
110                 break;
111             default:
112                 int ch = (c & 0xffff);
113                 if (ch >= ' ' && (ch < 0x80)) {
114                     buff.append(c);
115                 // not supported in properties files
116
// } else if(ch < 0xff) {
117
// buff.append("\\");
118
// // make sure it's three characters (0x200 is octal 1000)
119
// buff.append(Integer.toOctalString(0x200 | ch).substring(1));
120
} else {
121                     buff.append("\\u");
122                     // make sure it's four characters
123
buff.append(Integer.toHexString(0x10000 | ch).substring(1));
124                 }
125             }
126         }
127         return buff.toString();
128     }
129
130     public static String JavaDoc addAsterix(String JavaDoc s, int index) {
131         if (s != null && index < s.length()) {
132             s = s.substring(0, index) + "[*]" + s.substring(index);
133         }
134         return s;
135     }
136
137     private static SQLException JavaDoc getFormatException(String JavaDoc s, int i) {
138         return Message.getSQLException(Message.STRING_FORMAT_ERROR_1, addAsterix(s, i));
139     }
140
141     public static String JavaDoc javaDecode(String JavaDoc s) throws SQLException JavaDoc {
142         StringBuffer JavaDoc buff = new StringBuffer JavaDoc(s.length());
143         for (int i = 0; i < s.length(); i++) {
144             char c = s.charAt(i);
145             if(c == '"') {
146                 break;
147             } else if(c=='\\') {
148                 if(i >= s.length()) {
149                     throw getFormatException(s, s.length()-1);
150                 }
151                 c = s.charAt(++i);
152                 switch(c) {
153                 case 't':
154                     buff.append('\t');
155                     break;
156                 case 'r':
157                     buff.append('\r');
158                     break;
159                 case 'n':
160                     buff.append('\n');
161                     break;
162                 case 'b':
163                     buff.append('\b');
164                     break;
165                 case 'f':
166                     buff.append('\f');
167                     break;
168                 case '"':
169                     buff.append('"');
170                     break;
171                 case '\\':
172                     buff.append('\\');
173                     break;
174                 case 'u': {
175                     try {
176                         c = (char)(Integer.parseInt(s.substring(i+1, i+5), 16));
177                     } catch(NumberFormatException JavaDoc e) {
178                         throw getFormatException(s, i);
179                     }
180                     i += 4;
181                     buff.append(c);
182                     break;
183                 }
184                 default:
185                     if(c >= '0' && c <= '9') {
186                         try {
187                             c = (char)(Integer.parseInt(s.substring(i, i+3), 8));
188                         } catch(NumberFormatException JavaDoc e) {
189                             throw getFormatException(s, i);
190                         }
191                         i += 2;
192                         buff.append(c);
193                     } else {
194                         throw getFormatException(s, i);
195                     }
196                 }
197             } else {
198                 buff.append(c);
199             }
200         }
201         return buff.toString();
202     }
203
204     public static String JavaDoc quoteJavaString(String JavaDoc s) {
205         if(s==null) {
206             return "null";
207         } else {
208             return "\"" + javaEncode(s) + "\"";
209         }
210     }
211
212     public static byte[] utf8Encode(String JavaDoc s) throws SQLException JavaDoc {
213         try {
214             // TODO UTF8: String.getBytes("UTF-8") only returns 1 byte for 0xd800-0xdfff
215
return s.getBytes(Constants.UTF8);
216         } catch (UnsupportedEncodingException JavaDoc e) {
217             throw Message.convert(e);
218         }
219     }
220
221     public static String JavaDoc utf8Decode(byte[] utf8) {
222         try {
223             return new String JavaDoc(utf8, Constants.UTF8);
224         } catch (UnsupportedEncodingException JavaDoc e) {
225             throw Message.convertToInternal(e);
226         }
227     }
228
229     public static String JavaDoc utf8Decode(byte[] bytes, int offset, int length) {
230         try {
231             return new String JavaDoc(bytes, offset, length, Constants.UTF8);
232         } catch (UnsupportedEncodingException JavaDoc e) {
233             throw Message.convertToInternal(e);
234         }
235     }
236
237     public static String JavaDoc quoteJavaStringArray(String JavaDoc[] array) {
238         if(array == null) {
239             return "null";
240         }
241         StringBuffer JavaDoc buff = new StringBuffer JavaDoc();
242         buff.append("new String[]{");
243         for(int i=0; i<array.length; i++) {
244             if(i>0) {
245                 buff.append(", ");
246             }
247             buff.append(quoteJavaString(array[i]));
248         }
249         buff.append("}");
250         return buff.toString();
251     }
252
253     public static String JavaDoc quoteJavaIntArray(int[] array) {
254         if(array == null) {
255             return "null";
256         }
257         StringBuffer JavaDoc buff = new StringBuffer JavaDoc(2*array.length);
258         buff.append("new int[]{");
259         for(int i=0; i<array.length; i++) {
260             if(i>0) {
261                 buff.append(", ");
262             }
263             buff.append(array[i]);
264         }
265         buff.append("}");
266         return buff.toString();
267     }
268
269     public static String JavaDoc enclose(String JavaDoc s) {
270         if(s.startsWith("(")) {
271             return s;
272         } else {
273             return "(" + s + ")";
274         }
275     }
276
277     public static String JavaDoc unEnclose(String JavaDoc s) {
278         if(s.startsWith("(") && s.endsWith(")")) {
279             return s.substring(1, s.length()-1);
280         } else {
281             return s;
282         }
283     }
284
285     public static String JavaDoc urlEncode(String JavaDoc s) {
286 //#ifdef JDK14
287
try {
288             return URLEncoder.encode(s, "UTF-8");
289         } catch (UnsupportedEncodingException JavaDoc e) {
290             e.printStackTrace();
291             return s;
292         }
293 //#endif
294
//#ifdef JDK13
295
/*
296         return URLEncoder.encode(s);
297 */

298 //#endif
299
// byte[] utf = utf8Encode(s);
300
// StringBuffer buff = new StringBuffer(utf.length);
301
// for(int i=0; i<utf.length; i++) {
302
//
303
// buff.append()
304
// }
305
}
306
307     public static String JavaDoc urlDecode(String JavaDoc encoded) throws SQLException JavaDoc {
308         byte[] buff = new byte[encoded.length()];
309         int j=0;
310         for(int i=0; i<encoded.length(); i++) {
311             char ch = encoded.charAt(i);
312             if(ch=='+') {
313                 buff[j++] = ' ';
314             } else if(ch=='%') {
315                 buff[j++] = (byte)Integer.parseInt(encoded.substring(i+1,i+3),16);
316                 i+=2;
317             } else {
318                 if(Constants.CHECK && (ch > 127 || ch < ' ')) {
319                     throw new IllegalArgumentException JavaDoc("unexpected char " + (int)ch + " decoding " + encoded);
320                 }
321                 buff[j++] = (byte)ch;
322             }
323         }
324         String JavaDoc s = utf8Decode(buff, 0, j);
325         return s;
326     }
327
328     public static String JavaDoc[] arraySplit(String JavaDoc s, char separatorChar, boolean trim) {
329         if(s==null) {
330             return null;
331         }
332         if(s.length()==0) {
333             return new String JavaDoc[0];
334         }
335         ArrayList JavaDoc list = new ArrayList JavaDoc();
336         StringBuffer JavaDoc buff=new StringBuffer JavaDoc(s.length());
337         for(int i=0;i<s.length();i++) {
338             char c=s.charAt(i);
339             if(c==separatorChar) {
340                 String JavaDoc e = buff.toString();
341                 list.add(trim ? e.trim() : e);
342                 buff.setLength(0);
343             } else if(c=='\\' && i<s.length()-1) {
344                 buff.append(s.charAt(++i));
345             } else {
346                 buff.append(c);
347             }
348         }
349         String JavaDoc e = buff.toString();
350         list.add(trim ? e.trim() : e);
351         String JavaDoc[] array = new String JavaDoc[list.size()];
352         list.toArray(array);
353         return array;
354     }
355
356     public static String JavaDoc arrayCombine(String JavaDoc[] list, char separatorChar) {
357         StringBuffer JavaDoc buff=new StringBuffer JavaDoc();
358         for(int i=0;i<list.length;i++) {
359             if(i>0) {
360                 buff.append(separatorChar);
361             }
362             String JavaDoc s=list[i];
363             if(s==null) {
364                 s = "";
365             }
366             for(int j=0;j<s.length();j++) {
367                 char c=s.charAt(j);
368                 if(c=='\\' || c==separatorChar) {
369                     buff.append('\\');
370                 }
371                 buff.append(c);
372             }
373         }
374         return buff.toString();
375     }
376
377     /**
378      * Formats a date using a format string
379      */

380     public static String JavaDoc formatDateTime(Date JavaDoc date, String JavaDoc format, String JavaDoc locale, String JavaDoc timezone) throws SQLException JavaDoc {
381         SimpleDateFormat JavaDoc sdf = getDateFormat(format, locale, timezone);
382         return sdf.format(date);
383     }
384
385     /**
386      * Parses a date using a format string
387      */

388     public static Date JavaDoc parseDateTime(String JavaDoc date, String JavaDoc format, String JavaDoc locale, String JavaDoc timezone) throws SQLException JavaDoc {
389         SimpleDateFormat JavaDoc sdf = getDateFormat(format, locale, timezone);
390         try {
391             return sdf.parse(date);
392         } catch(ParseException JavaDoc e) {
393             throw Message.getSQLException(Message.PARSE_ERROR_1, date);
394         }
395     }
396
397     private static SimpleDateFormat JavaDoc getDateFormat(String JavaDoc format, String JavaDoc locale, String JavaDoc timezone) throws SQLException JavaDoc {
398         try {
399             SimpleDateFormat JavaDoc df;
400             if(locale == null) {
401                 df = new SimpleDateFormat JavaDoc(format);
402             } else {
403 //#ifdef JDK14
404
Locale JavaDoc l = new Locale JavaDoc(locale);
405 //#endif
406
//#ifdef JDK13
407
/*
408                 Locale l = new Locale(locale, "");
409 */

410 //#endif
411
df = new SimpleDateFormat JavaDoc(format, l);
412             }
413             if(timezone != null) {
414                 df.setTimeZone(TimeZone.getTimeZone(timezone));
415             }
416             return df;
417         } catch(Exception JavaDoc e) {
418             throw Message.getSQLException(Message.PARSE_ERROR_1, format + "/" + locale + "/" + timezone);
419         }
420     }
421
422     /**
423      * Creates an XML attribute of the form name="value".
424      * A single space is prepended to the name,
425      * so that multiple attributes can be concatenated.
426      * @param name
427      * @param value
428      * @return the attribute
429      */

430     public static String JavaDoc xmlAttr(String JavaDoc name, String JavaDoc value) {
431         return " " + name + "=\"" + xmlText(value) + "\"";
432     }
433
434     /**
435      * Create an XML node with optional attributes and content.
436      * The data is indented with 4 spaces if it contains a newline character.
437      *
438      * @param name the element name
439      * @param attributes the attributes (may be null)
440      * @param content the content (may be null)
441      * @return the node
442      */

443     public static String JavaDoc xmlNode(String JavaDoc name, String JavaDoc attributes, String JavaDoc content) {
444         String JavaDoc start = attributes == null ? name : name + attributes;
445         if(content == null) {
446             return "<" + start + "/>\n";
447         } else {
448             if(content.indexOf('\n') >= 0) {
449                 content = "\n" + indent(content);
450             }
451             return "<" + start + ">" + content + "</" + name + ">\n";
452         }
453     }
454
455     /**
456      * Indents a string with 4 spaces.
457      * @param s the string
458      * @return the indented string
459      */

460     public static String JavaDoc indent(String JavaDoc s) {
461         return indent(s, 4);
462     }
463
464     /**
465      * Indents a string with spaces.
466      * @param s the string
467      * @param spaces the number of spaces
468      * @return the indented string
469      */

470     public static String JavaDoc indent(String JavaDoc s, int spaces) {
471         StringBuffer JavaDoc buff = new StringBuffer JavaDoc(s.length() + spaces);
472         for(int i=0; i < s.length(); ) {
473             for(int j=0; j<spaces; j++) {
474                 buff.append(' ');
475             }
476             int n = s.indexOf('\n', i);
477             n = n < 0 ? s.length() : n+1;
478             buff.append(s.substring(i, n));
479             i = n;
480         }
481         if(!s.endsWith("\n")) {
482             buff.append('\n');
483         }
484         return buff.toString();
485     }
486
487     /**
488      * Escapes a comment.
489      * If the data contains '--', it is converted to '- -'.
490      * The data is indented with 4 spaces if it contains a newline character.
491      *
492      * @param data
493      * @return <!-- data -->
494      */

495     public static String JavaDoc xmlComment(String JavaDoc data) {
496         int idx = 0;
497         while(true) {
498             idx = data.indexOf("--", idx);
499             if(idx<0) {
500                 break;
501             }
502             data = data.substring(0, idx + 1) + " " + data.substring(idx + 1);
503         }
504         // must have a space at the beginning and at the end,
505
// otherwise the data must not contain '-' as the first/last character
506
if(data.indexOf('\n') >= 0) {
507             return "<!--\n" + indent(data) + "-->\n";
508         } else {
509             return "<!-- " + data + " -->\n";
510         }
511     }
512
513     /**
514      * Converts the data to a CDATA element.
515      * If the data contains ']]>', it is escaped as a text element.
516      * @param data
517      * @return <![CDATA[data]]>
518      */

519     public static String JavaDoc xmlCData(String JavaDoc data) {
520         if(data.indexOf("]]>") >= 0) {
521             return xmlText(data);
522         }
523         boolean newline = data.endsWith("\n");
524         data = "<![CDATA[" + data + "]]>";
525         return newline ? data + "\n" : data;
526     }
527
528     /**
529      * Returns <?xml version="1.0"?>
530      * @return <?xml version="1.0"?>
531      */

532     public static String JavaDoc xmlStartDoc() {
533         return "<?xml version=\"1.0\"?>\n";
534     }
535
536     /**
537      * Escapes an XML text element.
538      *
539      * @param text
540      * @return the escaped text
541      */

542     public static String JavaDoc xmlText(String JavaDoc text) {
543         StringBuffer JavaDoc buff = new StringBuffer JavaDoc(text.length());
544         for(int i=0; i<text.length(); i++) {
545             char ch = text.charAt(i);
546             switch(ch) {
547             case '<':
548                 buff.append("&lt;");
549                 break;
550             case '>':
551                 buff.append("&gt;");
552                 break;
553             case '&':
554                 buff.append("&amp;");
555                 break;
556             case '\'':
557                 buff.append("&apos;");
558                 break;
559             case '\"':
560                 buff.append("&quot;");
561                 break;
562             case '\r':
563             case '\n':
564             case '\t':
565                 buff.append(ch);
566                 break;
567             default:
568                 if(ch < ' ' || ch > 127) {
569                     buff.append("&#x");
570                     buff.append(Integer.toHexString(ch));
571                     buff.append(';');
572                 } else {
573                     buff.append(ch);
574                 }
575             }
576         }
577         return buff.toString();
578     }
579
580     public static String JavaDoc replaceAll(String JavaDoc s, String JavaDoc before, String JavaDoc after) {
581         int index = 0;
582         while(true) {
583             int next = s.indexOf(before, index);
584             if(next < 0) {
585                 return s;
586             }
587             s = s.substring(0, next) + after + s.substring(next+before.length());
588             index = next + after.length();
589         }
590     }
591
592     public static String JavaDoc quoteIdentifier(String JavaDoc s) {
593         StringBuffer JavaDoc buff = new StringBuffer JavaDoc("\"");
594         for(int i=0; i<s.length(); i++) {
595             char c = s.charAt(i);
596             if(c == '"') {
597                 buff.append(c);
598             }
599             buff.append(c);
600         }
601         return buff.append('\"').toString();
602     }
603
604 }
605
Popular Tags