KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sslexplorer > util > Utils


1 /*
2  * ====================================================================
3  * Copyright (c) 1995-1999 Purple Technology, Inc. All rights
4  * reserved.
5  *
6  * PLAIN LANGUAGE LICENSE: Do whatever you like with this code, free
7  * of charge, just give credit where credit is due. If you improve it,
8  * please send your improvements to alex@purpletech.com. Check
9  * http://www.purpletech.com/code/ for the latest version and news.
10  *
11  * LEGAL LANGUAGE LICENSE: Redistribution and use in source and binary
12  * forms, with or without modification, are permitted provided that
13  * the following conditions are met:
14  *
15  * 1. Redistributions of source code must retain the above copyright
16  * notice, this list of conditions and the following disclaimer.
17  *
18  * 2. Redistributions in binary form must reproduce the above
19  * copyright notice, this list of conditions and the following
20  * disclaimer in the documentation and/or other materials provided
21  * with the distribution.
22  *
23  * 3. The names of the authors and the names "Purple Technology,"
24  * "Purple Server" and "Purple Chat" must not be used to endorse or
25  * promote products derived from this software without prior written
26  * permission. For written permission, please contact
27  * server@purpletech.com.
28  *
29  * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND PURPLE TECHNOLOGY ``AS
30  * IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
31  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
32  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
33  * AUTHORS OR PURPLE TECHNOLOGY BE LIABLE FOR ANY DIRECT, INDIRECT,
34  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
35  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
36  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
37  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
38  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
39  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
40  * OF THE POSSIBILITY OF SUCH DAMAGE.
41  *
42  * ====================================================================
43  *
44  **/

45
46 package com.sslexplorer.util;
47
48 import java.io.EOFException JavaDoc;
49 import java.io.IOException JavaDoc;
50 import java.io.InputStream JavaDoc;
51 import java.io.PrintWriter JavaDoc;
52 import java.io.StringWriter JavaDoc;
53 import java.io.Writer JavaDoc;
54 import java.util.Arrays JavaDoc;
55 import java.util.Collection JavaDoc;
56 import java.util.HashMap JavaDoc;
57 import java.util.Iterator JavaDoc;
58 import java.util.Map JavaDoc;
59
60 public class Utils {
61
62     /**
63      * fills the left side of a number with zeros <br>
64      * e.g. zerofill(14, 3) -> "014" <br>
65      * e.g. zerofill(187, 6) -> "000014" <br>
66      * e.g. zerofill(-33, 4) -> "-033" <br>
67      **/

68     public static String JavaDoc zerofill(int x, int desiredWidth) {
69         StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
70         if (x < 0) {
71             buf.append("-");
72             desiredWidth--;
73             x = -x;
74         }
75         while (desiredWidth>7) {
76             buf.append("0");
77             desiredWidth--;
78         }
79         switch (desiredWidth) {
80         case 7:
81             if (x<1000000) buf.append("0");
82         case 6:
83             if (x<100000) buf.append("0");
84         case 5:
85             if (x<10000) buf.append("0");
86         case 4:
87             if (x<1000) buf.append("0");
88         case 3:
89             if (x<100) buf.append("0");
90         case 2:
91             if (x<10) buf.append( "0" );
92         }
93         buf.append(x);
94         return buf.toString();
95     }
96
97     public static void printIndent(PrintWriter JavaDoc out, int indent) {
98         out.print(indent(indent));
99     }
100
101     public static String JavaDoc indent(int indent) {
102         switch (indent) {
103         case 8:
104             return(" ");
105         case 7:
106             return(" ");
107         case 6:
108             return(" ");
109         case 5:
110             return(" ");
111         case 4:
112             return(" ");
113         case 3:
114             return(" ");
115         case 2:
116             return(" ");
117         case 1:
118             return(" ");
119         default:
120             StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
121             for (int i=0; i<indent; ++i) { buf.append(" "); }
122             return buf.toString();
123         }
124     }
125
126     /**
127      * @deprecated use org.apache.commons.lang.StringUtils.join()
128      **/

129     public static String JavaDoc commaList(Object JavaDoc[] a) {
130         return commaList(Arrays.asList(a).iterator());
131     }
132
133     /**
134      * @deprecated use org.apache.commons.lang.StringUtils.join()
135      **/

136     public static String JavaDoc commaList(Collection JavaDoc c) {
137         return commaList(c.iterator());
138     }
139
140     /**
141      * @deprecated use org.apache.commons.lang.StringUtils.join()
142      **/

143     public static String JavaDoc commaList(Iterator JavaDoc i) {
144         StringWriter JavaDoc sw = new StringWriter JavaDoc();
145         PrintWriter JavaDoc pw = new PrintWriter JavaDoc(sw);
146         printCommaList(pw, i);
147         pw.close();
148         return sw.toString();
149     }
150
151
152     /**
153      * Given an iterator, prints it as a comma-delimited list
154      * (actually a comma-and-space delimited list). E.g. If the
155      * iterator contains the strings { "my", "dog", "has fleas" } it
156      * will print "my, dog, has fleas".
157      *
158      * @param out the stream to write to
159      * @param i an iterator containing printable (toString) objects, e.g. strings
160      **/

161     public static void printCommaList(PrintWriter JavaDoc out, Iterator JavaDoc i) {
162         boolean first = true;
163         while (i.hasNext()) {
164             if (first) first = false;
165             else out.print(", ");
166             out.print(i.next());
167         }
168     }
169
170     /**
171      * @return true if all characters in the string are whitespace characters, or the string is empty
172      **/

173     public static boolean isWhitespace(String JavaDoc s) {
174         for (int i=0; i<s.length(); ++i) {
175             if (!Character.isWhitespace(s.charAt(i))) return false;
176         }
177         return true;
178     }
179
180     /**
181      * Class encapsulating information from an exec call -- slightly
182      * easier than the standard API
183      **/

184     public static class ExecInfo {
185         public int exit;
186         public String JavaDoc stdout;
187         public String JavaDoc stderr;
188
189         public String JavaDoc toString() {
190             return "ExecInfo[exit=" + exit + "," +
191                 "stdout=" + javaEscape(stdout) + "," +
192                 "stderr=" + javaEscape(stderr) + "]";
193         }
194     }
195
196     /**
197      * Wrapper for Runtime.exec. Takes input as a String. Times out
198      * after sleep msec. Returns an object containing exit value,
199      * standard output, and error output.
200      * @param command the command-line to execute
201      * @param input a string to pass to the process as standard input
202      * @param sleep msec to wait before terminating process (if <= 0, waits forever)
203      **/

204     /*public static ExecInfo exec(String command, String input, long sleep) throws IOException {
205         Process process = null;
206         ExecInfo info = new ExecInfo();
207         try {
208             Alarm a = null;
209             if (sleep>0) {
210                 a = new Alarm(Thread.currentThread(), sleep);
211                 a.start();
212             }
213
214             process = Runtime.getRuntime().exec(command);
215
216             if (input != null) {
217                 PrintWriter pw = new PrintWriter(process.getOutputStream());
218                 pw.print(input);
219                 pw.close();
220             }
221
222             info.stdout = IOUtils.readStream(process.getInputStream());
223
224             info.stderr = IOUtils.readStream(process.getErrorStream());
225
226             process.waitFor();
227             if (a!=null) a.stop = true;
228         }
229         catch (InterruptedIOException iioe) {
230             throw new IOException("Process '" + command + "' took more than " + sleep/1000 + " sec");
231         }
232         catch (InterruptedException ie) {
233             throw new IOException("Process '" + command + "' took more than " + sleep/1000 + " sec");
234         }
235
236         finally {
237             if (process != null)
238                 process.destroy();
239         }
240
241         info.exit = process.exitValue();
242         return info;
243     }*/

244
245     /**
246      * Turn "Now is the time for all good men" into "Now is the time for..."
247      * <p>
248      * Specifically:
249      * <p>
250      * If str is less than max characters long, return it.
251      * Else abbreviate it to (substring(str, 0, max-3) + "...").
252      * If max is less than 3, throw an IllegalArgumentException.
253      * In no case will it return a string of length greater than max.
254      *
255      * @param max maximum length of result string
256      **/

257     public static String JavaDoc abbreviate(String JavaDoc s, int max) {
258         if (max < 4)
259             throw new IllegalArgumentException JavaDoc("Minimum abbreviation is 3 chars");
260         if (s.length() <= max) return s;
261         // todo: break into words
262
return s.substring(0, max-3) + "...";
263     }
264
265     /**
266      * pad or truncate
267      **/

268     public static String JavaDoc pad(String JavaDoc s, int length) {
269         if (s.length() < length) return s + indent(length - s.length());
270         else return s.substring(0,length);
271     }
272
273     /**
274      * Compare two strings, and return the portion where they differ.
275      * (More precisely, return the remainder of the second string,
276      * starting from where it's different from the first.)
277      * <p>
278      * E.g. strdiff("i am a machine", "i am a robot") -> "robot"
279      *
280      **/

281     public static String JavaDoc strdiff(String JavaDoc s1, String JavaDoc s2) {
282         int at = strdiffat(s1, s2);
283         if (at == -1)
284             return "";
285         return s2.substring(at);
286     }
287
288     /**
289      * Compare two strings, and return the index at which the strings begin to diverge<p>
290      * E.g. strdiff("i am a machine", "i am a robot") -> 7<p>
291      * @return -1 if they are the same
292      *
293      **/

294     public static int strdiffat(String JavaDoc s1, String JavaDoc s2)
295     {
296         int i;
297         for (i=0; i<s1.length() && i<s2.length(); ++i)
298         {
299             if (s1.charAt(i) != s2.charAt(i)) {
300                 break;
301             }
302         }
303         if (i<s2.length() || i<s1.length())
304             return i;
305         return -1;
306     }
307
308     /**
309      * Compare two strings, and return a verbose description of how
310      * they differ. Shows a window around the location to provide
311      * context. E.g. strdiffVerbose("i am a robot", "i am a machine")
312      * might return a string containing <pre>
313      * strings differ at character 7
314      * Expected: ...am a robot
315      * Actual: ...am a machine</pre>
316      *
317      * This was developed in order to provide some sanity to JUnit's
318      * assertEquals routine.
319      **/

320
321     public static String JavaDoc strdiffVerbose(String JavaDoc expected, String JavaDoc actual)
322     {
323         int at = Utils.strdiffat(actual, expected);
324         if (at == -1)
325             return null;
326         int length = 60; // todo: parameterize
327
int back = 20; // todo: parameterize
328
int start = at - back;
329         if (start < 3) start = 0;
330
331         StringBuffer JavaDoc buf = new StringBuffer JavaDoc(length*2 + 100);
332         buf.append("strings differ at character ").append(at);
333         buf.append("\n");
334
335         buf.append("Expected: ");
336         appendWithEllipses(buf, expected, start, length);
337         buf.append("\n");
338
339         buf.append(" Actual: ");
340         appendWithEllipses(buf, actual, start, length);
341         buf.append("\n");
342
343         return buf.toString();
344     }
345
346     private static void appendWithEllipses(StringBuffer JavaDoc buf, String JavaDoc s, int start, int length)
347     {
348         if (start > 0) buf.append("...");
349         buf.append
350             (javaEscape // note that escapes may add \, making final string more than 60 chars
351
(abbreviate // abbreviate adds the final ... if necessary
352
(s.substring(start), length)));
353     }
354
355     /**
356      * count the number of occurences of ch inside s
357      * @deprecated use org.apache.commons.lang.StringUtils.countMatches instead
358      **/

359     public static int count(String JavaDoc s, char ch) {
360         int c=0;
361         for (int i=0; i<s.length(); ++i) {
362             if (s.charAt(i) == ch) c++;
363         }
364         return c;
365     }
366
367     /**
368      * Replace all occurences of target inside source with replacement.
369      * E.g. replace("fee fie fo fum", "f", "gr") -> "gree grie gro grum"
370      **/

371     public static String JavaDoc replace(String JavaDoc source, String JavaDoc target, String JavaDoc replacement)
372     {
373         // could use a regular expression, but this keeps it portable
374
StringBuffer JavaDoc result = new StringBuffer JavaDoc(source.length());
375         int i = 0, j = 0;
376         int len = source.length();
377         while (i < len) {
378             j = source.indexOf(target, i);
379             if (j == -1) {
380                 result.append( source.substring(i,len) );
381                 break;
382             }
383             else {
384                 result.append( source.substring(i,j) );
385                 result.append( replacement );
386                 i = j + target.length();
387             }
388         }
389         return result.toString();
390     }
391
392     /**
393      * <p>
394      * Trim the whitespace off the right side of a <code>String</code>.
395      * </p>
396      *
397      * @param orig <code>String</code> to rtrim.
398      * @return <code>String</code> - orig with no right spaces
399      */

400     public static String JavaDoc rtrim(String JavaDoc orig) {
401         int len = orig.length();
402         int st = 0;
403         int off = 0;
404         char[] val = orig.toCharArray();
405
406         while ((st < len) && (val[off + len - 1] <= ' ')) {
407             len--;
408         }
409         return ((st > 0) || (len < orig.length())) ? orig.substring(st, len) : orig;
410     }
411
412     /**
413      * <p>
414      * Trim the left spacing off of a <code>String</code>.
415      * </p>
416      *
417      * @param orig <code>String</code> to rtrim.
418      * @return <code>String</code> - orig with no left spaces
419      */

420     public static String JavaDoc ltrim(String JavaDoc orig) {
421         int len = orig.length();
422         int st = 0;
423         int off = 0;
424         char[] val = orig.toCharArray();
425
426         while ((st < len) && (val[off + st] <= ' ')) {
427             st++;
428         }
429         return ((st > 0) || (len < orig.length())) ? orig.substring(st, len) : orig;
430     }
431
432     /**
433      * calculate the maximum length of all strings in i. If i
434      * contains other than strings, uses toString() value.
435      **/

436     public static int getMaxLength(Iterator JavaDoc i) {
437         int max = 0;
438         while (i.hasNext()) {
439             String JavaDoc s = i.next().toString();
440             int c = s.length();
441             if (c>max) max=c;
442         }
443         return max;
444     }
445
446     // see http://hotwired.lycos.com/webmonkey/reference/special_characters/
447
static Object JavaDoc[][] entities = {
448        // {"#39", new Integer(39)}, // ' - apostrophe
449
{"quot", new Integer JavaDoc(34)}, // " - double-quote
450
{"amp", new Integer JavaDoc(38)}, // & - ampersand
451
{"lt", new Integer JavaDoc(60)}, // < - less-than
452
{"gt", new Integer JavaDoc(62)}, // > - greater-than
453
{"nbsp", new Integer JavaDoc(160)}, // non-breaking space
454
{"copy", new Integer JavaDoc(169)}, // � - copyright
455
{"reg", new Integer JavaDoc(174)}, // � - registered trademark
456
{"Agrave", new Integer JavaDoc(192)}, // � - uppercase A, grave accent
457
{"Aacute", new Integer JavaDoc(193)}, // � - uppercase A, acute accent
458
{"Acirc", new Integer JavaDoc(194)}, // � - uppercase A, circumflex accent
459
{"Atilde", new Integer JavaDoc(195)}, // � - uppercase A, tilde
460
{"Auml", new Integer JavaDoc(196)}, // � - uppercase A, umlaut
461
{"Aring", new Integer JavaDoc(197)}, // � - uppercase A, ring
462
{"AElig", new Integer JavaDoc(198)}, // � - uppercase AE
463
{"Ccedil", new Integer JavaDoc(199)}, // � - uppercase C, cedilla
464
{"Egrave", new Integer JavaDoc(200)}, // � - uppercase E, grave accent
465
{"Eacute", new Integer JavaDoc(201)}, // � - uppercase E, acute accent
466
{"Ecirc", new Integer JavaDoc(202)}, // � - uppercase E, circumflex accent
467
{"Euml", new Integer JavaDoc(203)}, // � - uppercase E, umlaut
468
{"Igrave", new Integer JavaDoc(204)}, // � - uppercase I, grave accent
469
{"Iacute", new Integer JavaDoc(205)}, // � - uppercase I, acute accent
470
{"Icirc", new Integer JavaDoc(206)}, // � - uppercase I, circumflex accent
471
{"Iuml", new Integer JavaDoc(207)}, // � - uppercase I, umlaut
472
{"ETH", new Integer JavaDoc(208)}, // � - uppercase Eth, Icelandic
473
{"Ntilde", new Integer JavaDoc(209)}, // � - uppercase N, tilde
474
{"Ograve", new Integer JavaDoc(210)}, // � - uppercase O, grave accent
475
{"Oacute", new Integer JavaDoc(211)}, // � - uppercase O, acute accent
476
{"Ocirc", new Integer JavaDoc(212)}, // � - uppercase O, circumflex accent
477
{"Otilde", new Integer JavaDoc(213)}, // � - uppercase O, tilde
478
{"Ouml", new Integer JavaDoc(214)}, // � - uppercase O, umlaut
479
{"Oslash", new Integer JavaDoc(216)}, // � - uppercase O, slash
480
{"Ugrave", new Integer JavaDoc(217)}, // � - uppercase U, grave accent
481
{"Uacute", new Integer JavaDoc(218)}, // � - uppercase U, acute accent
482
{"Ucirc", new Integer JavaDoc(219)}, // � - uppercase U, circumflex accent
483
{"Uuml", new Integer JavaDoc(220)}, // � - uppercase U, umlaut
484
{"Yacute", new Integer JavaDoc(221)}, // � - uppercase Y, acute accent
485
{"THORN", new Integer JavaDoc(222)}, // � - uppercase THORN, Icelandic
486
{"szlig", new Integer JavaDoc(223)}, // � - lowercase sharps, German
487
{"agrave", new Integer JavaDoc(224)}, // � - lowercase a, grave accent
488
{"aacute", new Integer JavaDoc(225)}, // � - lowercase a, acute accent
489
{"acirc", new Integer JavaDoc(226)}, // � - lowercase a, circumflex accent
490
{"atilde", new Integer JavaDoc(227)}, // � - lowercase a, tilde
491
{"auml", new Integer JavaDoc(228)}, // � - lowercase a, umlaut
492
{"aring", new Integer JavaDoc(229)}, // � - lowercase a, ring
493
{"aelig", new Integer JavaDoc(230)}, // � - lowercase ae
494
{"ccedil", new Integer JavaDoc(231)}, // � - lowercase c, cedilla
495
{"egrave", new Integer JavaDoc(232)}, // � - lowercase e, grave accent
496
{"eacute", new Integer JavaDoc(233)}, // � - lowercase e, acute accent
497
{"ecirc", new Integer JavaDoc(234)}, // � - lowercase e, circumflex accent
498
{"euml", new Integer JavaDoc(235)}, // � - lowercase e, umlaut
499
{"igrave", new Integer JavaDoc(236)}, // � - lowercase i, grave accent
500
{"iacute", new Integer JavaDoc(237)}, // � - lowercase i, acute accent
501
{"icirc", new Integer JavaDoc(238)}, // � - lowercase i, circumflex accent
502
{"iuml", new Integer JavaDoc(239)}, // � - lowercase i, umlaut
503
{"igrave", new Integer JavaDoc(236)}, // � - lowercase i, grave accent
504
{"iacute", new Integer JavaDoc(237)}, // � - lowercase i, acute accent
505
{"icirc", new Integer JavaDoc(238)}, // � - lowercase i, circumflex accent
506
{"iuml", new Integer JavaDoc(239)}, // � - lowercase i, umlaut
507
{"eth", new Integer JavaDoc(240)}, // � - lowercase eth, Icelandic
508
{"ntilde", new Integer JavaDoc(241)}, // � - lowercase n, tilde
509
{"ograve", new Integer JavaDoc(242)}, // � - lowercase o, grave accent
510
{"oacute", new Integer JavaDoc(243)}, // � - lowercase o, acute accent
511
{"ocirc", new Integer JavaDoc(244)}, // � - lowercase o, circumflex accent
512
{"otilde", new Integer JavaDoc(245)}, // � - lowercase o, tilde
513
{"ouml", new Integer JavaDoc(246)}, // � - lowercase o, umlaut
514
{"oslash", new Integer JavaDoc(248)}, // � - lowercase o, slash
515
{"ugrave", new Integer JavaDoc(249)}, // � - lowercase u, grave accent
516
{"uacute", new Integer JavaDoc(250)}, // � - lowercase u, acute accent
517
{"ucirc", new Integer JavaDoc(251)}, // � - lowercase u, circumflex accent
518
{"uuml", new Integer JavaDoc(252)}, // � - lowercase u, umlaut
519
{"yacute", new Integer JavaDoc(253)}, // � - lowercase y, acute accent
520
{"thorn", new Integer JavaDoc(254)}, // � - lowercase thorn, Icelandic
521
{"yuml", new Integer JavaDoc(255)}, // � - lowercase y, umlaut
522
{"euro", new Integer JavaDoc(8364)}, // Euro symbol
523
};
524     static Map JavaDoc e2i = new HashMap JavaDoc();
525     static Map JavaDoc i2e = new HashMap JavaDoc();
526     static {
527         for (int i=0; i<entities.length; ++i) {
528             e2i.put(entities[i][0], entities[i][1]);
529             i2e.put(entities[i][1], entities[i][0]);
530         }
531     }
532
533     /**
534      * Turns funky characters into HTML entity equivalents<p>
535      * e.g. <tt>"bread" & "butter"</tt> => <tt>&amp;quot;bread&amp;quot; &amp;amp; &amp;quot;butter&amp;quot;</tt>.
536      * Update: supports nearly all HTML entities, including funky accents. See the source code for more detail.
537      * @see #htmlunescape(String)
538      **/

539     public static String JavaDoc htmlescape(String JavaDoc s1)
540     {
541         StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
542         int i;
543         for (i=0; i<s1.length(); ++i) {
544             char ch = s1.charAt(i);
545             String JavaDoc entity = (String JavaDoc)i2e.get( new Integer JavaDoc((int)ch) );
546             if (entity == null) {
547                 if (((int)ch) > 128) {
548                     buf.append("&#" + ((int)ch) + ";");
549                 }
550                 else {
551                     buf.append(ch);
552                 }
553             }
554             else {
555                 buf.append("&" + entity + ";");
556             }
557         }
558         return buf.toString();
559     }
560
561     /**
562      * Given a string containing entity escapes, returns a string
563      * containing the actual Unicode characters corresponding to the
564      * escapes.
565      *
566      * Note: nasty bug fixed by Helge Tesgaard (and, in parallel, by
567      * Alex, but Helge deserves major props for emailing me the fix).
568      * 15-Feb-2002 Another bug fixed by Sean Brown <sean@boohai.com>
569      *
570      * @see #htmlescape(String)
571      **/

572     public static String JavaDoc htmlunescape(String JavaDoc s1) {
573         StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
574         int i;
575         for (i=0; i<s1.length(); ++i) {
576             char ch = s1.charAt(i);
577             if (ch == '&') {
578                 int semi = s1.indexOf(';', i+1);
579                 if (semi == -1) {
580                     buf.append(ch);
581                     continue;
582                 }
583                 String JavaDoc entity = s1.substring(i+1, semi);
584                 Integer JavaDoc iso;
585                 if (entity.charAt(0) == '#') {
586                     iso = new Integer JavaDoc(entity.substring(1));
587                 }
588                 else {
589                     iso = (Integer JavaDoc)e2i.get(entity);
590                 }
591                 if (iso == null) {
592                     buf.append("&" + entity + ";");
593                 }
594                 else {
595                     buf.append((char)(iso.intValue()));
596                 }
597                 i = semi;
598             }
599             else {
600                 buf.append(ch);
601             }
602         }
603         return buf.toString();
604     }
605
606     /**
607      * Prepares a string for output inside a JavaScript string,
608      * e.g. for use inside a document.write("") command.
609      *
610      * Example:
611      * <pre>
612      * input string: He didn't say, "Stop!"
613      * output string: He didn\'t say, \"Stop!\"
614      * </pre>
615      *
616      * Deals with quotes and control-chars (tab, backslash, cr, ff, etc.)
617      * Bug: does not yet properly escape Unicode / high-bit characters.
618      *
619      * @see #jsEscape(String, Writer)
620      **/

621     public static String JavaDoc jsEscape(String JavaDoc source) {
622         try {
623             StringWriter JavaDoc sw = new StringWriter JavaDoc();
624             jsEscape(source, sw);
625             sw.flush();
626             return sw.toString();
627         }
628         catch (IOException JavaDoc ioe) {
629             // should never happen writing to a StringWriter
630
ioe.printStackTrace();
631             return null;
632         }
633     }
634
635     /**
636      * @see #javaEscape(String, Writer)
637      **/

638     public static String JavaDoc javaEscape(String JavaDoc source) {
639         try {
640             StringWriter JavaDoc sw = new StringWriter JavaDoc();
641             javaEscape(source, sw);
642             sw.flush();
643             return sw.toString();
644         }
645         catch (IOException JavaDoc ioe) {
646             // should never happen writing to a StringWriter
647
ioe.printStackTrace();
648             return null;
649         }
650     }
651     
652     public static String JavaDoc readLine(InputStream JavaDoc in) throws IOException JavaDoc, EOFException JavaDoc {
653         
654             StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
655             
656             int ch;
657             
658             while((ch = in.read()) > -1) {
659                   
660                    if(ch=='\n')
661                        break;
662                buf.append((char)ch);
663             }
664             
665             if(ch != '\n' && buf.length()==0)
666                    return null;
667             
668             
669             return buf.toString();
670     }
671
672
673     /**
674      * Prepares a string for output inside a JavaScript string,
675      * e.g. for use inside a document.write("") command.
676      *
677      * Example:
678      * <pre>
679      * input string: He didn't say, "stop!"
680      * output string: He didn\'t say, \"stop!\"
681      * </pre>
682      *
683      * Deals with quotes and control-chars (tab, backslash, cr, ff, etc.)
684      *
685      * @see #jsEscape(String)
686      **/

687     public static void jsEscape(String JavaDoc source, Writer JavaDoc out) throws IOException JavaDoc {
688         stringEscape(source, out, true);
689     }
690
691     /**
692      * Prepares a string for output inside a Java string,
693      *
694      * Example:
695      * <pre>
696      * input string: He didn't say, "stop!"
697      * output string: He didn't say, \"stop!\"
698      * </pre>
699      *
700      * Deals with quotes and control-chars (tab, backslash, cr, ff, etc.)
701      *
702      * @see #jsEscape(String,Writer)
703      **/

704     public static void javaEscape(String JavaDoc source, Writer JavaDoc out) throws IOException JavaDoc {
705         stringEscape(source, out, false);
706     }
707
708     private static void stringEscape(String JavaDoc source, Writer JavaDoc out, boolean escapeSingleQuote) throws IOException JavaDoc {
709         char[] chars = source.toCharArray();
710         for (int i=0; i<chars.length; ++i) {
711             char ch = chars[i];
712             switch (ch) {
713             case '\b': // backspace (ASCII 8)
714
out.write("\\b");
715                 break;
716             case '\t': // horizontal tab (ASCII 9)
717
out.write("\\t");
718                 break;
719             case '\n': // newline (ASCII 10)
720
out.write("\\n");
721                 break;
722             case 11: // vertical tab (ASCII 11)
723
out.write("\\v");
724                 break;
725             case '\f': // form feed (ASCII 12)
726
out.write("\\f");
727                 break;
728             case '\r': // carriage return (ASCII 13)
729
out.write("\\r");
730                 break;
731             case '"': // double-quote (ASCII 34)
732
out.write("\\\"");
733                 break;
734             case '\'': // single-quote (ASCII 39)
735
if (escapeSingleQuote) out.write("\\'");
736                 else out.write("'");
737                 break;
738             case '\\': // literal backslash (ASCII 92)
739
out.write("\\\\");
740                 break;
741             default:
742                     if ((int) ch < 32 || (int) ch > 127)
743                     {
744                         out.write("\\u");
745                         zeropad(out, Integer.toHexString(ch).toUpperCase(), 4);
746                     }
747                     else
748                     {
749                         out.write(ch);
750                     }
751                     break;
752             }
753         }
754     }
755
756     private static void zeropad(Writer JavaDoc out, String JavaDoc s, int width) throws IOException JavaDoc
757     {
758         while (width > s.length()) {
759             out.write('0');
760             width--;
761         }
762         out.write(s);
763     }
764
765
766     /**
767      * Filter out Windows and Mac curly quotes, replacing them with
768      * the non-curly versions. Note that this doesn't actually do any
769      * checking to verify the input codepage. Instead it just
770      * converts the more common code points used on the two platforms
771      * to their equivalent ASCII values. As such, this method
772      * <B>should not be used</b> on ISO-8859-1 input that includes
773      * high-bit-set characters, and some text which uses other
774      * codepoints may be rendered incorrectly.
775      *
776      * @author Ian McFarland
777      **/

778     public static String JavaDoc uncurlQuotes(String JavaDoc input)
779     {
780         if (input==null)
781             return "";
782         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
783         for (int i = 0; i < input.length(); i++)
784         {
785             char ch = input.charAt(i);
786             int code = (int) ch;
787             if (code == 210 || code == 211 || code == 147 || code == 148)
788             {
789                 ch = (char) 34; // double quote
790
}
791             else if (code == 212 || code == 213 || code == 145 || code == 146)
792             {
793                 ch = (char) 39; // single quote
794
}
795             sb.append(ch);
796         }
797         return sb.toString();
798     }
799
800     /**
801      * capitalize the first character of s
802      **/

803     public static String JavaDoc capitalize(String JavaDoc s) {
804         return s.substring(0,1).toUpperCase() + s.substring(1);
805     }
806
807     /**
808      * lowercase the first character of s
809      **/

810     public static String JavaDoc lowerize(String JavaDoc s) {
811         return s.substring(0,1).toLowerCase() + s.substring(1);
812     }
813
814     /**
815      * turn String s into a plural noun (doing the right thing with
816      * "story" -> "stories" and "mess" -> "messes")
817      **/

818     public static String JavaDoc pluralize(String JavaDoc s) {
819         if (s.endsWith("y"))
820             return s.substring(0, s.length()-1) + "ies";
821
822         else if (s.endsWith("s"))
823             return s + "es";
824
825         else
826             return s + "s";
827     }
828
829     public static boolean ok(String JavaDoc s) {
830         return (!(s == null || s.equals("")));
831     }
832
833     /**
834      * Converts camelCaseVersusC to camel_case_versus_c
835      **/

836     public static String JavaDoc toUnderscore(String JavaDoc s) {
837         StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
838         char[] ch = s.toCharArray();
839         for (int i=0; i<ch.length; ++i) {
840             if (Character.isUpperCase(ch[i])) {
841                 buf.append('_');
842                 buf.append(Character.toLowerCase(ch[i]));
843             }
844             else {
845                 buf.append(ch[i]);
846             }
847         }
848         //System.err.println(s + " -> " + buf.toString());
849
return buf.toString();
850     }
851
852     /**
853      * @deprecated use org.apache.commons.lang.StringUtils deleteSpaces instead
854      **/

855     public static String JavaDoc stripWhitespace(String JavaDoc s) {
856         StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
857         char[] ch = s.toCharArray();
858         for (int i=0; i<ch.length; ++i) {
859             if (Character.isWhitespace(ch[i])) {
860                 continue;
861             }
862             else {
863                 buf.append(ch[i]);
864             }
865         }
866         return buf.toString();
867     }
868
869     public static String JavaDoc getStackTrace(Throwable JavaDoc t) {
870         StringWriter JavaDoc s = new StringWriter JavaDoc();
871         PrintWriter JavaDoc p = new PrintWriter JavaDoc(s);
872         t.printStackTrace(p);
873         p.close();
874         return s.toString();
875     }
876
877     public static void sleep(long msec) {
878         try {
879             Thread.sleep(msec);
880         }
881         catch (InterruptedException JavaDoc ie) {}
882     }
883 } // class Utils
884

885
Popular Tags