KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > quadcap > util > Util


1 package com.quadcap.util;
2
3 /* Copyright 1997 - 2003 Quadcap Software. All rights reserved.
4  *
5  * This software is distributed under the Quadcap Free Software License.
6  * This software may be used or modified for any purpose, personal or
7  * commercial. Open Source redistributions are permitted. Commercial
8  * redistribution of larger works derived from, or works which bundle
9  * this software requires a "Commercial Redistribution License"; see
10  * http://www.quadcap.com/purchase.
11  *
12  * Redistributions qualify as "Open Source" under one of the following terms:
13  *
14  * Redistributions are made at no charge beyond the reasonable cost of
15  * materials and delivery.
16  *
17  * Redistributions are accompanied by a copy of the Source Code or by an
18  * irrevocable offer to provide a copy of the Source Code for up to three
19  * years at the cost of materials and delivery. Such redistributions
20  * must allow further use, modification, and redistribution of the Source
21  * Code under substantially the same terms as this license.
22  *
23  * Redistributions of source code must retain the copyright notices as they
24  * appear in each source code file, these license terms, and the
25  * disclaimer/limitation of liability set forth as paragraph 6 below.
26  *
27  * Redistributions in binary form must reproduce this Copyright Notice,
28  * these license terms, and the disclaimer/limitation of liability set
29  * forth as paragraph 6 below, in the documentation and/or other materials
30  * provided with the distribution.
31  *
32  * The Software is provided on an "AS IS" basis. No warranty is
33  * provided that the Software is free of defects, or fit for a
34  * particular purpose.
35  *
36  * Limitation of Liability. Quadcap Software shall not be liable
37  * for any damages suffered by the Licensee or any third party resulting
38  * from use of the Software.
39  */

40
41 //-//#ifdef JDK11
42
//-import com.sun.java.util.collections.ArrayList;
43
//-import com.sun.java.util.collections.Collections;
44
//-import com.sun.java.util.collections.Comparator;
45
//#endif
46

47 import java.util.ArrayList JavaDoc;
48 import java.util.Collections JavaDoc;
49 import java.util.Comparator JavaDoc;
50 import java.util.HashMap JavaDoc;
51 import java.util.Hashtable JavaDoc;
52 import java.util.List JavaDoc;
53 import java.util.Properties JavaDoc;
54 import java.util.Vector JavaDoc;
55
56 import java.io.ByteArrayInputStream JavaDoc;
57 import java.io.ByteArrayOutputStream JavaDoc;
58 import java.io.File JavaDoc;
59 import java.io.FileInputStream JavaDoc;
60 import java.io.FileOutputStream JavaDoc;
61 import java.io.IOException JavaDoc;
62 import java.io.InputStream JavaDoc;
63 import java.io.OutputStream JavaDoc;
64 import java.io.PrintStream JavaDoc;
65
66 import java.text.Collator JavaDoc;
67
68 import java.lang.reflect.Array JavaDoc;
69
70 /**
71  * This class aggregates a bunch of various string manipulation utilities.
72  *
73  * @author Stan Bailes
74  */

75 public class Util {
76     /**
77      * Split a string into a vector of elements.
78      */

79     public static Vector JavaDoc split(String JavaDoc s, char delim) {
80         return split(s, delim, -1);
81     }
82     
83     public static Vector JavaDoc split(String JavaDoc s, char delim, int cnt) {
84         Vector JavaDoc v = new Vector JavaDoc();
85         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
86         for (int i = 0; i < s.length(); i++) {
87             char c = s.charAt(i);
88             if (c == delim && (cnt < 0 || v.size()+1 < cnt)) {
89                 if (sb.length() > 0) {
90                     v.addElement(sb.toString());
91                     sb = new StringBuffer JavaDoc();
92                 }
93             } else {
94                 sb.append(c);
95             }
96         }
97         if (sb.length() > 0) {
98             v.addElement(sb.toString());
99         }
100         while (v.size() < cnt) {
101             v.addElement(new String JavaDoc(""));
102         }
103         return v;
104     }
105
106     public static Hashtable JavaDoc parseArgs(String JavaDoc args[]) {
107         Hashtable JavaDoc t = new Hashtable JavaDoc();
108         int i = 0;
109         Vector JavaDoc a = new Vector JavaDoc();
110         while (i < args.length && args[i].startsWith("-")) {
111             String JavaDoc arg = args[i];
112             if (arg.charAt(0) == '-') {
113                 Vector JavaDoc v = (Vector JavaDoc)t.get(arg);
114                 if (v == null) v = new Vector JavaDoc();
115                 v.addElement(args[i+1]);
116                 t.put(arg.substring(1), v);
117                 i++;
118             } else {
119                 a.addElement(arg);
120             }
121             i++;
122         }
123         t.put("", a);
124         return t;
125     }
126
127     public static String JavaDoc readFile(String JavaDoc filename) {
128         File JavaDoc f = new File JavaDoc(filename);
129         if (f.exists()) {
130             try {
131                 FileInputStream JavaDoc is = new FileInputStream JavaDoc(f);
132                 StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
133                 int c;
134                 while ((c = is.read()) >= 0) sb.append((char)c);
135                 String JavaDoc r = sb.toString();
136                 return r;
137             } catch (IOException JavaDoc e) {
138                 Debug.println("Util.readFile(" + filename + ") " +
139                               "Got IOException: " + e.toString());
140             }
141         }
142         return null;
143     }
144
145     public static char[] hexMap = {'0', '1', '2', '3', '4', '5', '6', '7',
146                 '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
147     
148     public static String JavaDoc strBytes(byte[] buf, int offset, int len) {
149     if (buf == null || len == 0) return "<null>";
150     StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
151     for (int i = 0; i < len; i++) {
152         if ((i % 16) == 0 && (len - i > 12 || i > 0)) {
153         if (i > 0) {
154             sb.append(' ');
155             sb.append(' ');
156             for (int j = (i-1) & ~15; j < i; j++) {
157             byte c = buf[offset + j];
158             if (c >= 0x20 && c <= 0x7f) sb.append((char)c);
159             else sb.append('.');
160             }
161         }
162         sb.append('\n');
163         }
164         byte b = buf[offset+i];
165         sb.append(hexMap[(b >> 4) & 0xf]);
166         sb.append(hexMap[b & 0xf]);
167         sb.append(' ');
168     }
169     if (len > 16) for (int j = len; (j&15) != 0; j++) sb.append(" ");
170     sb.append(" ");
171     for (int j = (len-1) & ~15; j < len; j++) {
172         byte c = buf[offset + j];
173         if (c >= 0x20 && c <= 0x7f) sb.append((char)c);
174         else sb.append('.');
175     }
176     return sb.toString();
177     }
178
179     public static String JavaDoc hexBytes(byte[] buf) {
180     if (buf == null) return "<null>";
181     return hexBytes(buf, 0, buf.length);
182     }
183
184     public static String JavaDoc hexBytes(byte[] buf, int off, int len) {
185     if (buf == null) return "<null>";
186     StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
187     for (int i = off; i < off + len; i++) {
188         if (i >= buf.length) {
189         sb.append("###### OVERRUN ######");
190         break;
191         }
192         byte b = buf[i];
193         sb.append(hexMap[(b >> 4) & 0xf]);
194         sb.append(hexMap[b & 0xf]);
195     }
196     return sb.toString();
197     }
198
199     public static String JavaDoc hexInts(byte[] buf) {
200         return hexInts(buf, 0, buf.length);
201     }
202     
203     public static String JavaDoc hexInts(byte[] buf, int off, int len) {
204     if (buf == null) return "<null>";
205     StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
206     for (int i = off; i < off + len; i++) {
207         if (i >= buf.length) {
208         sb.append("###### OVERRUN ######");
209         break;
210         }
211         byte b = buf[i];
212         sb.append(hexMap[(b >> 4) & 0xf]);
213         sb.append(hexMap[b & 0xf]);
214             if ((((i+1) - off) % 4) == 0) sb.append(' ');
215     }
216     return sb.toString();
217     }
218
219     public static String JavaDoc strBytes(byte[] buf) {
220     if (buf == null) return "<null>";
221     return strBytes(buf, 0, buf.length);
222     }
223
224     public static boolean boolProperty(String JavaDoc s) {
225     return Boolean.getBoolean(s);
226     }
227
228     public static int intProperty(String JavaDoc s, int defVal) {
229     String JavaDoc v = System.getProperty(s);
230     return v == null ? defVal : Integer.parseInt(v);
231     }
232
233     public static String JavaDoc strProperty(String JavaDoc s, String JavaDoc defVal) {
234     String JavaDoc v = System.getProperty(s);
235     return v == null ? defVal : v;
236     }
237     public static byte[] bytes(String JavaDoc s) {
238     byte[] buf = new byte[s.length()];
239     s.getBytes(0, buf.length, buf, 0);
240     return buf;
241     }
242
243     /**
244      * To hell with character encodings ;-)
245      */

246     public static byte[] strCharsAsBytes(String JavaDoc s) {
247     byte[] buf = new byte[s.length() * 2];
248         char[] cbuf = s.toCharArray();
249         charsToBytes(cbuf, 0, buf, 0, s.length());
250     return buf;
251     }
252
253     public static void bytesToChars(byte[] bbuf, int boff,
254                                     char[] cbuf, int coff, int clen) {
255         int clim = coff + clen;
256         while (coff < clim) {
257             int c1 = bbuf[boff++] & 0xff;
258             int c2 = bbuf[boff++] & 0xff;
259             cbuf[coff++] = (char)((c1 << 8) | c2);
260         }
261     }
262
263     public static void charsToBytes(char[] cbuf, int coff,
264                                     byte[] bbuf, int boff, int clen) {
265         int clim = coff + clen;
266         while (coff < clim) {
267             char c = cbuf[coff++];
268             bbuf[boff++] = (byte)(c >> 8);
269             bbuf[boff++] = (byte)(c & 0xff);
270         }
271     }
272
273     /**
274      * Convert an int to a byte array, MSB first
275      *
276      * @param i the int value
277      */

278     public static byte[] bytes(int i) {
279     byte[] buf = new byte[4];
280     buf[0] = (byte)((i >> 24) & 0xff);
281     buf[1] = (byte)((i >> 16) & 0xff);
282     buf[2] = (byte)((i >> 8) & 0xff);
283     buf[3] = (byte)((i >> 0) & 0xff);
284     return buf;
285     }
286
287     /**
288      * Convert a long to a byte array, MSB first.
289      *
290      * @param i the long value
291      */

292     public static byte[] bytes(long i) {
293     byte[] buf = new byte[8];
294     buf[0] = (byte)((i >> 56) & 0xff);
295     buf[1] = (byte)((i >> 48) & 0xff);
296     buf[2] = (byte)((i >> 40) & 0xff);
297     buf[3] = (byte)((i >> 32) & 0xff);
298     buf[4] = (byte)((i >> 24) & 0xff);
299     buf[5] = (byte)((i >> 16) & 0xff);
300     buf[6] = (byte)((i >> 8) & 0xff);
301     buf[7] = (byte)((i >> 0) & 0xff);
302     return buf;
303     }
304
305     /**
306      * Convert a byte array which represents an integer into an integer.
307      *
308      * @param buf the byte array, MSB first.
309      * @return the integer value stored in the byte array.
310      */

311     public static int integer(byte[] buf) {
312     int ret = 0;
313     for (int i = 0; i < buf.length; i++) {
314         ret <<= 8;
315         ret |= (buf[i] & 0xff);
316     }
317     return ret;
318     }
319
320     /**
321      * Extract an integer from four bytes in a byte array.
322      *
323      * @param buf the byte array
324      * @param pos the offset in the array of the first (MSB) byte of the int
325      * @return the integer value stored in the byte array.
326      */

327     public static int integer(byte[] buf, int pos) {
328     int b1 = buf[pos++] & 0xff;
329     int b2 = buf[pos++] & 0xff;
330     int b3 = buf[pos++] & 0xff;
331     int b4 = buf[pos++] & 0xff;
332     int val = (b1 << 24) + (b2 << 16) + (b3 << 8) + (b4 << 0) ;
333     return val;
334     }
335
336     public static void putInt(byte[] buf, int pos, int val) {
337     buf[pos++] = (byte)((val >>> 24) & 0xff);
338     buf[pos++] = (byte)((val >>> 16) & 0xff);
339     buf[pos++] = (byte)((val >>> 8) & 0xff);
340     buf[pos] = (byte)((val ) & 0xff);
341     }
342
343     public static void putLong(byte[] buf, int pos, long val) {
344     buf[pos++] = (byte)((val >>> 56) & 0xff);
345     buf[pos++] = (byte)((val >>> 48) & 0xff);
346     buf[pos++] = (byte)((val >>> 40) & 0xff);
347     buf[pos++] = (byte)((val >>> 32) & 0xff);
348     buf[pos++] = (byte)((val >>> 24) & 0xff);
349     buf[pos++] = (byte)((val >>> 16) & 0xff);
350     buf[pos++] = (byte)((val >>> 8) & 0xff);
351     buf[pos] = (byte)((val ) & 0xff);
352     }
353
354     /**
355      * Convert a byte array which represents a long into a long.
356      *
357      * @param buf the byte array, MSB first.
358      * @return the long value stored in the byte array.
359      */

360     public final static long bytesToLong(byte[] buf) {
361     return bytesToLong(buf, 0);
362     }
363
364     /**
365      * Convert a byte array which represents a long into a long.
366      *
367      * @param buf the byte array, MSB first.
368      * @return the long value stored in the byte array.
369      */

370     public final static long bytesToLong(byte[] buf, int offset) {
371     long ret = 0;
372         int lim = offset + 8;
373     for (int i = offset; i < buf.length && i < lim; i++) {
374         ret <<= 8;
375         ret |= (buf[i] & 0xff);
376     }
377     return ret;
378     }
379
380     /**
381      * Byte-array comparison.
382      *
383      * @param k1 the byte array containing key 1.
384      * @param s1 the starting offset of key 1 in <code>k1</code>.
385      * @param c1 the length of key 1.
386      * @param k2 the byte array containing key 2.
387      * @param s2 the starting offset of key 2 in <code>k2</code>.
388      * @param c2 the length of key 2.
389      * @return<p><table cellspacing=2 border=2>
390      * <tr><td>&lt; zero<td>if key1 is less than key2
391      * <tr><td>zero<td>if key1 is equal to key2
392      * <tr><td>&gt; zero<td>if key1 is greater than key2</table>
393      */

394     public static int compareBytes(byte[] k1, int s1, int c1,
395                 byte[] k2, int s2, int c2)
396     {
397     int l1 = s1 + c1;
398     int l2 = s2 + c2;
399     while (s1 < l1 && s2 < l2) {
400         if (k1[s1] < k2[s2]) return -1;
401         if (k1[s1] > k2[s2]) return 1;
402         s1++;
403         s2++;
404     }
405     if (c1 < c2) return -1;
406     if (c1 > c2) return 1;
407     return 0;
408     }
409
410     public static int compareBytes(byte[] b1, byte[] b2) {
411     return compareBytes(b1, 0, b1.length, b2, 0, b2.length);
412     }
413
414     /**
415      * Return a File object corresponding to the specified file name.
416      * If the name is relative, it is located relative to the user's
417      * current directory. This is helpful for the case when we run
418      * as a service from the /winnt/system32 directory and want to
419      * open files relative to our install root.
420      *
421      * @param name the file name
422      * @return the file
423      */

424     public static File JavaDoc userFile(String JavaDoc name) {
425     File JavaDoc f = new File JavaDoc(name);
426     f = new File JavaDoc(f.getAbsolutePath());
427     return f;
428     }
429
430     /**
431      * Like File.list(), but returns directories first, and sorts alpha
432      */

433     public static String JavaDoc[] listFiles(final File JavaDoc f) {
434     String JavaDoc[] s = f.list();
435     if (s != null) {
436         final Collator JavaDoc col = Collator.getInstance();
437         Comparator JavaDoc c = new Comparator JavaDoc() {
438         public int compare(Object JavaDoc a, Object JavaDoc b) {
439             File JavaDoc fa = new File JavaDoc(f, a.toString());
440             File JavaDoc fb = new File JavaDoc(f, b.toString());
441             if (fa.isDirectory() && !fb.isDirectory()) return -1;
442             if (!fa.isDirectory() && fb.isDirectory()) return 1;
443             return col.compare(a.toString(), b.toString());
444         }
445         public boolean equals(Object JavaDoc obj) { return false; }
446         };
447         ArrayList JavaDoc a = new ArrayList JavaDoc();
448         for (int i = 0; i < s.length; i++) a.add(s[i]);
449         Collections.sort(a, c);
450         for (int i = 0; i < s.length; i++) s[i] = (String JavaDoc)a.get(i);
451     }
452     return s;
453     }
454
455     public static String JavaDoc getStackTrace(Throwable JavaDoc t) {
456         ByteArrayOutputStream JavaDoc bos = new ByteArrayOutputStream JavaDoc();
457         PrintStream JavaDoc ps = new PrintStream JavaDoc(bos);
458         t.printStackTrace(ps);
459         ps.flush();
460         return bos.toString();
461     }
462
463     static HashMap JavaDoc traces = new HashMap JavaDoc();
464     static int lastTrace = 0;
465
466     /**
467      * Return a string showing the current stack trace.
468      */

469     public static String JavaDoc stackTrace() {
470         return stackTrace(new Exception JavaDoc(""), true);
471     }
472
473     public static String JavaDoc stackTrace(boolean condense) {
474         return stackTrace(new Exception JavaDoc(""), condense);
475     }
476
477     /**
478      * Return a string showing the current stack trace.
479      */

480     public static String JavaDoc stackTrace(Throwable JavaDoc e, boolean condense) {
481         ByteArrayOutputStream JavaDoc bos = new ByteArrayOutputStream JavaDoc();
482         PrintStream JavaDoc ps = new PrintStream JavaDoc(bos);
483         e.printStackTrace(ps);
484         ps.flush();
485         ByteArrayInputStream JavaDoc bis = new ByteArrayInputStream JavaDoc(bos.toByteArray());
486         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
487         int state = 1;
488         while (state >= 0) {
489             int c = bis.read();
490             if (c < 0) state = -1;
491             switch (state) {
492             case -1:
493                 break;
494             case 0:
495                 if (c == '\n') state++;
496                 break;
497             case 1:
498                 if (c == '\n') state++;
499                 break;
500             case 2:
501                 if (c == 'a') state++;
502                 break;
503             case 3:
504                 if (c == 't') state++;
505                 break;
506             case 4:
507                 if (c == ' ') state++;
508                 break;
509             case 5:
510                 sb.append((char)c);
511                 if (c == '\n') state = 2;
512                 break;
513             }
514         }
515         String JavaDoc s = sb.toString();
516         Integer JavaDoc num = (Integer JavaDoc)traces.get(s);
517         if (num == null) {
518             num = new Integer JavaDoc(++lastTrace);
519             traces.put(s, num);
520             s = "Trace " + num + ": " + s;
521         } else {
522             s = "Trace " + num + (condense ? "" : (": " + s));
523         }
524         return s;
525     }
526
527     public static void copyStream(InputStream JavaDoc in, OutputStream JavaDoc out)
528     throws IOException JavaDoc
529     {
530     byte[] buf = new byte[4096];
531     int cnt;
532     while ((cnt = in.read(buf)) > 0) out.write(buf, 0, cnt);
533     }
534
535     public static int execCommand(String JavaDoc cmd,
536                                   OutputStream JavaDoc out, OutputStream JavaDoc err) {
537         int ret = -1;
538         try {
539             Runtime JavaDoc r = Runtime.getRuntime();
540             Process JavaDoc p = r.exec(cmd);
541             return waitFor(p, out, err);
542         } catch (IOException JavaDoc e) {
543             Debug.print(e);
544             ret = -1;
545         }
546         return ret;
547     }
548
549     public static int execCommand(String JavaDoc[] cmdarray,
550                                   OutputStream JavaDoc out, OutputStream JavaDoc err) {
551         int ret = -1;
552         try {
553             Runtime JavaDoc r = Runtime.getRuntime();
554             Process JavaDoc p = r.exec(cmdarray);
555             return waitFor(p, out, err);
556         } catch (IOException JavaDoc e) {
557             Debug.print(e);
558             ret = -1;
559         }
560         return ret;
561     }
562
563     public static int waitFor(Process JavaDoc p, OutputStream JavaDoc out,
564                               OutputStream JavaDoc err) throws IOException JavaDoc {
565         Thread JavaDoc it = makeCopyThread(p.getInputStream(), out);
566         Thread JavaDoc et = makeCopyThread(p.getErrorStream(), err);
567         it.start();
568         et.start();
569         int ret = Util.waitFor(p);
570         Util.join(it);
571         Util.join(et);
572         return ret;
573     }
574
575     
576         
577     public static int execCommand(String JavaDoc cmd, OutputStream JavaDoc out) {
578         return execCommand(cmd, out, out);
579     }
580
581     public static String JavaDoc execCommand(String JavaDoc cmd) {
582         ByteArrayOutputStream JavaDoc b = new ByteArrayOutputStream JavaDoc();
583         execCommand(cmd, b);
584         return b.toString();
585     }
586             
587     public static String JavaDoc execCommand(String JavaDoc[] cmd) {
588         ByteArrayOutputStream JavaDoc b = new ByteArrayOutputStream JavaDoc();
589         execCommand(cmd, b, b);
590         return b.toString();
591     }
592             
593     public static String JavaDoc execCommand(String JavaDoc a, String JavaDoc b) {
594         return execCommand(new String JavaDoc[]{a, b});
595     }
596     public static String JavaDoc execCommand(String JavaDoc a, String JavaDoc b, String JavaDoc c) {
597         return execCommand(new String JavaDoc[]{a, b, c});
598     }
599             
600     /**
601      * Create a thread which copies bytes from an input stream to
602      * an output stream until end of file is reached.
603      */

604     public static Thread JavaDoc makeCopyThread(final InputStream JavaDoc in,
605                     final OutputStream JavaDoc out) {
606     Thread JavaDoc t = new Thread JavaDoc() {
607         boolean terminate = false;
608         public void run() {
609         int c;
610         try {
611             while (!terminate && (c = in.read()) >= 0) out.write(c);
612         } catch (IOException JavaDoc e) {
613             Debug.print(e);
614         }
615         }
616         public void terminate() {
617         this.terminate = true;
618         }
619     };
620     return t;
621     }
622
623     /**
624      * Utility to sleep without having to worry about catching
625      * InterruptedException.
626      *
627      * @param ms milliseconds to sleep.
628      */

629     public static final void sleep(long ms) {
630     try {
631         Thread.sleep(ms);
632     } catch (InterruptedException JavaDoc e) {
633         Debug.print(e);
634     }
635     }
636
637     /**
638      * Utility to join without having to worry about catching
639      * InterruptedException.
640      *
641      * @param t the thread to wait for
642      */

643     public static final void join(Thread JavaDoc t) {
644     try {
645         t.join();
646     } catch (InterruptedException JavaDoc e) {
647         Debug.print(e);
648     }
649     }
650
651     /**
652      * Utility to wait for a process without having to worry about catching
653      * InterruptedException
654      *
655      * @param p the process to wait for
656      */

657     public static final int waitFor(Process JavaDoc p) {
658         try {
659             return p.waitFor();
660         } catch (InterruptedException JavaDoc e) {
661             Debug.print(e);
662             return -1;
663         }
664     }
665     
666     /**
667      * Parse a semicolon-separated property list:
668      *
669      * prop1=val1;prop2=val2
670      */

671     public static final Properties JavaDoc parsePropsString(String JavaDoc extraProps) {
672         Properties JavaDoc props = new Properties JavaDoc();
673         Vector JavaDoc v = Util.split(extraProps, ';');
674         for (int i = 0; i < v.size(); i++) {
675             String JavaDoc prop = v.elementAt(i).toString();
676             int idx = prop.indexOf('=');
677             if (idx > 0) {
678                 props.setProperty(prop.substring(0, idx),
679                                   prop.substring(idx+1));
680             }
681         }
682         return props;
683     }
684
685     /**
686      * Generic array resizer
687      */

688     public static Object JavaDoc checkCapacity(Object JavaDoc array, int desiredcap) {
689         int len = Array.getLength(array);
690         if (len < desiredcap) {
691             Class JavaDoc c = array.getClass();
692             Class JavaDoc t = c.getComponentType();
693             Object JavaDoc n = Array.newInstance(t, desiredcap);
694             System.arraycopy(array, 0, n, 0, len);
695             array = n;
696         }
697         return array;
698     }
699
700     /**
701      * Parse a comma-separated list of integers or integer ranges.
702      *
703      * Example: 1,2
704      * Example: 1,3-5,77
705      *
706      * @return a List of Integers
707      */

708     public static List JavaDoc parseIntList(String JavaDoc s) {
709         List JavaDoc ret = new ArrayList JavaDoc();
710         List JavaDoc tests = Util.split(s, ',');
711
712         for (int i = 0; i < tests.size(); i++) {
713             int first, last;
714             final String JavaDoc t = tests.get(i).toString();
715             final int idx = t.indexOf('-');
716             if (idx > 0) {
717                 first = Integer.parseInt(t.substring(0, idx));
718                 last = Integer.parseInt(t.substring(idx+1));
719                 if (last < first) last = first;
720             } else {
721                 first = last = Integer.parseInt(t);
722             }
723             for (int test = first; test <= last; test++) {
724                 ret.add(new Integer JavaDoc(test));
725             }
726         }
727         return ret;
728     }
729
730     public static int compareObjects(Object JavaDoc a, Object JavaDoc b) {
731         if (a == null) {
732             return (b == null) ? 0 : -1;
733         } else if (b == null) {
734             return 1;
735         } else if (a instanceof Comparable JavaDoc) {
736             return ((Comparable JavaDoc)a).compareTo(b);
737         } else if (b instanceof Comparable JavaDoc) {
738             return 0 - ((Comparable JavaDoc)b).compareTo(a);
739         } else {
740             return String.valueOf(a).compareTo(String.valueOf(b));
741         }
742     }
743
744     public static String JavaDoc htmlEscape(String JavaDoc s) {
745         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
746     for (int i = 0; i < s.length(); i++) {
747             char c = s.charAt(i);
748             switch (c) {
749         case '<': sb.append("&lt;"); break;
750         case '>': sb.append("&gt;"); break;
751         case '&': sb.append("&amp;"); break;
752         default: sb.append(c); break;
753             }
754         }
755     return sb.toString();
756     }
757     
758 }
759
Popular Tags