KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > knowgate > misc > Gadgets


1 /*
2   Copyright (C) 2003 Know Gate S.L. All rights reserved.
3                       C/Oña, 107 1º2 28050 Madrid (Spain)
4
5   Redistribution and use in source and binary forms, with or without
6   modification, are permitted provided that the following conditions
7   are met:
8
9   1. Redistributions of source code must retain the above copyright
10      notice, this list of conditions and the following disclaimer.
11
12   2. The end-user documentation included with the redistribution,
13      if any, must include the following acknowledgment:
14      "This product includes software parts from hipergate
15      (http://www.hipergate.org/)."
16      Alternately, this acknowledgment may appear in the software itself,
17      if and wherever such third-party acknowledgments normally appear.
18
19   3. The name hipergate must not be used to endorse or promote products
20      derived from this software without prior written permission.
21      Products derived from this software may not be called hipergate,
22      nor may hipergate appear in their name, without prior written
23      permission.
24
25   This library is distributed in the hope that it will be useful,
26   but WITHOUT ANY WARRANTY; without even the implied warranty of
27   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
28
29   You should have received a copy of hipergate License with this code;
30   if not, visit http://www.hipergate.org or mail to info@hipergate.org
31 */

32
33 package com.knowgate.misc;
34
35 import java.lang.StringBuffer JavaDoc;
36 import java.lang.System JavaDoc;
37
38 import java.util.Random JavaDoc;
39 import java.util.Date JavaDoc;
40 import java.util.StringTokenizer JavaDoc;
41 import java.util.Collection JavaDoc;
42 import java.util.LinkedList JavaDoc;
43 import java.util.Iterator JavaDoc;
44 import java.util.Vector JavaDoc;
45 import java.util.ArrayList JavaDoc;
46 import java.util.Currency JavaDoc;
47 import java.util.Locale JavaDoc;
48
49 import java.math.BigDecimal JavaDoc;
50
51 import java.text.DecimalFormat JavaDoc;
52 import java.text.FieldPosition JavaDoc;
53 import java.text.NumberFormat JavaDoc;
54
55 import java.net.InetAddress JavaDoc;
56 import java.net.UnknownHostException JavaDoc;
57
58 import org.apache.oro.text.regex.*;
59
60 import com.knowgate.debug.DebugFile;
61
62 /**
63  * Miscellaneous functions and utilities.
64  * @author Sergio Montoro Ten
65  * @version 2.1
66  */

67 public final class Gadgets {
68
69   private static int iSequence = 1048576;
70
71   private static DecimalFormat JavaDoc oFmt2 = null;
72   private static FieldPosition JavaDoc oFrac = null;
73   private static Currency JavaDoc oCurr = null;
74   private static String JavaDoc sCurr = null;
75
76   private static PatternMatcher oMatcher = null;
77   private static PatternCompiler oCompiler = null;
78
79   public Gadgets() { }
80
81   private static String JavaDoc[] byteToStr = {
82                                  "00","01","02","03","04","05","06","07","08","09","0a","0b","0c","0d","0e","0f",
83                                  "10","11","12","13","14","15","16","17","18","19","1a","1b","1c","1d","1e","1f",
84                                  "20","21","22","23","24","25","26","27","28","29","2a","2b","2c","2d","2e","2f",
85                                  "30","31","32","33","34","35","36","37","38","39","3a","3b","3c","3d","3e","3f",
86                                  "40","41","42","43","44","45","46","47","48","49","4a","4b","4c","4d","4e","4f",
87                                  "50","51","52","53","54","55","56","57","58","59","5a","5b","5c","5d","5e","5f",
88                                  "60","61","62","63","64","65","66","67","68","69","6a","6b","6c","6d","6e","6f",
89                                  "70","71","72","73","74","75","76","77","78","79","7a","7b","7c","7d","7e","7f",
90                                  "80","81","82","83","84","85","86","87","88","89","8a","8b","8c","8d","8e","8f",
91                                  "90","91","92","93","94","95","96","97","98","99","9a","9b","9c","9d","9e","9f",
92                                  "a0","a1","a2","a3","a4","a5","a6","a7","a8","a9","aa","ab","ac","ad","ae","af",
93                                  "b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","ba","bb","bc","bd","be","bf",
94                                  "c0","c1","c2","c3","c4","c5","c6","c7","c8","c9","ca","cb","cc","cd","ce","cf",
95                                  "d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","da","db","dc","dd","de","df",
96                                  "e0","e1","e2","e3","e4","e5","e6","e7","e8","e9","ea","eb","ec","ed","ee","ef",
97                                  "f0","f1","f2","f3","f4","f5","f6","f7","f8","f9","fa","fb","fc","fd","fe","ff" };
98
99   //-----------------------------------------------------------
100

101   /**
102    * Generate an universal unique identifier
103    * @return An hexadecimal string of 32 characters,
104    * created using the machine IP address, current system date, a randon number
105    * and a sequence.
106    */

107   public static String JavaDoc generateUUID() {
108
109     int iRnd;
110     long lSeed = new Date JavaDoc().getTime();
111     Random JavaDoc oRnd = new Random JavaDoc(lSeed);
112     String JavaDoc sHex;
113     StringBuffer JavaDoc sUUID = new StringBuffer JavaDoc(32);
114     byte[] localIPAddr = new byte[4];
115
116     try {
117
118       // 8 characters Code IP address of this machine
119
localIPAddr = InetAddress.getLocalHost().getAddress();
120
121       sUUID.append(byteToStr[((int) localIPAddr[0]) & 255]);
122       sUUID.append(byteToStr[((int) localIPAddr[1]) & 255]);
123       sUUID.append(byteToStr[((int) localIPAddr[2]) & 255]);
124       sUUID.append(byteToStr[((int) localIPAddr[3]) & 255]);
125     }
126     catch (UnknownHostException JavaDoc e) {
127       // Use localhost by default
128
sUUID.append("7F000000");
129     }
130
131     // Append a seed value based on current system date
132
sUUID.append(Long.toHexString(lSeed));
133
134     // 6 characters - an incremental sequence
135
sUUID.append(Integer.toHexString(iSequence++));
136
137     if (iSequence>16777000) iSequence=1048576;
138
139     do {
140       iRnd = oRnd.nextInt();
141       if (iRnd>0) iRnd = -iRnd;
142       sHex = Integer.toHexString(iRnd);
143     } while (0==iRnd);
144
145     // Finally append a random number
146
sUUID.append(sHex);
147
148     return sUUID.substring(0, 32);
149   } // generateUUID()
150

151   //-----------------------------------------------------------
152

153   /**
154    * <p>Return text enconded as XHTML.</p>
155    * ASCII-7 character are returned as they are,any other character is returned as &#<i>code</i>;
156    * @param text String
157    * @return String
158    */

159   public static String JavaDoc XHTMLEncode(String JavaDoc text) {
160     char c;
161     int len = text.length();
162     StringBuffer JavaDoc results = new StringBuffer JavaDoc(len*2);
163
164     for (int i = 0; i < len; ++i) {
165       c = text.charAt(i);
166       if (c>=32 && c<=127)
167         results.append(c);
168       else
169         results.append("&#"+String.valueOf((int)c)+";");
170     }
171     return results.toString();
172   }
173
174   //-----------------------------------------------------------
175

176   /**
177    * <p>Return text enconded as HTML.</p>
178    * For example "Tom & Jerry" is encoded as "Tom &amp; Jerry"
179    * @param text Text to encode
180    * @return HTML-encoded text
181    */

182   public static String JavaDoc HTMLEncode(String JavaDoc text) {
183     if (text == null) return "";
184
185     char c;
186     int len = text.length();
187     StringBuffer JavaDoc results = new StringBuffer JavaDoc(len);
188
189     for (int i = 0; i < len; ++i) {
190       c = text.charAt(i);
191       switch (c) {
192             case '&':
193               results.append("&amp;");
194               break;
195             case '<':
196               results.append("&lt;");
197               break;
198             case '>':
199               results.append("&gt;");
200               break;
201             case 39:
202               results.append("&#39;");
203               break;
204             case '"':
205               results.append("&quot;");
206               break;
207             case '¡':
208               results.append("&iexcl;");
209               break;
210             case '¤':
211               results.append("&curren;");
212               break;
213             case '¥':
214               results.append("&yen;");
215               break;
216             case '|':
217               results.append("&brvbar;");
218               break;
219             case '§':
220               results.append("&sect;");
221               break;
222             case '¨':
223               results.append("&uml;");
224               break;
225             case '©':
226               results.append("&copy;");
227               break;
228             case 'ª':
229               results.append("&ordf;");
230               break;
231             case '«':
232               results.append("&laquo;");
233               break;
234             case '»':
235               results.append("&raquo;");
236               break;
237             case '€':
238               results.append("&euro;");
239               break;
240             case '£':
241               results.append("&pound;");
242               break;
243             case '­':
244               results.append("&shy;");
245               break;
246             case '®':
247               results.append("&reg;");
248               break;
249             case '¯':
250               results.append("&macr;");
251               break;
252             case '°':
253               results.append("&deg;");
254               break;
255             case '±':
256               results.append("&plusmn;");
257               break;
258             case '¹':
259               results.append("&sup1;");
260               break;
261             case '²':
262               results.append("&sup2;");
263               break;
264             case '³':
265               results.append("&sup3;");
266               break;
267             case '´':
268               results.append("&acute;");
269               break;
270             case 'µ':
271               results.append("&micro;");
272               break;
273             case '¶':
274               results.append("&para;");
275               break;
276             case '·':
277               results.append("&middot;");
278               break;
279             case '¸':
280               results.append("&cedil;");
281               break;
282             case 'º':
283               results.append("&ordm;");
284               break;
285             case '¿':
286               results.append("&iquest;");
287               break;
288             case 'ñ':
289               results.append("&ntilde;");
290               break;
291             case 'Ñ':
292               results.append("&Ntilde;");
293               break;
294             case 'á':
295               results.append("&aacute;");
296               break;
297             case 'é':
298               results.append("&eacute;");
299               break;
300             case 'í':
301               results.append("&iacute;");
302               break;
303             case 'ó':
304               results.append("&oacute;");
305               break;
306             case 'ú':
307               results.append("&uacute;");
308               break;
309             case 'ü':
310               results.append("&uuml;");
311               break;
312             case 'Á':
313               results.append("&Aacute;");
314               break;
315             case 'À':
316               results.append("&Agrave;");
317               break;
318             case 'Ä':
319               results.append("&Auml;");
320               break;
321             case 'Â':
322               results.append("&Acirc;");
323               break;
324             case 'Å':
325               results.append("&Aring;");
326               break;
327             case 'É':
328               results.append("&Eacute;");
329               break;
330             case 'È':
331               results.append("&Egrave;");
332               break;
333             case 'Ë':
334               results.append("&Euml;");
335               break;
336             case 'Ê':
337               results.append("&Ecirc;");
338               break;
339             case 'Í':
340               results.append("&Iacute;");
341               break;
342             case 'Ì':
343               results.append("&Igrave;");
344               break;
345             case 'Ï':
346               results.append("&Iuml;");
347               break;
348             case 'Î':
349               results.append("&Icirc;");
350               break;
351             case 'Ó':
352               results.append("&Oacute;");
353               break;
354             case 'Ò':
355               results.append("&Ograve;");
356               break;
357             case 'Ö':
358               results.append("&Ouml;");
359               break;
360             case 'Ô':
361               results.append("&Ocirc;");
362               break;
363             case 'Ú':
364               results.append("&Uacute;");
365               break;
366             case 'Ù':
367               results.append("&Ugrave;");
368               break;
369             case 'Ü':
370               results.append("&Uuml;");
371               break;
372             case 'Û':
373               results.append("&Ucirc;");
374               break;
375             case '½':
376               results.append("&frac12;");
377               break;
378             case '¾':
379               results.append("&frac34;");
380               break;
381             case '¼':
382               results.append("&frac14;");
383               break;
384             case 'Ç':
385               results.append("&Ccedil;");
386               break;
387             case 'ç':
388               results.append("&ccedil;");
389               break;
390             case 'ð':
391               results.append("&eth;");
392               break;
393             case '¢':
394               results.append("&cent;");
395               break;
396             case 'Þ':
397               results.append("&THORN;");
398               break;
399             case 'þ':
400               results.append("&thorn;");
401               break;
402             case 'Ð':
403               results.append("&ETH;");
404               break;
405             case '×':
406               results.append("&times;");
407               break;
408             case '÷':
409               results.append("&divide;");
410               break;
411             case 'Æ':
412               results.append("&AElig;");
413               break;
414
415               /*
416                            uml => chr 168, #umlaut (dieresis)
417                            laquo => chr 171, #angle quotation mark, left
418                            not => chr 172, #not sign
419                            shy => chr 173, #soft hyphen
420                            reg => chr 174, #registered sign
421                            macr => chr 175, #macron
422                            deg => chr 176, #degree sign
423                            sup2 => chr 178, #superscript two
424                            sup3 => chr 179, #superscript three
425                            acute => chr 180, #acute accent
426                            micro => chr 181, #micro sign
427                            para => chr 182, #pilcrow (paragraph sign)
428                            cedil => chr 184, #cedilla
429                            sup1 => chr 185, #superscript one
430                            raquo => chr 187, #angle quotation mark, right
431                            iquest => chr 191, #inverted question mark
432                            Auml => chr 196, #capital A, dieresis or umlaut mark
433                            Aring => chr 197, #capital A, ring
434                            Ccedil => chr 199, #capital C, cedilla
435                            Egrave => chr 200, #capital E, grave accent
436                            Eacute => chr 201, #capital E, acute accent
437                            Ecirc => chr 202, #capital E, circumflex accent
438                            Euml => chr 203, #capital E, dieresis or umlaut mark
439                            Igrave => chr 204, #capital I, grave accent
440                            Iacute => chr 205, #capital I, acute accent
441                            Icirc => chr 206, #capital I, circumflex accent
442                            Iuml => chr 207, #capital I, dieresis or umlaut mark
443                            Ouml => chr 214, #capital O, dieresis or umlaut mark
444                            Oslash => chr 216, #capital O, slash
445                            Ugrave => chr 217, #capital U, grave accent
446                            Uacute => chr 218, #capital U, acute accent
447                            Ucirc => chr 219, #capital U, circumflex accent
448                            Uuml => chr 220, #capital U, dieresis or umlaut mark
449                            Yacute => chr 221, #capital Y, acute accent
450                            szlig => chr 223, #small sharp s, German (sz ligature)
451                            agrave => chr 224, #small a, grave accent
452                            aacute => chr 225, #small a, acute accent
453                            acirc => chr 226, #small a, circumflex accent
454                            atilde => chr 227, #small a, tilde
455                            auml => chr 228, #small a, dieresis or umlaut mark
456                            aring => chr 229, #small a, ring
457                            aelig => chr 230, #small ae diphthong (ligature)
458                            ccedil => chr 231, #small c, cedilla
459                            egrave => chr 232, #small e, grave accent
460                            eacute => chr 233, #small e, acute accent
461                            ecirc => chr 234, #small e, circumflex accent
462                            euml => chr 235, #small e, dieresis or umlaut mark
463                            igrave => chr 236, #small i, grave accent
464                            iacute => chr 237, #small i, acute accent
465                            icirc => chr 238, #small i, circumflex accent
466                            iuml => chr 239, #small i, dieresis or umlaut mark
467                            eth => chr 240, #small eth, Icelandic
468                            ntilde => chr 241, #small n, tilde
469                            ograve => chr 242, #small o, grave accent
470                            oacute => chr 243, #small o, acute accent
471                            ocirc => chr 244, #small o, circumflex accent
472                            otilde => chr 245, #small o, tilde
473                            ouml => chr 246, #small o, dieresis or umlaut mark
474                            divide => chr 247, #divide sign
475                            oslash => chr 248, #small o, slash
476                            ugrave => chr 249, #small u, grave accent
477                            uacute => chr 250, #small u, acute accent
478                            ucirc => chr 251, #small u, circumflex accent
479                            uuml => chr 252, #small u, dieresis or umlaut mark
480                            yacute => chr 253, #small y, acute accent
481                            thorn => chr 254, #small thorn, Icelandic
482                            yuml => chr 255, #small y, dieresis or umlaut mark
483
484                              <!ENTITY Atilde CDATA "&#195;" -- latin capital letter A with tilde,
485                                                                U+00C3 ISOlat1 -->
486                              <!ENTITY Aring CDATA "&#197;" -- latin capital letter A with ring above
487                                                                = latin capital letter A ring,
488                                                                U+00C5 ISOlat1 -->
489                              <!ENTITY AElig CDATA "&#198;" -- latin capital letter AE
490                                                                = latin capital ligature AE,
491                                                                U+00C6 ISOlat1 -->
492                              <!ENTITY Egrave CDATA "&#200;" -- latin capital letter E with grave,
493                                                                U+00C8 ISOlat1 -->
494                              <!ENTITY Eacute CDATA "&#201;" -- latin capital letter E with acute,
495                                                                U+00C9 ISOlat1 -->
496                              <!ENTITY Ecirc CDATA "&#202;" -- latin capital letter E with circumflex,
497                                                                U+00CA ISOlat1 -->
498                              <!ENTITY Euml CDATA "&#203;" -- latin capital letter E with diaeresis,
499                                                                U+00CB ISOlat1 -->
500                              <!ENTITY Igrave CDATA "&#204;" -- latin capital letter I with grave,
501                                                                U+00CC ISOlat1 -->
502                              <!ENTITY Iacute CDATA "&#205;" -- latin capital letter I with acute,
503                                                                U+00CD ISOlat1 -->
504                              <!ENTITY Icirc CDATA "&#206;" -- latin capital letter I with circumflex,
505                                                                U+00CE ISOlat1 -->
506                              <!ENTITY Iuml CDATA "&#207;" -- latin capital letter I with diaeresis,
507                                                                U+00CF ISOlat1 -->
508                              <!ENTITY ETH CDATA "&#208;" -- latin capital letter ETH, U+00D0 ISOlat1 -->
509                              <!ENTITY Ograve CDATA "&#210;" -- latin capital letter O with grave,
510                                                                U+00D2 ISOlat1 -->
511                              <!ENTITY Oacute CDATA "&#211;" -- latin capital letter O with acute,
512                                                                U+00D3 ISOlat1 -->
513                              <!ENTITY Ocirc CDATA "&#212;" -- latin capital letter O with circumflex,
514                                                                U+00D4 ISOlat1 -->
515                              <!ENTITY Otilde CDATA "&#213;" -- latin capital letter O with tilde,
516                                                                U+00D5 ISOlat1 -->
517                              <!ENTITY Ouml CDATA "&#214;" -- latin capital letter O with diaeresis,
518                                                                U+00D6 ISOlat1 -->
519                              <!ENTITY times CDATA "&#215;" -- multiplication sign, U+00D7 ISOnum -->
520                              <!ENTITY Oslash CDATA "&#216;" -- latin capital letter O with stroke
521                                                                = latin capital letter O slash,
522                                                                U+00D8 ISOlat1 -->
523                              <!ENTITY Ugrave CDATA "&#217;" -- latin capital letter U with grave,
524                                                                U+00D9 ISOlat1 -->
525                              <!ENTITY Uacute CDATA "&#218;" -- latin capital letter U with acute,
526                                                                U+00DA ISOlat1 -->
527                              <!ENTITY Ucirc CDATA "&#219;" -- latin capital letter U with circumflex,
528                                                                U+00DB ISOlat1 -->
529                              <!ENTITY Uuml CDATA "&#220;" -- latin capital letter U with diaeresis,
530                                                                U+00DC ISOlat1 -->
531                              <!ENTITY Yacute CDATA "&#221;" -- latin capital letter Y with acute,
532                                                                U+00DD ISOlat1 -->
533                              <!ENTITY THORN CDATA "&#222;" -- latin capital letter THORN,
534                                                                U+00DE ISOlat1 -->
535                              <!ENTITY szlig CDATA "&#223;" -- latin small letter sharp s = ess-zed,
536                                                                U+00DF ISOlat1 -->
537                              <!ENTITY agrave CDATA "&#224;" -- latin small letter a with grave
538                                                                = latin small letter a grave,
539                                                                U+00E0 ISOlat1 -->
540                              <!ENTITY aacute CDATA "&#225;" -- latin small letter a with acute,
541                                                                U+00E1 ISOlat1 -->
542                              <!ENTITY acirc CDATA "&#226;" -- latin small letter a with circumflex,
543                                                                U+00E2 ISOlat1 -->
544                              <!ENTITY atilde CDATA "&#227;" -- latin small letter a with tilde,
545                                                                U+00E3 ISOlat1 -->
546                              <!ENTITY auml CDATA "&#228;" -- latin small letter a with diaeresis,
547                                                                U+00E4 ISOlat1 -->
548                              <!ENTITY aring CDATA "&#229;" -- latin small letter a with ring above
549                                                                = latin small letter a ring,
550                                                                U+00E5 ISOlat1 -->
551                              <!ENTITY aelig CDATA "&#230;" -- latin small letter ae
552                                                                = latin small ligature ae, U+00E6 ISOlat1 -->
553                              <!ENTITY egrave CDATA "&#232;" -- latin small letter e with grave,
554                                                                U+00E8 ISOlat1 -->
555                              <!ENTITY ecirc CDATA "&#234;" -- latin small letter e with circumflex,
556                                                                U+00EA ISOlat1 -->
557                              <!ENTITY euml CDATA "&#235;" -- latin small letter e with diaeresis,
558                                                                U+00EB ISOlat1 -->
559                              <!ENTITY igrave CDATA "&#236;" -- latin small letter i with grave,
560                                                                U+00EC ISOlat1 -->
561                              <!ENTITY iacute CDATA "&#237;" -- latin small letter i with acute,
562                                                                U+00ED ISOlat1 -->
563                              <!ENTITY icirc CDATA "&#238;" -- latin small letter i with circumflex,
564                                                                U+00EE ISOlat1 -->
565                              <!ENTITY iuml CDATA "&#239;" -- latin small letter i with diaeresis,
566                                                                U+00EF ISOlat1 -->
567                              <!ENTITY ograve CDATA "&#242;" -- latin small letter o with grave,
568                                                                U+00F2 ISOlat1 -->
569                              <!ENTITY oacute CDATA "&#243;" -- latin small letter o with acute,
570                                                                U+00F3 ISOlat1 -->
571                              <!ENTITY ocirc CDATA "&#244;" -- latin small letter o with circumflex,
572                                                                U+00F4 ISOlat1 -->
573                              <!ENTITY otilde CDATA "&#245;" -- latin small letter o with tilde,
574                                                                U+00F5 ISOlat1 -->
575                              <!ENTITY ouml CDATA "&#246;" -- latin small letter o with diaeresis,
576                                                                U+00F6 ISOlat1 -->
577                              <!ENTITY divide CDATA "&#247;" -- division sign, U+00F7 ISOnum -->
578                              <!ENTITY oslash CDATA "&#248;" -- latin small letter o with stroke,
579                                                                = latin small letter o slash,
580                                                                U+00F8 ISOlat1 -->
581                              <!ENTITY ugrave CDATA "&#249;" -- latin small letter u with grave,
582                                                                U+00F9 ISOlat1 -->
583                              <!ENTITY uacute CDATA "&#250;" -- latin small letter u with acute,
584                                                                U+00FA ISOlat1 -->
585                              <!ENTITY ucirc CDATA "&#251;" -- latin small letter u with circumflex,
586                                                                U+00FB ISOlat1 -->
587                              <!ENTITY uuml CDATA "&#252;" -- latin small letter u with diaeresis,
588                                                                U+00FC ISOlat1 -->
589                              <!ENTITY yacute CDATA "&#253;" -- latin small letter y with acute,
590                                                                U+00FD ISOlat1 -->
591                              <!ENTITY thorn CDATA "&#254;" -- latin small letter thorn,
592                                                                U+00FE ISOlat1 -->
593                              <!ENTITY yuml CDATA "&#255;" -- latin small letter y with diaeresis,
594                                                                U+00FF ISOlat1 -->
595
596               */

597             default:
598               if (c<256)
599                 results.append(c);
600               else
601                 results.append("&#"+String.valueOf(c)+";");
602           } // end switch (c)
603
} // end for (i)
604

605     return results.toString();
606   } // HTMLEncode
607

608   //-----------------------------------------------------------
609

610   public static String JavaDoc HTMLDencode(String JavaDoc text) {
611     if (text == null) return "";
612
613     char c,d;
614     int len = text.length();
615     StringBuffer JavaDoc results = new StringBuffer JavaDoc(len);
616
617     final String JavaDoc[] aEnts = {"amp;", "lt;", "gt;", "quot;", "iexcl;", "curren;", "yen;", "brvbar;", "sect;",
618                            "uml;", "copy;", "ordf;", "laquo;", "raquo;", "euro;", "pound;", "shy;", "reg;",
619                            "macr;", "deg;", "plusmn;", "sup1;", "sup2;", "sup3;", "acute;", "micro;", "para;",
620                            "middot;", "cedil;", "ordm;", "iquest;", "ntilde;", "Ntilde;", "aacute;", "eacute;", "iacute;",
621                            "oacute;", "uacute;", "uuml;", "Aacute;", "Agrave;", "Auml;", "Acirc;", "Aring;", "Eacute;",
622                            "Egrave;", "Euml;", "Ecirc;", "Iacute;", "Igrave;", "Iuml;", "Icirc;", "Oacute;", "Ograve;",
623                            "Ouml;", "Ocirc;", "Uacute;", "Ugrave;", "Uuml;", "Ucirc;", "frac12;", "frac34;", "frac14;",
624                            "Ccedil;", "ccedil;", "eth;", "cent;", "THORN;", "thorn;", "ETH;", "times;", "divide;",
625                            "AElig;"
626                            };
627
628     final String JavaDoc[] aChars= {"&", "<", ">", "\"", "¡", "¤", "¥", "|", "§",
629                             "¨", "©", "ª", "«" , "»", "€", "£", "­", "®",
630                             "¯", "°", "±", "¹" , "²", "³", "´", "µ", "¶",
631                             "·", "¸", "º", "¿" , "ñ", "Ñ", "á", "é", "í",
632                             "ó", "ú", "ü", "Á" , "À", "Ä", "Â", "Å", "É",
633                             "È", "Ë", "Ê", "Í" , "Ì", "Ï", "Î", "Ó", "Ò",
634                             "Ö", "Ô", "Ú", "Ù" , "Ü", "Û", "½", "¾", "¼",
635                             "Ç", "ç", "ð", "¢" , "Þ", "þ", "Ð", "×", "÷",
636                             "Æ"
637                            };
638
639     final int iEnts = aEnts.length;
640
641     for (int i = 0; i < len; ++i) {
642       c = text.charAt(i);
643       if (c=='&' && i<len-3) {
644         try {
645           if (text.charAt(i+1)=='#') {
646             int semicolon = text.indexOf(59, i+1);
647             if (semicolon>0) {
648               results.append( (char) Integer.parseInt(text.substring(i + 2, semicolon)));
649               i = semicolon+1;
650             }
651             else {
652               results.append(c);
653             }
654           }
655           else {
656             for (int e=0; e<iEnts; e++) {
657               if (text.substring(i+1, i+aEnts[e].length()).equals(aEnts[e]))
658                 results.append(aChars[e]);
659             }
660           }
661         } catch (StringIndexOutOfBoundsException JavaDoc siob) {
662           return results.toString();
663         }
664       }
665       else {
666         results.append(c);
667       }
668     } // next (i)
669

670     return results.toString();
671   } // HTMLDencode
672

673   // ----------------------------------------------------------
674

675   /**
676    * Return text enconded as an URL.
677    * For example, "Tom's Bookmarks" is encodes as "Tom%27s%20Bookmarks"
678    * @param sStr Text to encode
679    * @return URL-encoded text
680    */

681   public static String JavaDoc URLEncode (String JavaDoc sStr) {
682     if (sStr==null) return null;
683
684     int iLen = sStr.length();
685     StringBuffer JavaDoc sEscaped = new StringBuffer JavaDoc(iLen+100);
686     char c;
687     for (int p=0; p<iLen; p++) {
688       c = sStr.charAt(p);
689       switch (c) {
690         case ' ':
691           sEscaped.append("%20");
692           break;
693         case '"':
694           sEscaped.append("%22");
695           break;
696         case '#':
697           sEscaped.append("%23");
698           break;
699         case '%':
700           sEscaped.append("%25");
701           break;
702         case '&':
703           sEscaped.append("%26");
704           break;
705         case (char)39:
706           sEscaped.append("%27");
707           break;
708         case ',':
709           sEscaped.append("%2C");
710           break;
711         case '=':
712           sEscaped.append("%3D");
713           break;
714         case '?':
715           sEscaped.append("%3F");
716           break;
717         case 'á':
718           sEscaped.append("%E1");
719           break;
720         case 'é':
721           sEscaped.append("%E9");
722           break;
723         case 'í':
724           sEscaped.append("%ED");
725           break;
726         case 'ó':
727           sEscaped.append("%F3");
728           break;
729         case 'ú':
730           sEscaped.append("%FA");
731           break;
732         case 'Á':
733           sEscaped.append("%C1");
734           break;
735         case 'É':
736           sEscaped.append("%C9");
737           break;
738         case 'Í':
739           sEscaped.append("%CD");
740           break;
741         case 'Ó':
742           sEscaped.append("%D3");
743           break;
744         case 'Ú':
745           sEscaped.append("%DA");
746           break;
747         case 'à':
748           sEscaped.append("%E0");
749           break;
750         case 'è':
751           sEscaped.append("%E8");
752           break;
753         case 'ì':
754           sEscaped.append("%EC");
755           break;
756         case 'ò':
757           sEscaped.append("%F2");
758           break;
759         case 'ù':
760           sEscaped.append("%F9");
761           break;
762         case 'À':
763           sEscaped.append("%C0");
764           break;
765         case 'È':
766           sEscaped.append("%C8");
767           break;
768         case 'Ì':
769           sEscaped.append("%CC");
770           break;
771         case 'Ò':
772           sEscaped.append("%D2");
773           break;
774         case 'Ù':
775           sEscaped.append("%D9");
776           break;
777         case 'ñ':
778           sEscaped.append("%F1");
779           break;
780         case 'Ñ':
781           sEscaped.append("%D1");
782           break;
783         case 'ç':
784           sEscaped.append("%E7");
785           break;
786         case 'Ç':
787           sEscaped.append("%C7");
788           break;
789         case 'ô':
790           sEscaped.append("%F4");
791           break;
792         case 'Ô':
793           sEscaped.append("%D4");
794           break;
795         case 'ö':
796           sEscaped.append("%F6");
797           break;
798         case 'Ö':
799           sEscaped.append("%D6");
800           break;
801         default:
802           sEscaped.append(c);
803           break;
804       }
805     } // next
806

807     return sEscaped.toString();
808   } // URLEncode
809

810   // ----------------------------------------------------------
811

812   /**
813    * Convert an ASCII-8 String to an ASCII-7 String
814    */

815   public static String JavaDoc ASCIIEncode (String JavaDoc sStrIn) {
816     if (sStrIn==null) return null;
817
818     int iLen = sStrIn.length();
819
820     if (iLen==0) return sStrIn;
821
822     StringBuffer JavaDoc sStrBuff = new StringBuffer JavaDoc(iLen);
823     String JavaDoc sStr = sStrIn.toUpperCase();
824
825     for (int c=0; c<iLen; c++) {
826       switch (sStr.charAt(c)) {
827         case 'Á':
828         case 'À':
829         case 'Ä':
830         case 'Â':
831         case 'Å':
832           sStrBuff.append('A');
833           break;
834         case 'É':
835         case 'È':
836         case 'Ë':
837         case 'Ê':
838           sStrBuff.append('E');
839           break;
840         case 'Í':
841         case 'Ì':
842         case 'Ï':
843         case 'Î':
844           sStrBuff.append('I');
845           break;
846         case 'Ó':
847         case 'Ò':
848         case 'Ö':
849         case 'Ô':
850         case 'Ø':
851           sStrBuff.append('O');
852           break;
853         case 'Ú':
854         case 'Ù':
855         case 'Ü':
856         case 'Û':
857           sStrBuff.append('U');
858           break;
859         case 'Æ':
860           sStrBuff.append('E');
861           break;
862         case 'Ñ':
863           sStrBuff.append('N');
864           break;
865         case 'Ç':
866           sStrBuff.append('C');
867           break;
868         case '°':
869           sStrBuff.append('o');
870           break;
871         case '\\':
872         case '.':
873         case '/':
874           sStrBuff.append('_');
875           break;
876         case '&':
877           sStrBuff.append('A');
878           break;
879         case ':':
880           sStrBuff.append(';');
881           break;
882         case '<':
883           sStrBuff.append('L');
884           break;
885         case '>':
886           sStrBuff.append('G');
887           break;
888         case '"':
889           sStrBuff.append((char)39);
890           break;
891         case '|':
892           sStrBuff.append('P');
893           break;
894         case '¡':
895           sStrBuff.append('E');
896           break;
897         case '¿':
898         case '?':
899           sStrBuff.append('Q');
900           break;
901         case '*':
902           sStrBuff.append('W');
903           break;
904         case '%':
905           sStrBuff.append('P');
906           break;
907         case 'ß':
908           sStrBuff.append('B');
909           break;
910         case '¥':
911           sStrBuff.append('Y');
912           break;
913         case (char)255:
914           sStrBuff.append('_');
915           break;
916         default:
917           sStrBuff.append(sStr.charAt(c));
918       } // end switch
919
} // next ()
920
return sStrBuff.toString();
921   } // ASCIIEncode
922

923   // ----------------------------------------------------------
924

925   /**
926    * Split a String in two parts
927    * This method is a special case optimization of split() to be used when
928    * the input string is to be splitted by a single character delimiter and
929    * there at most one occurrence of that delimiter.
930    * @param sInputStr String to split
931    * @param cDelimiter Single character to be used as delimiter,
932    * the String will be splited on the first occurence of character.
933    * @return If cDelimiter is not found, or cDelimiter if found as the first
934    * character of sInputStr or cDelimiter if found as the last character of
935    * sInputStr then an array with a single String element is returned. If
936    * cDelimiter is found somewhere in the middle of sInputStr then an array
937    * with 2 elements is returned.
938    * @throws NullPointerException If sInputStr is <b>null</b>
939    */

940   public static String JavaDoc[] split2(String JavaDoc sInputStr, char cDelimiter)
941     throws NullPointerException JavaDoc {
942
943     int iDelim = sInputStr.indexOf(cDelimiter);
944
945     if (iDelim<0)
946       return new String JavaDoc[]{sInputStr};
947     else if (iDelim==0)
948       return new String JavaDoc[]{"", sInputStr.substring(iDelim+1)};
949     else if (iDelim==sInputStr.length()-1)
950       return new String JavaDoc[]{sInputStr.substring(0, iDelim), ""};
951     else
952       return new String JavaDoc[]{sInputStr.substring(0, iDelim), sInputStr.substring(iDelim+1)};
953   } // split2
954

955   // ----------------------------------------------------------
956

957   /**
958    * Split a String in two parts
959    * This method is a special case optimization of split() to be used when
960    * the input string is to be splitted by a variable length delimiter and
961    * there at most one occurrence of that delimiter.
962    * @param sInputStr String to split
963    * @param sDelimiter String to be used as delimiter,
964    * the String will be splited on the first occurence of sDelimiter.
965    * @return If sDelimiter is not found, or sInputStr starts with sDelimiter or
966    * sInputStr ends with sDelimiter then an array with a single String element
967    * is returned. If sDelimiter is found somewhere in the middle of sInputStr
968    * then an array with 2 elements is returned.
969    * @throws NullPointerException If sInputStr is <b>null</b>
970    */

971   public static String JavaDoc[] split2(String JavaDoc sInputStr, String JavaDoc sDelimiter)
972     throws NullPointerException JavaDoc {
973
974     int iDelim = sInputStr.indexOf(sDelimiter);
975
976     if (iDelim<0)
977       return new String JavaDoc[]{sInputStr};
978     else if (iDelim==0)
979       return new String JavaDoc[]{"", sInputStr.substring(iDelim+sDelimiter.length())};
980     else if (iDelim==sInputStr.length()-sDelimiter.length())
981       return new String JavaDoc[]{sInputStr.substring(0, iDelim), ""};
982     else
983       return new String JavaDoc[]{sInputStr.substring(0, iDelim), sInputStr.substring(iDelim+sDelimiter.length())};
984   } // split2
985

986   // ----------------------------------------------------------
987

988   /**
989    * <p>Split a String using a character delimiter</p>
990    * Contiguous delimiters with nothing in the middle will delimit empty substrings.<br>
991    * This is an important behaviour difference between Gadgets.split(String,String) and Gadgets.split(String,char).<br>
992    * Gadgets.split("1;;3;;5;6,";") will return String[4] but Gadgets.split("1;;3;;5;6,';') will return String[6]
993    * @param sInputStr String to split
994    * @param cDelimiter Character Delimiter
995    * @return An array with the splitted substrings
996    * @throws NullPointerException If sInputStr is <b>null</b>
997    */

998   public static String JavaDoc[] split(String JavaDoc sInputStr, char cDelimiter)
999     throws NullPointerException JavaDoc {
1000    int iStrLen = sInputStr.length();
1001    int iTokCount = 0;
1002
1003    if (DebugFile.trace) {
1004      DebugFile.writeln("Begin Gadgets.split(\"" + sInputStr + "\",'" + cDelimiter+ "')");
1005      DebugFile.incIdent();
1006    }
1007
1008    if (0==iStrLen) {
1009      if (DebugFile.trace) {
1010        DebugFile.decIdent();
1011        DebugFile.writeln("End Gadgets.split() : 0");
1012      }
1013      return null;
1014    }
1015
1016    for (int p=0; p<iStrLen; p++)
1017      if (sInputStr.charAt(p)==cDelimiter) iTokCount++;
1018
1019    if (DebugFile.trace) DebugFile.writeln(String.valueOf(iTokCount+1) + " tokens found");
1020
1021    String JavaDoc Tokens[] = new String JavaDoc[iTokCount+1];
1022
1023    int iToken = 0;
1024    int iLast = 0;
1025    for (int iNext=0; iNext<iStrLen; iNext++) {
1026      if (sInputStr.charAt(iNext)==cDelimiter) {
1027        if (iLast==iNext)
1028          Tokens[iToken] = "";
1029        else
1030          Tokens[iToken] = sInputStr.substring(iLast, iNext);
1031      iLast = iNext + 1;
1032      iToken++;
1033      } // fi (sInputStr[iNext]==cDelimiter)
1034
} // next
1035

1036    if (iLast>=iStrLen)
1037      Tokens[iToken] = "";
1038    else
1039      Tokens[iToken] = sInputStr.substring(iLast, iStrLen);
1040
1041    if (DebugFile.trace) {
1042      DebugFile.decIdent();
1043      DebugFile.writeln("End Gadgets.split()");
1044    }
1045    return Tokens;
1046  } // split
1047

1048  // ----------------------------------------------------------
1049

1050  /**
1051   * <p>Split a String using any of the given characters as delimiter</p>
1052   * @param aDelimiter Character Delimiter Array
1053   * @return An array with the splitted substrings
1054   * @throws NullPointerException If sInputStr is <b>null</b> or aDelimiter is <b>null</b>
1055   */

1056  public static String JavaDoc[] split(String JavaDoc sInputStr, char[] aDelimiter)
1057    throws NullPointerException JavaDoc {
1058    int iStrLen = sInputStr.length();
1059    int iTokCount = 0;
1060    int iDelimCount = aDelimiter.length;
1061    int d;
1062    boolean b;
1063
1064    if (DebugFile.trace) {
1065      DebugFile.writeln("Begin Gadgets.split(\"" + sInputStr + "\",char[])");
1066      DebugFile.incIdent();
1067    }
1068
1069    if (0==iStrLen) {
1070      if (DebugFile.trace) {
1071        DebugFile.decIdent();
1072        DebugFile.writeln("End Gadgets.split() : 0");
1073      }
1074      return null;
1075    }
1076
1077    for (int p=0; p<iStrLen; p++) {
1078      for (d=0,b=false; d<iDelimCount && !b; d++) b=(sInputStr.charAt(p)==aDelimiter[d]);
1079      if (b) iTokCount++;
1080    }
1081
1082    if (DebugFile.trace) DebugFile.writeln(String.valueOf(iTokCount+1) + " tokens found");
1083
1084    String JavaDoc Tokens[] = new String JavaDoc[iTokCount+1];
1085
1086    int iToken = 0;
1087    int iLast = 0;
1088    for (int iNext=0; iNext<iStrLen; iNext++) {
1089      for (d=0,b=false; d<iDelimCount && !b; d++) b=(sInputStr.charAt(iNext)==aDelimiter[d]);
1090      if (b) {
1091        if (iLast==iNext)
1092          Tokens[iToken] = "";
1093        else
1094          Tokens[iToken] = sInputStr.substring(iLast, iNext);
1095      iLast = iNext + 1;
1096      iToken++;
1097      } // fi (sInputStr[iNext]==cDelimiter)
1098
} // next
1099

1100    if (iLast>=iStrLen)
1101      Tokens[iToken] = "";
1102    else
1103      Tokens[iToken] = sInputStr.substring(iLast, iStrLen);
1104
1105    if (DebugFile.trace) {
1106      DebugFile.decIdent();
1107      DebugFile.writeln("End Gadgets.split()");
1108    }
1109    return Tokens;
1110  } // split
1111

1112  // ----------------------------------------------------------
1113

1114  /**
1115   * <p>Split a String using a substring delimiter</p>
1116   * Contiguous delimiters with nothing in the middle will be considered has a single delimiter.<br>
1117   * This is an important behaviour difference between Gadgets.split(String,String) and Gadgets.split(String,char).<br>
1118   * Gadgets.split("1;;3;;5;6,";") will return String[4] but Gadgets.split("1;;3;;5;6,';') will return String[6]
1119   * @param sInputStr String to split
1120   * @param sDelimiter Substring Delimiter (no regular expressions allowed)
1121   * @return An array with the splitted substrings
1122   * @throws NullPointerException If sInputStr is <b>null</b>
1123   */

1124  public static String JavaDoc[] split(String JavaDoc sInputStr, String JavaDoc sDelimiter)
1125    throws NullPointerException JavaDoc {
1126
1127    if (DebugFile.trace) {
1128      DebugFile.writeln("Begin Gadgets.split(\"" + sInputStr + "\",\"" + sDelimiter+ "\")");
1129      DebugFile.incIdent();
1130    }
1131
1132    // Split an input String by a given delimiter and return an array
1133
StringTokenizer JavaDoc oTokenizer = new StringTokenizer JavaDoc(sInputStr, sDelimiter);
1134    int iTokCount = oTokenizer.countTokens();
1135    int iTok = 0;
1136    String JavaDoc Tokens[] = null;
1137
1138    if (DebugFile.trace) DebugFile.writeln(String.valueOf(iTokCount) + " tokens found");
1139
1140    if(iTokCount>0) {
1141      Tokens = new String JavaDoc[iTokCount];
1142      while (oTokenizer.hasMoreTokens()) {
1143        Tokens[iTok] = oTokenizer.nextToken();
1144        if (DebugFile.trace) DebugFile.writeln("Token " + String.valueOf(iTok) + "=" + Tokens[iTok]);
1145        iTok++;
1146      } // wend
1147
}
1148
1149    if (DebugFile.trace) {
1150      DebugFile.decIdent();
1151      DebugFile.writeln("End Gadgets.split()");
1152    }
1153
1154    return Tokens;
1155  } // split
1156

1157  // ----------------------------------------------------------
1158

1159  /**
1160   * Join a Collection into a String
1161   * @param oList Collection to join
1162   * @param sDelimiter Delimiter for elements in resulting String
1163   * @return List joined as a String
1164   */

1165  public String JavaDoc join (Collection JavaDoc oList, String JavaDoc sDelimiter) {
1166    // Join a LinkedList into a single String
1167
StringBuffer JavaDoc oBuff = new StringBuffer JavaDoc(oList.size()*(32+sDelimiter.length())+1);
1168    Iterator JavaDoc oIter = oList.iterator();
1169
1170    while (oIter.hasNext()) {
1171      oBuff.append(oIter.next());
1172      oBuff.append(sDelimiter);
1173    } // wend()
1174

1175    oIter = null;
1176
1177    if (oBuff.length()>0)
1178      return oBuff.substring(0, oBuff.length()-sDelimiter.length()-1);
1179    else
1180      return "";
1181  } // join
1182

1183  // ----------------------------------------------------------
1184

1185  /**
1186   * Join an Array into a String
1187   * @param aList Array to join
1188   * @param sDelimiter Delimiter for elements in resulting String
1189   * @return List joined as a String
1190   * @since v3.0
1191   */

1192
1193  public String JavaDoc join (String JavaDoc[] aList, String JavaDoc sDelimiter) {
1194    if (null==aList) return null;
1195    final int iCount = aList.length;
1196    if (iCount==0) return "";
1197    if (null==sDelimiter) sDelimiter="";
1198
1199    // Join an array into a single String
1200
StringBuffer JavaDoc oBuff = new StringBuffer JavaDoc(iCount*(32+sDelimiter.length())+1);
1201    oBuff.append(aList[0]);
1202    for (int s=1; s<iCount; s++) {
1203      oBuff.append(sDelimiter);
1204      oBuff.append(aList[0]);
1205    }
1206    return oBuff.toString();
1207  } // join
1208

1209  // ----------------------------------------------------------
1210

1211   /**
1212    * <p>Split a String into a Collection using a character delimiter</p>
1213    * Contiguous delimiters with nothing in the middle will delimit empty substrings.
1214    * @param sInputStr String to split
1215    * @param cDelimiter Character Delimiter
1216    * @return A LinkedList splitted substrings
1217    * @throws NullPointerException If sInputStr is <b>null</b>
1218    */

1219
1220   public static Collection JavaDoc splitAsCollection(String JavaDoc sInputStr, char cDelimiter)
1221     throws NullPointerException JavaDoc {
1222     int iStrLen = sInputStr.length();
1223     int iTokCount = 0;
1224
1225     if (DebugFile.trace) {
1226       DebugFile.writeln("Begin Gadgets.splitAsCollection(\"" + sInputStr + "\",'" + cDelimiter+ "')");
1227       DebugFile.incIdent();
1228     }
1229
1230     LinkedList JavaDoc oTokens = new LinkedList JavaDoc();
1231
1232     int iLast = 0;
1233     for (int iNext=0; iNext<iStrLen; iNext++) {
1234       if (sInputStr.charAt(iNext)==cDelimiter) {
1235         if (iLast==iNext)
1236           oTokens.add("");
1237         else
1238           oTokens.add(sInputStr.substring(iLast, iNext));
1239       iLast = iNext + 1;
1240       } // fi (sInputStr[iNext]==cDelimiter)
1241
} // next
1242

1243     if (iLast>=iStrLen)
1244       oTokens.add("");
1245     else
1246       oTokens.add(sInputStr.substring(iLast, iStrLen));
1247
1248     if (DebugFile.trace) {
1249       DebugFile.decIdent();
1250       DebugFile.writeln("End Gadgets.splitAsCollection() : " + String.valueOf(oTokens.size()));
1251     }
1252     return oTokens;
1253   } // splitAsCollection
1254

1255  // ----------------------------------------------------------
1256

1257  /**
1258   * Get index of a substring inside another string
1259   * @param sSource String String to be scanned
1260   * @param sSought Substring to be sought
1261   * @param iStartAt int Index to start searching from
1262   * @return int Start index of substring or -1 if not found
1263   */

1264
1265  public static int indexOfIgnoreCase(String JavaDoc sSource, String JavaDoc sSought, int iStartAt) {
1266    if ((sSource==null) || (sSought==null)) return -1;
1267
1268    final int iSrcLen = sSource.length();
1269    final int iSghLen = sSought.length();
1270
1271    if (iSrcLen<iSghLen) return -1;
1272
1273    if (iSrcLen==iSghLen) return (sSource.equalsIgnoreCase(sSought) ? 0 : -1);
1274
1275    final int iReducedLen = iSrcLen-iSghLen;
1276
1277    if (iStartAt+iSghLen>iSrcLen) return -1;
1278
1279    for (int p=iStartAt; p<iReducedLen; p++) {
1280      if (sSource.substring(p, p+iSghLen).equalsIgnoreCase(sSought))
1281        return p;
1282    }
1283    return -1;
1284  }
1285
1286  // ----------------------------------------------------------
1287

1288  /**
1289   * Get index of a substring inside another string
1290   * @param sSource String String to be scanned
1291   * @param sSought Substring to be sought
1292   * @return int Start index of substring or -1 if not found
1293   */

1294  public static int indexOfIgnoreCase(String JavaDoc sSource, String JavaDoc sSought) {
1295    if ((sSource==null) || (sSought==null)) return -1;
1296
1297    final int iSrcLen = sSource.length();
1298    final int iSghLen = sSought.length();
1299
1300    if (iSrcLen<iSghLen) return -1;
1301
1302    if (iSrcLen==iSghLen) return (sSource.equalsIgnoreCase(sSought) ? 0 : -1);
1303
1304    final int iReducedLen = iSrcLen-iSghLen;
1305
1306    for (int p=0; p<iReducedLen; p++) {
1307      if (sSource.substring(p, p+iSghLen).equalsIgnoreCase(sSought))
1308        return p;
1309    }
1310    return -1;
1311  } // indexOfIgnoreCase
1312

1313  // ----------------------------------------------------------
1314

1315  /**
1316   * Fill String with a given character
1317   * @param c Character for filling
1318   * @param len Number of characters
1319   * @return A String with given numbers of characters
1320   * @throws IndexOutOfBoundsException if len<0
1321   */

1322  public static String JavaDoc fill(char c, int len) throws IndexOutOfBoundsException JavaDoc {
1323    // Return a String filled with a given character
1324
if (len<0)
1325      throw new IndexOutOfBoundsException JavaDoc("Gadgets.fill() numbers of characters must be greater than or equal to zero");
1326    else if (len==0)
1327      return "";
1328    else {
1329      StringBuffer JavaDoc oStrBuff = new StringBuffer JavaDoc(len);
1330      for (int i=0; i<len; i++) oStrBuff.append(c);
1331      return oStrBuff.toString();
1332    }
1333  } // fill
1334

1335  // ----------------------------------------------------------
1336

1337  /**
1338   * Check whether or not a String matches a regular expression
1339   * @param sSource String Source
1340   * @param sRegExp String Regular Expression
1341   * @return boolean <b>false</b> if either sSource or sRegExp are <b>null</b>
1342   * @throws MalformedPatternException
1343   * @since v3.0
1344   * @see http://www.savarese.org/oro/docs/OROMatcher/Syntax.html
1345   */

1346  public static boolean matches (String JavaDoc sSource, String JavaDoc sRegExp) throws MalformedPatternException {
1347    if (null==oMatcher) oMatcher = new Perl5Matcher();
1348    if (null==oCompiler) oCompiler = new Perl5Compiler();
1349
1350    if (sSource==null || sRegExp==null)
1351      return false;
1352    else
1353      return oMatcher.matches(sSource, oCompiler.compile(sRegExp));
1354  } // matches
1355

1356  // ----------------------------------------------------------
1357

1358  /**
1359   * Check whether or not a String contains a regular expression
1360   * @param sSource String Source
1361   * @param sRegExp String Regular Expression
1362   * @return boolean <b>false</b> if either sSource or sRegExp are <b>null</b>
1363   * @throws MalformedPatternException
1364   * @since v3.0
1365   * @see http://www.savarese.org/oro/docs/OROMatcher/Syntax.html
1366   */

1367  public static boolean contains (String JavaDoc sSource, String JavaDoc sRegExp) throws MalformedPatternException {
1368    if (null==oMatcher) oMatcher = new Perl5Matcher();
1369    if (null==oCompiler) oCompiler = new Perl5Compiler();
1370
1371    if (sSource==null || sRegExp==null)
1372      return false;
1373    else
1374      return oMatcher.contains(sSource, oCompiler.compile(sRegExp));
1375  } // contains
1376

1377  // ----------------------------------------------------------
1378

1379  /**
1380   * Get the first substring that matches the given regular expression
1381   * @param sSource String Source
1382   * @param sRegExp String Regular Expression
1383   * @return String if no substring matches the regular expression then <b>null</b> is returned
1384   * @throws MalformedPatternException
1385   * @since v3.0
1386   * @see http://jakarta.apache.org/oro/api/org/apache/oro/text/regex/Perl5Matcher.html
1387   */

1388  public static String JavaDoc getFirstMatchSubStr (String JavaDoc sSource, String JavaDoc sRegExp) throws MalformedPatternException {
1389    String JavaDoc sRetStr;
1390    if (sSource==null || sRegExp==null)
1391      sRetStr=null;
1392    else {
1393      if (null==oMatcher) oMatcher = new Perl5Matcher();
1394      if (null==oCompiler) oCompiler = new Perl5Compiler();
1395      if (oMatcher.contains(sSource, oCompiler.compile(sRegExp))) {
1396        sRetStr=oMatcher.getMatch().group(0);
1397      } else {
1398        sRetStr=null;
1399      }
1400    }
1401    return sRetStr;
1402  } // getFirstMatchSubStr
1403

1404  // ----------------------------------------------------------
1405

1406  /**
1407   * Replace a given pattern on a string with a fixed value
1408   * @param sSource Source String
1409   * @param sRegExp Regular Expression to be matched
1410   * @param sNewVal New value for replacement
1411   * @throws MalformedPatternException
1412   * @see http://www.savarese.org/oro/docs/OROMatcher/Syntax.html
1413   */

1414  public static String JavaDoc replace(String JavaDoc sSource, String JavaDoc sRegExp, String JavaDoc sNewVal) throws MalformedPatternException {
1415    Pattern oPattern;
1416    if (null==oMatcher) oMatcher = new Perl5Matcher();
1417    if (null==oCompiler) oCompiler = new Perl5Compiler();
1418
1419    oPattern = oCompiler.compile(sRegExp);
1420
1421    return Util.substitute(oMatcher, oPattern,
1422               new Perl5Substitution(sNewVal, Perl5Substitution.INTERPOLATE_ALL),
1423                           sSource, Util.SUBSTITUTE_ALL);
1424  } // replace
1425

1426  /**
1427   * Replace a given pattern on a string with a fixed value
1428   * @param sSource Source String
1429   * @param sRegExp Regular Expression to be matched
1430   * @param sNewVal New value for replacement
1431   * @param iOptions A set of flags giving the compiler instructions on how to
1432   * treat the regular expression. The flags are a logical OR of any number of
1433   * the five <a HREF="http://jakarta.apache.org/oro/api/org/apache/oro/text/regex/Perl5Compiler.html">
1434   * org.apache.oro.text.regex.Perl5Compiler</A> MASK constants.<br>
1435   * <table>
1436   * <tr><td>CASE_INSENSITIVE_MASK</td><td>Compiled regular expression should be case insensitive</td></tr>
1437   * <tr><td>DEFAULT_MASK</td><td>Use default mask for compile method</td></tr>
1438   * <tr><td>EXTENDED_MASK</td><td>compiled regular expression should be treated as a Perl5 extended pattern (i.e., a pattern using the /x modifier)</td></tr>
1439   * <tr><td>MULTILINE_MASK</td><td>Compiled regular expression should treat input as having multiple lines</td></tr>
1440   * <tr><td>READ_ONLY_MASK</td><td>Resulting Perl5Pattern should be treated as a read only data structure by Perl5Matcher, making it safe to share a single Perl5Pattern instance among multiple threads without needing synchronization</td></tr>
1441   * <tr><td>SINGLELINE_MASK</td><td>Compiled regular expression should treat input as being a single line</td></tr>
1442   * @throws MalformedPatternException
1443   * @see http://www.savarese.org/oro/docs/OROMatcher/Syntax.html
1444   */

1445  public static String JavaDoc replace(String JavaDoc sSource, String JavaDoc sRegExp, String JavaDoc sNewVal, int iOptions) throws MalformedPatternException {
1446    Pattern oPattern;
1447    if (null==oMatcher) oMatcher = new Perl5Matcher();
1448    if (null==oCompiler) oCompiler = new Perl5Compiler();
1449
1450    oPattern = oCompiler.compile(sRegExp, iOptions);
1451
1452    return Util.substitute(oMatcher, oPattern,
1453                           new Perl5Substitution(sNewVal, Perl5Substitution.INTERPOLATE_ALL),
1454                           sSource, Util.SUBSTITUTE_ALL);
1455  } // replace
1456

1457  // ----------------------------------------------------------
1458

1459  /**
1460   * Count occurrences of a given substring
1461   * @param sSource String Source
1462   * @param sSubStr Substring to be searched (no wildcards)
1463   * @param iOptions int org.apache.oro.text.regex.Perl5Compiler.CASE_INSENSITIVE_MASK for case insensitive search
1464   * @return int Number of occurrences of sSubStr at sSource.
1465   * If sSource is null or sSubStr is null then the number of occurrences is zero.
1466   * If sSource is empty or sSubStr is empty then the number of occurrences is zero.
1467   */

1468  public static int countOccurrences(String JavaDoc sSource, String JavaDoc sSubStr, int iOptions) throws MalformedPatternException {
1469    if (null==sSource || null==sSubStr) return 0;
1470    if (sSource.length()==0 || sSubStr.length()==0) return 0;
1471
1472    int lSource = sSource.length();
1473    int lSubStr = sSubStr.length();
1474    int iOccurrences = 0;
1475    int iCurPos;
1476    if ((org.apache.oro.text.regex.Perl5Compiler.CASE_INSENSITIVE_MASK&iOptions)==0) {
1477      iCurPos = sSource.indexOf(sSubStr);
1478      while (iCurPos!=-1 && iCurPos+lSubStr<=lSource) {
1479        iOccurrences++;
1480        iCurPos = sSource.indexOf(sSubStr, iCurPos+1);
1481      }
1482    } else {
1483      iCurPos = Gadgets.indexOfIgnoreCase(sSource, sSubStr);
1484      while (iCurPos!=-1 && iCurPos+lSubStr<=lSource) {
1485        iOccurrences++;
1486        iCurPos = Gadgets.indexOfIgnoreCase(sSource, sSubStr, iCurPos+1);
1487      }
1488    }
1489    return iOccurrences;
1490  } // countOccurrences
1491

1492  // ----------------------------------------------------------
1493

1494  /**
1495   * Return left portion of a string.
1496   * This function is similar to substring(sSource, nChars) but it does not raise
1497   * any exception if sSource.length()>nChars but just return the full sSource
1498   * input String.
1499   * @param sSource Source String
1500   * @param nChars Number of characters to the left of String to get.
1501   * @return Left characters of sSource String or <b>null</b> if sSource is <b>null</b>.
1502   */

1503  public static String JavaDoc left(String JavaDoc sSource, int nChars) {
1504    int iLen;
1505
1506    if (null==sSource) return null;
1507
1508    iLen = sSource.length();
1509
1510    if (iLen>nChars)
1511      return sSource.substring(0, nChars);
1512    else
1513      return sSource;
1514  } // left
1515

1516  // ----------------------------------------------------------
1517

1518  /**
1519   * Add padding characters to the left.
1520   * @param sSource Input String
1521   * @param cPad Padding character
1522   * @param nChars Final length of the padded string
1523   * @return Padded String
1524   */

1525  public static String JavaDoc leftPad(String JavaDoc sSource, char cPad, int nChars) {
1526      if (null==sSource) return null;
1527
1528      int iPadLen = nChars - sSource.length();
1529
1530      if (iPadLen<=0) return sSource;
1531
1532      char aPad[] = new char[iPadLen];
1533
1534      for (int c=0; c<iPadLen; c++) aPad[c] = cPad;
1535
1536      return new String JavaDoc(aPad) + sSource;
1537  } // leftPad
1538

1539  // ----------------------------------------------------------
1540

1541  /**
1542   * Ensure that a String ends with a given character
1543   * @param sSource Input String
1544   * @param cEndsWith Character that the String must end with.
1545   * @return If sSource ends with cEndsWith then sSource is returned,
1546   * else sSource+cEndsWith is returned.
1547   */

1548  public static String JavaDoc chomp(String JavaDoc sSource, char cEndsWith) {
1549
1550    if (null==sSource)
1551      return null;
1552    else if (sSource.length()==0)
1553      return "";
1554    else if (sSource.charAt(sSource.length()-1)==cEndsWith)
1555      return sSource;
1556    else
1557      return sSource + String.valueOf(cEndsWith);
1558  } // chomp
1559

1560  // ----------------------------------------------------------
1561

1562  /**
1563   * Ensure that a String ends with a given substring
1564   * @param sSource Input String
1565   * @param sEndsWith Substring that the String must end with.
1566   * @return If sSource ends with sEndsWith then sSource is returned,
1567   * else sSource+sEndsWith is returned.
1568   */

1569  public static String JavaDoc chomp(String JavaDoc sSource, String JavaDoc sEndsWith) {
1570
1571    if (null==sSource)
1572      return null;
1573    else if (sSource.length()==0)
1574      return "";
1575    else if (sSource.endsWith(sEndsWith))
1576      return sSource;
1577    else
1578      return sSource + sEndsWith;
1579  } // chomp
1580

1581  // ----------------------------------------------------------
1582

1583  /**
1584   * Ensure that a String does not end with a given substring
1585   * @param sSource Input String
1586   * @param sEndsWith Substring that the String must not end with.
1587   * @return If sSource does not end with sEndsWith then sSource is returned,
1588   * else sSource-sEndsWith is returned.
1589   */

1590  public static String JavaDoc dechomp(String JavaDoc sSource, String JavaDoc sEndsWith) {
1591
1592    if (null==sSource)
1593      return null;
1594    else if (sEndsWith==null)
1595      return sSource;
1596    else if (sSource.length()<sEndsWith.length())
1597      return sSource;
1598    else if (sSource.endsWith(sEndsWith))
1599      return sSource.substring(0, sSource.length()-sEndsWith.length());
1600    else
1601      return sSource;
1602  } // dechomp
1603

1604  // ----------------------------------------------------------
1605

1606  /**
1607   * Ensure that a String does not end with a given character
1608   * @param sSource Input String
1609   * @param cEndsWith Character that the String must not end with.
1610   * @return If sSource does not end with sEndsWith then sSource is returned,
1611   * else sSource-cEndsWith is returned.
1612   */

1613  public static String JavaDoc dechomp(String JavaDoc sSource, char cEndsWith) {
1614
1615    if (null==sSource)
1616      return null;
1617    else if (sSource.length()<1)
1618      return sSource;
1619    else if (sSource.charAt(sSource.length()-1)==cEndsWith)
1620      return sSource.substring(0, sSource.length()-1);
1621    else
1622      return sSource;
1623  } // dechomp
1624

1625  // ----------------------------------------------------------
1626

1627  /**
1628   * <p>Take an input string and tokenize each command on it<p>
1629   * @param sSource String to be parsed.<br>
1630   * Tokens are separated by spaces. Single or double quotes are allowed for qualifying string literals.
1631   * @return String[] Array of tokens. If sSource is <b>null</b> then the return value is <b>null</b>,
1632   * if sSource is empty then the return value is an array with a single element being it <b>null</b>.
1633   * @throws StringIndexOutOfBoundsException
1634   */

1635  public static String JavaDoc[] tokenizeCmdLine(String JavaDoc sSource)
1636    throws StringIndexOutOfBoundsException JavaDoc {
1637    String JavaDoc[] aTokens;
1638
1639    if (DebugFile.trace) {
1640      DebugFile.writeln("Begin Gadgets.tokenizeCmdLine("+sSource+")");
1641       DebugFile.incIdent();
1642    }
1643
1644    if (null==sSource) {
1645      aTokens=null;
1646    } else if (sSource.length()==0) {
1647      aTokens=new String JavaDoc[]{null};
1648    } else {
1649      final int iLen = sSource.length();
1650      ArrayList JavaDoc oTokens = new ArrayList JavaDoc();
1651      char cTextQualifier = (char) 0;
1652      char cCurrentChar;
1653      StringBuffer JavaDoc oCurrentToken = new StringBuffer JavaDoc(256);
1654      for (int p=0; p<iLen; p++) {
1655        cCurrentChar = sSource.charAt(p);
1656        switch (cCurrentChar) {
1657          case ' ':
1658            if (0!=cTextQualifier) {
1659              oCurrentToken.append(cCurrentChar);
1660            } else if (oCurrentToken.length()>0) {
1661              oTokens.add(oCurrentToken.toString());
1662              oCurrentToken.setLength(0);
1663            }
1664            break;
1665          case '\\':
1666            if (p==iLen-1) throw new StringIndexOutOfBoundsException JavaDoc("Input string terminated with a single backslash character");
1667            switch (sSource.charAt(++p)) {
1668              case 'n':
1669                oCurrentToken.append('\n');
1670                break;
1671              case 't':
1672                oCurrentToken.append('\t');
1673                break;
1674              case '\\':
1675                oCurrentToken.append('\\');
1676                break;
1677              case '"':
1678                oCurrentToken.append('"');
1679                break;
1680              default:
1681                throw new StringIndexOutOfBoundsException JavaDoc("Unrecognized escape sequence \\"+sSource.charAt(p));
1682            } // end switch (charAt(++p))
1683
break;
1684          case '"':
1685            if (0==cTextQualifier) {
1686              cTextQualifier='"';
1687            } else if ('"'==cTextQualifier) {
1688              cTextQualifier=(char)0;
1689            }
1690            break;
1691          case '\'':
1692            if (0==cTextQualifier) {
1693              cTextQualifier='\'';
1694            } else if ('\''==cTextQualifier) {
1695              cTextQualifier=(char)0;
1696            }
1697            break;
1698          case ',':
1699          case ';':
1700          case '(':
1701          case ')':
1702          case '[':
1703          case ']':
1704          case '{':
1705          case '}':
1706          case '-':
1707          case '+':
1708          case '/':
1709          case '*':
1710          case '=':
1711          case '&':
1712          case '!':
1713          case '?':
1714            if (0!=cTextQualifier) {
1715              oCurrentToken.append(cCurrentChar);
1716            }
1717            else {
1718              if (oCurrentToken.length()>0) {
1719                oTokens.add(oCurrentToken.toString());
1720                oCurrentToken.setLength(0);
1721              }
1722              oTokens.add(new String JavaDoc(new char[]{cCurrentChar}));
1723            }
1724            break;
1725          default:
1726            oCurrentToken.append(cCurrentChar);
1727        }
1728      } // next
1729
if (oCurrentToken.length()>0) {
1730        oTokens.add(oCurrentToken.toString());
1731      }
1732      aTokens=new String JavaDoc[oTokens.size()];
1733      System.arraycopy(oTokens.toArray(),0,aTokens,0,aTokens.length);
1734    }
1735
1736    if (DebugFile.trace) {
1737      StringBuffer JavaDoc oOutput = new StringBuffer JavaDoc();
1738      if (aTokens!=null)
1739        for (int t=0; t<aTokens.length; t++)
1740          oOutput.append(aTokens[t]+(t<aTokens.length-1 ? "¶" :""));
1741      DebugFile.decIdent();
1742      DebugFile.writeln("End Gadgets.tokenizeCmdLine() : " + oOutput.toString());
1743    }
1744
1745    return aTokens;
1746  } // tokenizeCmdLine
1747

1748  // ----------------------------------------------------------
1749

1750  /**
1751   * Check that an e-mail address is syntactically valid.
1752   * @param sEMailAddr e-mail address to check
1753   * @return <b>true</b> if e-mail address is syntactically valid.
1754   */

1755  public static boolean checkEMail(String JavaDoc sEMailAddr) {
1756    final String JavaDoc nu = "1234567890";
1757    final String JavaDoc ok = "1234567890qwertyuiop[]asdfghjklzxcvbnm.@-_QWERTYUIOPASDFGHJKLZXCVBNM";
1758    int iAt, iDot;
1759
1760    if (sEMailAddr==null) return false;
1761
1762    if (sEMailAddr.trim().length()==0) return false;
1763
1764    iAt = sEMailAddr.indexOf("@");
1765    iDot = sEMailAddr.lastIndexOf(".");
1766
1767    // Domain extension must exist
1768
if (iDot<=0) return false;
1769
1770    if (iAt<=0 || iAt==sEMailAddr.length()-1) return false;
1771
1772    // Domain name must exist
1773
if (ok.indexOf(sEMailAddr.substring(iAt-1, iAt))<0 ||
1774        ok.indexOf(sEMailAddr.substring(iAt+1, iAt+2))<0) return false;
1775
1776    // Domain name cannot start with a number
1777
if (nu.indexOf(sEMailAddr.substring(iAt+1, iAt+2))>=0) return false;
1778
1779    // Domain extension is at most 4 characters
1780
if (iDot<sEMailAddr.length()-5) return false;
1781
1782    // Domain extension is at least 2 characters
1783
if (iDot>sEMailAddr.length()-3) return false;
1784
1785  return true;
1786  } // checkEMail
1787

1788  // ----------------------------------------------------------
1789

1790  public static final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
1791
1792  public static void toHexChars( int val, char dst[], int dstIndex, int size ) {
1793      while( size > 0 ) {
1794          dst[dstIndex + size - 1] = HEX_DIGITS[val & 0x000F];
1795          if( val != 0 ) {
1796              val >>>= 4;
1797          }
1798          size--;
1799      }
1800  }
1801
1802  // ----------------------------------------------------------
1803

1804  public static String JavaDoc toHexString( int val, int size ) {
1805      char[] c = new char[size];
1806      toHexChars( val, c, 0, size );
1807      return new String JavaDoc( c );
1808  }
1809
1810  // ----------------------------------------------------------
1811

1812  /**
1813   * Convert a byte array into its corresponding Hexadecimal String representation
1814   * @param src Input array
1815   * @param srcIndex Begin Index
1816   * @param size Number of bytes to be readed
1817   * @return A String with two hexadecimal upper case digits per byte on the input array
1818   */

1819  public static String JavaDoc toHexString( byte[] src, int srcIndex, int size ) {
1820      if (null==src) return null;
1821
1822      char[] c = new char[size];
1823      size = ( size % 2 == 0 ) ? size / 2 : size / 2 + 1;
1824      for( int i = 0, j = 0; i < size; i++ ) {
1825          c[j++] = HEX_DIGITS[(src[i] >> 4 ) & 0x0F];
1826          if( j == c.length ) {
1827              break;
1828          }
1829          c[j++] = HEX_DIGITS[src[i] & 0x0F];
1830      }
1831      return new String JavaDoc( c );
1832  }
1833
1834  // ----------------------------------------------------------
1835

1836  /**
1837   * Convert a byte array into its corresponding Hexadecimal String representation
1838   * @param src Input array
1839   * @return A String with two hexadecimal upper case digits per byte on the input array
1840   */

1841  public static String JavaDoc toHexString( byte[] src) {
1842    if (null==src) return null;
1843
1844    return toHexString(src, 0, src.length);
1845  }
1846
1847  // ----------------------------------------------------------
1848

1849  /**
1850   * Remove a character from a String
1851   * @param sInput Input String
1852   * @param cRemove Character to be removed
1853   * @return The input String without all the occurences of the given character
1854   */

1855  public static String JavaDoc removeChar(String JavaDoc sInput, char cRemove) {
1856    if (null==sInput) return null;
1857    if (sInput.length()==0) return sInput;
1858
1859    final int iLen = sInput.length();
1860    StringBuffer JavaDoc oOutput = new StringBuffer JavaDoc(iLen);
1861
1862    for (int i=0; i<iLen; i++) {
1863      char c = sInput.charAt(i);
1864      if (cRemove!=c)
1865        oOutput.append(c);
1866    } // next
1867

1868    return oOutput.toString();
1869  } // removeChar
1870

1871  // ----------------------------------------------------------
1872

1873  /**
1874   * Remove a character set from a String
1875   * @param sInput Input String
1876   * @param sRemove A String containing all the characters to be removed from input String
1877   * @return The input String without all the characters of sRemove
1878   */

1879  public static String JavaDoc removeChars(String JavaDoc sInput, String JavaDoc sRemove) {
1880    if (null==sInput) return null;
1881    if (null==sRemove) return sInput;
1882    if (sInput.length()==0) return sInput;
1883    if (sRemove.length()==0) return sInput;
1884
1885    final int iLen = sInput.length();
1886    StringBuffer JavaDoc oOutput = new StringBuffer JavaDoc(iLen);
1887
1888    for (int i=0; i<iLen; i++) {
1889      char c = sInput.charAt(i);
1890      if (sRemove.indexOf(c)<0)
1891        oOutput.append(c);
1892    } // next
1893

1894    return oOutput.toString();
1895  } // removeChars
1896

1897  // ----------------------------------------------------------
1898

1899  /**
1900   * Rounds a BigDecimal value to two decimals
1901   * @param oDec BigDecimal to be rounded
1902   * @return BigDecimal If oDec is <b>null</b> then round2 returns <b>null</b>
1903   */

1904  public static BigDecimal JavaDoc round2 (BigDecimal JavaDoc oDec) {
1905    if (null==oDec) return null;
1906    StringBuffer JavaDoc oBuffer = new StringBuffer JavaDoc();
1907    if (null==oFmt2) {
1908      oFmt2 = new DecimalFormat JavaDoc("#0.00");
1909      oFrac = new FieldPosition JavaDoc(java.text.NumberFormat.FRACTION_FIELD);
1910    }
1911    oFmt2.format(oDec.doubleValue(), oBuffer, oFrac);
1912    return new BigDecimal JavaDoc (oBuffer.toString());
1913  }
1914
1915  // ----------------------------------------------------------
1916

1917  /**
1918   * Format a BigDecimal as a String following the rules for an specific locale
1919   * @param oDec BigDecimal to be formatted
1920   * @param sCurrency String ISO 4217 currency code (EUR, USD, GBP, BRL, CNY, etc.)
1921   * @param sLanguage String lowercase two-letter ISO-639 code
1922   * @param sLocale2 String uppercase two-letter ISO-3166 code
1923   * @return String
1924   * @see <a HREF="http://www.bsi-global.com/British_Standards/currency/index.xalter">BSI Currency Code Service (ISO 4217 Maintenance Agency)</a>
1925   * @see <a HREF="http://www.xe.com/iso4217.htm">ISO 4217 currency code list</a>
1926   * @see <a HREF="http://www.ics.uci.edu/pub/ietf/http/related/iso639.txt">ISO 639 language codes</a>
1927   * @see <a HREF="http://www.iso.org/iso/en/prods-services/iso3166ma/02iso-3166-code-lists/list-en1.html">ISO 3166 country codes</a>
1928   */

1929  public static String JavaDoc formatCurrency (BigDecimal JavaDoc oDec, String JavaDoc sCurrency,
1930                                       String JavaDoc sLanguage, String JavaDoc sCountry) {
1931    if (null==oDec) return null;
1932
1933    Locale JavaDoc oLoc;
1934    if (null!=sLanguage && null!=sCountry)
1935      oLoc = new Locale JavaDoc(sLanguage,sCountry);
1936    else if (null!=sLanguage)
1937      oLoc = new Locale JavaDoc(sLanguage);
1938    else
1939      oLoc = Locale.getDefault();
1940    if (null==sCurrency) {
1941      oCurr = Currency.getInstance(oLoc);
1942    }
1943    else if (!sCurrency.equals(sCurr)) {
1944      oCurr = Currency.getInstance(sCurrency);
1945    }
1946    NumberFormat JavaDoc oFmtC = NumberFormat.getCurrencyInstance(oLoc);
1947    oFmtC.setCurrency(oCurr);
1948    return oFmtC.format(oDec.doubleValue());
1949  }
1950
1951  // ----------------------------------------------------------
1952

1953  /**
1954   * Format a BigDecimal as a String following the rules for an specific locale
1955   * @param oDec BigDecimal to be formatted
1956   * @param sCurrency String ISO 4217 currency code (EUR, USD, GBP, BRL, CNY, etc.)
1957   * @param sLanguage String lowercase two-letter ISO-639 code
1958   * @return String
1959   * @see <a HREF="http://www.xe.com/iso4217.htm">ISO 4217 currency code list</a>
1960   * @see <a HREF="http://www.ics.uci.edu/pub/ietf/http/related/iso639.txt">ISO 639 language codes</a>
1961   */

1962  public static String JavaDoc formatCurrency (BigDecimal JavaDoc oDec, String JavaDoc sCurrency,
1963                                       String JavaDoc sLanguage) {
1964    if (null==oDec) return null;
1965
1966    Locale JavaDoc oLoc = (sLanguage==null ? Locale.getDefault() : new Locale JavaDoc(sLanguage));
1967    if (null==sCurrency) {
1968      oCurr = Currency.getInstance(oLoc);
1969    }
1970    else if (!sCurrency.equals(sCurr)) {
1971      oCurr = Currency.getInstance(sCurrency);
1972    }
1973    NumberFormat JavaDoc oFmtC = NumberFormat.getCurrencyInstance(oLoc);
1974    oFmtC.setCurrency(oCurr);
1975    return oFmtC.format(oDec.doubleValue());
1976  }
1977
1978  // ----------------------------------------------------------
1979
/**
1980   * Format a BigDecimal as a String following the rules for an specific locale
1981   * @param oDec BigDecimal to be formatted
1982   * @param sCurrency String ISO 4217 currency code (EUR, USD, GBP, BRL, CNY, etc.)
1983   * @param oLocale Locale used for formatting
1984   * @return String
1985   * @see <a HREF="http://java.sun.com/j2se/1.4.2/docs/api/java/util/Locale.html">java.util.Locale</a>
1986   */

1987  public static String JavaDoc formatCurrency (BigDecimal JavaDoc oDec, String JavaDoc sCurrency, Locale JavaDoc oLocale) {
1988    NumberFormat JavaDoc oFmtC;
1989    if (null==oDec) return null;
1990
1991    if (null==sCurrency) {
1992      oCurr = Currency.getInstance(oLocale==null ? Locale.getDefault() : oLocale);
1993    }
1994    else if (!sCurrency.equals(sCurr)) {
1995      oCurr = Currency.getInstance(sCurrency);
1996    }
1997    if (null==oLocale)
1998      oFmtC = NumberFormat.getCurrencyInstance(Locale.getDefault());
1999    else
2000      oFmtC = NumberFormat.getCurrencyInstance(oLocale);
2001    oFmtC.setCurrency(oCurr);
2002    return oFmtC.format(oDec.doubleValue());
2003  }
2004
2005  // ----------------------------------------------------------
2006

2007  public static void main(String JavaDoc[] argv) {
2008    if (argv.length>0) {
2009      if (argv[0].equalsIgnoreCase("uuidgen")) {
2010        System.out.println(Gadgets.generateUUID());
2011      } // fi (argv[0]=="uuidgen")
2012
}
2013  }
2014
2015} // Gadgets
2016
Popular Tags