more bug fixes in dublin core date functions....
[mir.git] / source / mir / misc / StringUtil.java
1 /*
2  * put your module comment here
3  */
4
5
6 package  mir.misc;
7
8 import  java.io.*;
9 import  java.lang.*;
10 import  java.util.*;
11 import  gnu.regexp.*;
12
13 /**
14  * Statische Hilfsmethoden zur Stringbehandlung
15  *
16  * @version 29.6.99
17  * @author RK
18  */
19 public final class StringUtil {
20
21         private static RE   re_newline2br, re_brbr2p, re_mail, re_url, re_tags;
22
23         private StringUtil() { }  // this avoids contruction
24
25         static {
26                 try {
27                         //precompile regex
28                         re_newline2br = new RE("(\r?\n){1}");
29                         re_brbr2p     = new RE("(<br>\r?\n<br>){1,}");
30                         re_mail       = new RE("([a-zA-Z0-9_.-]+)@([a-zA-Z0-9_-]+).([a-zA-Z0-9_.-]+)");
31                         re_url        = new RE("((https://)|(http://)|(ftp://)){1}([a-zA-Z0-9_-]+).([a-zA-Z0-9_.:-]+)/?([^ \t\r\n<>\\)\\]]+[^ \t\r\n.,<>\\)\\]])");
32                         re_tags       = new RE("<[^>]*>",RE.REG_ICASE);
33                 }
34                 catch (REException e){
35                         System.err.println("FATAL: StringUtil: could not precompile REGEX: "+e.toString());
36                 }
37         }
38
39
40         /**
41          * Wandelt Datum in einen 8-ziffrigen String um (yyyymmdd)
42          * @param theDate
43          * @return 8-ziffriger String (yyyymmdd)
44          */
45
46         public static final String date2webdbDate (GregorianCalendar theDate) {
47                 StringBuffer webdbDate = new StringBuffer();
48                 webdbDate.append(String.valueOf(theDate.get(Calendar.YEAR)));
49                 webdbDate.append(pad2(theDate.get(Calendar.MONTH) + 1));
50                 webdbDate.append(pad2(theDate.get(Calendar.DATE)));
51                 return  webdbDate.toString();
52         }
53
54         /**
55          * Wandelt Calendar in einen 12-ziffrigen String um (yyyymmddhhmm)
56          * @param theDate
57          * @return 12-ziffriger String (yyyymmdd)
58          */
59
60         public static final String date2webdbDateTime (GregorianCalendar theDate) {
61                 StringBuffer webdbDate = new StringBuffer();
62                 webdbDate.append(String.valueOf(theDate.get(Calendar.YEAR)));
63                 webdbDate.append(pad2(theDate.get(Calendar.MONTH) + 1));
64                 webdbDate.append(pad2(theDate.get(Calendar.DATE)));
65                 webdbDate.append(pad2(theDate.get(Calendar.HOUR)));
66                 webdbDate.append(pad2(theDate.get(Calendar.MINUTE)));
67                 return  webdbDate.toString();
68         }
69
70         /**
71          * Return a http://www.w3.org/TR/NOTE-datetime formatted date (yyyy-mm-ddThh:mm:ssTZ)
72          * @param theDate
73          * @return w3approved datetime
74          */
75
76         public static final String date2w3DateTime (GregorianCalendar theDate) {
77                 StringBuffer webdbDate = new StringBuffer();
78                 webdbDate.append(String.valueOf(theDate.get(Calendar.YEAR)));
79                 webdbDate.append("-");
80                 webdbDate.append(pad2(theDate.get(Calendar.MONTH) + 1));
81                 webdbDate.append("-");
82                 webdbDate.append(pad2(theDate.get(Calendar.DATE)));
83                 webdbDate.append("T");
84                 webdbDate.append(pad2(theDate.get(Calendar.HOUR)));
85                 webdbDate.append(":");
86                 webdbDate.append(pad2(theDate.get(Calendar.MINUTE)));
87                 webdbDate.append(":");
88                 webdbDate.append(pad2(theDate.get(Calendar.SECOND)));
89                 //assumes you are an hour-multiple away from UTC.... 
90                 int offset=(theDate.get(Calendar.ZONE_OFFSET)/(60*60*1000));
91                 if (offset < 0){
92                 webdbDate.append("-");
93                 }
94                 else{
95                 webdbDate.append("+");
96                 }
97                 webdbDate.append(pad2(Math.abs(offset)));
98                 webdbDate.append(":00");
99                 return  webdbDate.toString();
100         }
101
102         /**
103          * wandelt Calendar in dd.mm.yyyy / hh.mm um
104          * @param theDate
105          * @return String mit (dd.mm.yyyy / hh.mm um)
106          */
107         public static String date2readableDateTime (GregorianCalendar theDate) {
108                 String readable = "";
109                 int hour;
110                 readable += pad2(theDate.get(Calendar.DATE));
111                 readable += "." + pad2(theDate.get(Calendar.MONTH) + 1);
112                 readable += "." + String.valueOf(theDate.get(Calendar.YEAR));
113                 hour = theDate.get(Calendar.HOUR);
114                 if (theDate.get(Calendar.AM_PM) == Calendar.PM)
115                         hour += 12;
116                 readable += " / " + pad2(hour);
117                 readable += ":" + pad2(theDate.get(Calendar.MINUTE));
118                 return  readable;
119         }
120
121         /**
122          * wandelt eine Datum in einen 8-buchstabigen String, der durch <code>/</code>
123          * getrennt ist.
124          *
125          * @param webdbDate
126          * @return String mit <code>/yyyy/mm/dd</code>
127          */
128         public static final String webdbDate2path (String webdbDate) {
129                 StringBuffer path = new StringBuffer();
130                 path.append("/").append(webdbDate.substring(0, 4));
131                 path.append("/").append(webdbDate.substring(4, 6));
132                 path.append("/");
133                 //who did this?
134                 //path.append("/").append(webdbDate.substring(6, 8));
135                 return  path.toString();
136         }
137
138         /**
139          * wandelt Calendar in dd.mm.yyyy um
140          *
141          * @param theDate
142          * @return String mit  <code>dd.mm.yyyy</code>
143          */
144         public static final String webdbDate2readableDate (String webdbDate) {
145                 String date = "";
146                 date += webdbDate.substring(6, 8);
147                 date += "." + webdbDate.substring(4, 6);
148                 date += "." + webdbDate.substring(0, 4);
149                 return  date;
150         }
151
152
153         /**
154          * converts string from format: yyyy-mm-dd__hh:mm:ss.d
155          * to dd.mm.yyyy hh:mm
156          */
157         public static String dateToReadableDate(String date) {
158                 StringBuffer returnDate = new StringBuffer();
159                 if (date!=null) {
160
161                         returnDate.append(date.substring(8,10)).append('.');
162                         returnDate.append(date.substring(5,7)).append('.');
163                         returnDate.append(date.substring(0,4)).append(' ');
164                         returnDate.append(date.substring(11,16));
165                 }
166                 return returnDate.toString();
167         }
168         
169         /**
170          * converts string from format: yyyy-mm-dd__hh:mm:ss.dddddd+TZ
171          * to yyyy-mm-ddThhmmss+TZ:00 (w3 format for Dublin Core)
172          */
173         public static String webdbdateToDCDate(String date) {
174                 StringBuffer returnDate = new StringBuffer();
175                 if (date!=null) {
176
177                         returnDate.append(date.substring(0,4));
178                         returnDate.append("-");
179                         returnDate.append(date.substring(5,7));
180                         returnDate.append("-");
181                         returnDate.append(date.substring(8,10));
182                         returnDate.append("T");
183                         returnDate.append(date.substring(11,13));
184                         returnDate.append(":");
185                         returnDate.append(date.substring(14,16));
186                         returnDate.append(":");
187                         returnDate.append(date.substring(17,22));
188                         returnDate.append(date.substring(20,22));
189                         returnDate.append(":00");
190                 }
191                 return returnDate.toString();
192         }
193
194
195         /**
196          * converts string from format: yyyy-mm-dd__hh:mm:ss.d
197          * to yyyy
198          */
199         public static String dateToYear (String date) {
200                 StringBuffer returnDate = new StringBuffer();
201                 if (date!=null) {
202
203                         returnDate.append(date.substring(0,4));
204                 }
205                 return returnDate.toString();
206         }
207
208         /**
209          * converts string from format: yyyy-mm-dd__hh:mm:ss.d
210          * to [m]m
211          */
212         public static String dateToMonth (String date) {
213                 StringBuffer returnDate = new StringBuffer();
214                 if (date!=null) {
215                         if (!date.substring(5,6).equalsIgnoreCase("0")) returnDate.append(date.substring(5,7));
216                         else returnDate.append(date.substring(6,7));
217                 }
218                 return returnDate.toString();
219         }
220
221         /**
222          * converts string from format: yyyy-mm-dd__hh:mm:ss.d
223          * to [d]d
224          */
225         public static String dateToDayOfMonth (String date) {
226                 StringBuffer returnDate = new StringBuffer();
227                 if (date!=null) {
228                         if (!date.substring(8,9).equalsIgnoreCase("0")) returnDate.append(date.substring(8,10));
229                         else returnDate.append(date.substring(9,10));
230                 }
231                 return returnDate.toString();
232         }
233
234         /**
235          * converts string from format: yyyy-mm-dd__hh:mm:ss.d
236          * to hh:mm
237          */
238         public static String dateToTime (String date) {
239                 StringBuffer returnDate = new StringBuffer();
240                 if (date!=null) {
241                         returnDate.append(date.substring(11,16));
242                 }
243                 return returnDate.toString();
244         }
245
246     /**
247      * Splits the provided CSV text into a list. stolen wholesale from 
248      * from Jakarta Turbine StrinUtils.java -mh
249      *
250      * @param text      The CSV list of values to split apart.
251      * @param separator The separator character.
252      * @return          The list of values.
253      */
254     public static String[] split(String text, String separator)
255     {
256         StringTokenizer st = new StringTokenizer(text, separator);
257         String[] values = new String[st.countTokens()];
258         int pos = 0;
259         while (st.hasMoreTokens())
260         {
261             values[pos++] = st.nextToken();
262         }
263         return values;
264     }
265
266     /**
267      * Joins the elements of the provided array into a single string
268      * containing a list of CSV elements. Stolen wholesale from Jakarta
269      * Turbine StringUtils.java. -mh
270      *
271      * @param list      The list of values to join together.
272      * @param separator The separator character.
273      * @return          The CSV text.
274      */
275     public static String join(String[] list, String separator)
276     {
277         StringBuffer csv = new StringBuffer();
278         for (int i = 0; i < list.length; i++)
279         {
280             if (i > 0)
281             {
282                 csv.append(separator);
283             }
284             csv.append(list[i]);
285         }
286         return csv.toString();
287     }
288
289
290         /**
291          * schließt einen String in Anführungsszeichen ein, falls er Leerzeichen o.ä. enthält
292          *
293          * @return gequoteter String
294          */
295          public static String quoteIfNecessary(String s) {
296                 for (int i = 0; i < s.length(); i++)
297                         if (!(Character.isLetterOrDigit(s.charAt(i)) || s.charAt(i) == '.'))
298                                 return quote(s, '"');
299                 return s;
300         }
301
302          /**
303          * schließt <code>s</code> in <code>'</code> ein und setzt Backslashes vor
304          * "gefährliche" Zeichen innerhalb des Strings
305          * Quotes special SQL-characters in <code>s</code>
306          *
307          * @return geqoteter String
308          */
309         public static String quote(String s)
310         {
311                 String s2 = quote(s, '\'');
312                 s2 = quote(s2, '\"');
313                 return s2;
314         }
315
316         /**
317          * schließt <code>s</code> in <code>'</code> ein und setzt Backslashes vor
318          * "gefährliche" Zeichen innerhalb des Strings
319          *
320          * @param s String, der gequoted werden soll
321          * @param quoteChar zu quotendes Zeichen
322          * @return gequoteter String
323          */
324         public static String quote(String s, char quoteChar)
325         {
326                 StringBuffer buf = new StringBuffer(s.length());
327                 int pos = 0;
328                 while (pos < s.length()) {
329                         int i = s.indexOf(quoteChar, pos);
330                         if (i < 0) i = s.length();
331                         buf.append(s.substring(pos, i));
332                         pos = i;
333                         if (pos < s.length()) {
334                                 buf.append('\\');
335                                 buf.append(quoteChar);
336                                 pos++;
337                         }
338                 }
339                 return buf.toString();
340         }
341
342         /**
343          * replaces dangerous characters in <code>s</code>
344          *
345          */
346
347         public static String unquote(String s)
348         {
349                 char quoteChar='\'';
350                 StringBuffer buf = new StringBuffer(s.length());
351                 int pos = 0;
352                 String searchString = "\\"+quoteChar;
353                 while (pos < s.length()) {
354                         int i = s.indexOf(searchString, pos);
355                         if (i < 0) i = s.length();
356                         buf.append(s.substring(pos, i));
357                         pos = i+1;
358                 }
359                 return buf.toString();
360         }
361
362         /**
363          * Wandelet String in byte[] um.
364          * @param s
365          * @return byte[] des String
366          */
367
368         public static byte[] stringToBytes(String s) {
369                 String crlf = System.getProperty("line.separator");
370                 if (!crlf.equals("\n"))
371                         s = replace(s, "\n", crlf);
372                 // byte[] buf = new byte[s.length()];
373                 byte[] buf = s.getBytes();
374                 return buf;
375         }
376
377                 /**
378          * Ersetzt in String <code>s</code> das <code>pattern</code> durch <code>substitute</code>
379          * @param s
380          * @param pattern
381          * @param substitute
382          * @return String mit den Ersetzungen
383          */
384         public static String replace(String s, String pattern, String substitute) {
385                 int i = 0, pLen = pattern.length(), sLen = substitute.length();
386                 StringBuffer buf = new StringBuffer(s.length());
387                 while (true) {
388                         int j = s.indexOf(pattern, i);
389                         if (j < 0) {
390                                 buf.append(s.substring(i));
391                                 break;
392                         } else {
393                                 buf.append(s.substring(i, j));
394                                 buf.append(substitute);
395                                 i = j+pLen;
396                         }
397                 }
398                 return buf.toString();
399         }
400
401         /**
402          * Ersetzt in String <code>s</code> das Regexp <code>pattern</code> durch <code>substitute</code>
403          * @param s
404          * @param pattern
405          * @param substitute
406          * @return String mit den Ersetzungen
407          */
408         public static String regexpReplace(String haystack, String pattern, String substitute) {
409                 try {
410                         RE regex = new RE(pattern);
411                         return regex.substituteAll(haystack,substitute);
412                 } catch(REException ex){
413                         return null;
414                 }
415         }
416
417
418
419
420         /**
421          * Fügt einen Separator an den Pfad an
422          * @param path
423          * @return Pfad mit Separator am Ende
424          */
425         public static final String addSeparator (String path) {
426                 return  path.length() == 0 || path.endsWith(File.separator) ? path : path
427                                 + File.separatorChar;
428         }
429
430         /**
431          * Fügt ein <code>/</code> ans ende des Strings and
432          * @param path
433          * @return Pfad mit <code>/</code> am Ende
434          */
435         public static final String addSlash (String path) {
436                 return  path.length() == 0 || path.endsWith("/") ? path : path + '/';
437         }
438
439         /**
440          * Löscht <code>/</code> am Ende des Strings, falls vorhanden
441          * @param path
442          * @return String ohne <code>/</code> am Ende
443          */
444         public static final String removeSlash (String path) {
445                 return  path.length() > 1 && path.endsWith("/") ? path.substring(0, path.length()
446                                 - 1) : path;
447         }
448
449         /**
450          * Checks to see if the path is absolute by looking for a leading file
451          * separater
452          * @param path
453          * @return
454          */
455         public static boolean isAbsolutePath (String path) {
456                 return  path.startsWith(File.separator);
457         }
458
459         /**
460          * Löscht Slash am Anfang des Strings
461          * @param path
462          * @return
463          */
464         public static String removeFirstSlash (String path) {
465                 return  path.startsWith("/") ? path.substring(1) : path;
466         }
467
468         /**
469          * formatiert eine Zahl (0-99) zweistellig (z.B. 5 -> 05)
470          * @return zwistellige Zahl
471          */
472         public static String pad2 (int number) {
473                 return  number < 10 ? "0" + number : String.valueOf(number);
474         }
475
476         /**
477          * formatiert eine Zahl (0-999) dreistellig (z.B. 7 -> 007)
478          *
479          * @return 3-stellige Zahl
480          */
481         public static String pad3 (int number) {
482                 return  number < 10 ? "00" + number : number < 100 ? "0" + number : String.valueOf(number);
483         }
484
485         /**
486          * Konvertiert Unix-Linefeeds in Win-Linefeeds
487          * @param s
488          * @return Konvertierter String
489          */
490         public static String unixLineFeedsToWin(String s) {
491                 int i = -1;
492                 while (true) {
493                         i = s.indexOf('\n', i+1);
494                         if (i < 0) break;
495                         if ((i == 0 || s.charAt(i-1) != '\r') &&
496                                 (i == s.length()-1 || s.charAt(i+1) != '\r')) {
497                                 s = s.substring(0, i)+'\r'+s.substring(i);
498                                 i++;
499                         }
500                 }
501                 return s;
502         }
503
504
505         /**
506          * verwandelt einen String in eine gültige Url, konvertiert Sonderzeichen
507          * und Spaces werden zu Underscores
508          *
509          * @return gültige Url
510          */
511         public static String convert2url(String s) {
512                 s = toLowerCase(s);
513                 StringBuffer buf = new StringBuffer();
514                 for(int i = 0; i < s.length(); i++ ) {
515                                 switch( s.charAt( i ) ) {
516                                 case 'ö':
517                         buf.append( "oe" ); break;
518                                 case 'ä':
519                         buf.append( "ae" ); break;
520                                 case 'ü':
521                         buf.append( "ue" ); break;
522                                 case 'ã':
523                         buf.append( "a" ); break;
524                                 case '´':
525                                 case '.':
526                         buf.append( "_" ); break;
527                                 case ' ':
528                         if( buf.charAt( buf.length() - 1 ) != '_' ) {
529                                         buf.append( "_" );
530                         }
531                         break;
532                                 default:
533                         buf.append( s.charAt( i ) );
534                                 }
535                 }
536                 return buf.toString();
537         }
538
539         /**
540          * wandelt Sonderzeichen in Quotes um
541          *
542          * @return Kovertierter String
543          */
544         public static String encodeHtml(String s) {
545                 StringBuffer buf = new StringBuffer();
546                 for(int i=0;i < s.length(); i++ ) {
547
548                         /** @todo looks inefficient, to ask for index of every char, in
549                          *  case of failure it runs to the end.*/
550                         if (s.charAt(i)=='&') {
551                                 // convert html to xml-parsable representation
552                                 if( s.indexOf( "&ouml;", i ) == i ) {
553                                         buf.append( "&#246;" ); i += 5;
554                                         continue;
555                                 }
556                                 if( s.indexOf( "&auml;", i ) == i ) {
557                                         buf.append( "&#228;" ); i += 5;
558                                         continue;
559                                 }
560                                 if( s.indexOf( "&uuml;", i ) == i ) {
561                                         buf.append( "&#252;" ); i += 5;
562                                         continue;
563                                 }
564                                 if( s.indexOf( "&Ouml;", i ) == i ) {
565                                         buf.append( "&#214;" ); i += 5;
566                                         continue;
567                                 }
568                                 if( s.indexOf( "&Auml;", i ) == i ) {
569                                         buf.append( "&#196;" ); i += 5;
570                                         continue;
571                                 }
572                                 if( s.indexOf( "&Uuml;", i ) == i ) {
573                                         buf.append( "&#220;" ); i += 5;
574                                         continue;
575                                 }
576                                 if( s.indexOf( "&szlig;", i ) == i ) {
577                                         buf.append( "&#223;" ); i += 6;
578                                         continue;
579                                 }
580
581                                 /** @todo should only escape outside of tags */
582
583                                 if( s.indexOf( "&quot;", i ) == i ) {
584                                         buf.append( "&#223;" ); i += 5;
585                                         continue;
586                                 }
587                                 if( s.indexOf( "&ndash;", i ) == i ) {
588                                         buf.append( "&#8211;" ); i += 6;
589                                         continue;
590                                 }
591                                 if( s.indexOf( "&mdash;", i ) == i ) {
592                                         buf.append( "&#8212;" ); i += 6;
593                                         continue;
594                                 }
595                                 if( s.indexOf( "&ldquo;", i ) == i ) {
596                                         buf.append( "&#8220;" ); i += 6;
597                                         continue;
598                                 }
599                                 if( s.indexOf( "&rdquo;", i ) == i ) {
600                                         buf.append( "&#8221;" ); i += 6;
601                                         continue;
602                                 }
603                                 if( s.indexOf( "&bdquo;", i ) == i ) {
604                                         buf.append( "&#8222;" ); i += 6;
605                                         continue;
606                                 }
607
608                                 //looks pretty stupid
609                                 if( s.indexOf( "&lt;", i ) == i ) {
610                                         buf.append( "&lt;" ); i += 3;
611                                         continue;
612                                 }
613                                 if( s.indexOf( "&gt;", i ) == i ) {
614                                         buf.append( "&gt;" ); i += 3;
615                                         continue;
616                                 }
617                                 if( s.indexOf( "&acute;", i ) == i ) {
618                                         buf.append( "&acute;" ); i += 6;
619                                         continue;
620                                 }
621                                 if( s.indexOf( "&nbsp;", i ) == i ) {
622                                         buf.append( "&nbsp;" ); i += 5;
623                                         continue;
624                                 }
625                                 //has to be the last
626                                 //if( s.indexOf( "&", i ) == i ) {
627                                 //  buf.append( "&#38;" ); i += 0;
628                                 //  continue;
629                                 //}
630                         }
631                         // convert umlauts an other special charakters
632                         switch( s.charAt(i) ) {
633                                 case 'ö': buf.append( "&#246;" ); break;
634                                 case 'ä': buf.append( "&#228;" ); break;
635                                 case 'ü': buf.append( "&#252;" ); break;
636                                 case 'Ö': buf.append( "&#214;" ); break;
637                                 case 'Ä': buf.append( "&#196;" ); break;
638                                 case 'Ü': buf.append( "&#220;" ); break;
639                                 case 'ß': buf.append( "&#223;" ); break;
640                                 case 'é': buf.append( "&#233;" ); break;
641                                 case 'è': buf.append( "&#232;" ); break;
642                                 case 'á': buf.append( "&#225;" ); break;
643                                 case 'à': buf.append( "&#224;" ); break;
644                                 case 'â': buf.append( "&#226;" ); break;
645                                 case 'ã': buf.append( "&#227;" ); break;
646                                 case '¬': buf.append( "&#172;" ); break;
647                                 case '¹': buf.append( "&#185;" ); break;
648                                 case '²': buf.append( "&#178;" ); break;
649                                 case '³': buf.append( "&#179;" ); break;
650                                 case '¼': buf.append( "&#188;" ); break;
651                                 case '½': buf.append( "&#189;" ); break;
652                                 case '¾': buf.append( "&#190;" ); break;
653                                 case '¶': buf.append( "&#182;" ); break;
654                                 case 'æ': buf.append( "&#230;" ); break;
655                                 case 'ð': buf.append( "&#240;" ); break;
656                                 case '|': buf.append( "&#166;" ); break;
657                                 case '·': buf.append( "&#183;" ); break;
658                                 case '°': buf.append( "&#176;" ); break;
659                                 case '§': buf.append( "&#167;" ); break;
660                                 case 'ø': buf.append( "&#248;" ); break;
661                                 case 'ç': buf.append( "&#231;" ); break;
662                                 case '¤': buf.append( "&#164;" ); break;
663                                 case 'ª': buf.append( "&#170;" ); break;
664                                 case 'Ç': buf.append( "&#199;" ); break;
665                                 case 'Ã': buf.append( "&#195;" ); break;
666                                 case 'Â': buf.append( "&#194;" ); break;
667                                 case 'Æ': buf.append( "&#198;" ); break;
668                                 case '©': buf.append( "&#169;" ); break;
669                                 case '®': buf.append( "&#174;" ); break;
670                                 case '¥': buf.append( "&#165;" ); break;
671                                 case 'Þ': buf.append( "&#254;" ); break;
672                                 case '¯': buf.append( "&#175;" ); break;
673                                 case 'Ð': buf.append( "&#208;" ); break;
674                                 case 'º': buf.append( "&#186;" ); break;
675                                 case '¡': buf.append( "&#161;" ); break;
676                                 case '£': buf.append( "&#163;" ); break;
677                                 case '±': buf.append( "&#177;" ); break;
678                                 case '¿': buf.append( "&#191;" ); break;
679                                 case 'Ø': buf.append( "&#216;" ); break;
680                                 case 'Á': buf.append( "&#192;" ); break;
681                                 case 'À': buf.append( "&#193;" ); break;
682                                 case 'É': buf.append( "&#200;" ); break;
683                                 case 'È': buf.append( "&#201;" ); break;
684                                 case 'ù': buf.append( "&#250;" ); break;
685                                 case 'ñ': buf.append( "&#241;" ); break;
686                                 case 'Ñ': buf.append( "&#209;" ); break;
687                                 case 'µ': buf.append( "&#181;" ); break;
688                                 case 'Í': buf.append( "&#204;" ); break;
689                                 case 'Ì': buf.append( "&#205;" ); break;
690                                 case 'í': buf.append( "&#236;" ); break;
691                                 case 'ì': buf.append( "&#237;" ); break;
692                                 case 'î': buf.append( "&#238;" ); break;
693                                 case 'Î': buf.append( "&#206;" ); break;
694                                 case 'ó': buf.append( "&#243;" ); break;
695                                 case 'Ó': buf.append( "&#210;" ); break;
696                                 case 'ò': buf.append( "&#206;" ); break;
697                                 case 'Ò': buf.append( "&#211;" ); break;
698                                 case 'ô': buf.append( "&#244;" ); break;
699                                 case 'Ô': buf.append( "&#212;" ); break;
700                                 case 'õ': buf.append( "&#245;" ); break;
701                                 case 'Õ': buf.append( "&#213;" ); break;
702                                 case 'ý': buf.append( "&#253;" ); break;
703                                 case 'Ý': buf.append( "&#221;" ); break;
704                                 case 'û': buf.append( "&#251;" ); break;
705                                 case 'Û': buf.append( "&#219;" ); break;
706                                 case 'ú': buf.append( "&#249;" ); break;
707                                 case 'Ú': buf.append( "&#217;" ); break;
708                                 case 'Ù': buf.append( "&#218;" ); break;
709                                 case 'Ê': buf.append( "&#202;" ); break;
710                                 case 'ê': buf.append( "&#234;" ); break;
711                                 case 'å': buf.append( "&#229;" ); break;
712                                 case 'Å': buf.append( "&#197;" ); break;
713                                 case 'ë': buf.append( "&#235;" ); break;
714                                 case 'Ë': buf.append( "&#203;" ); break;
715                                 case 'ÿ': buf.append( "&#255;" ); break;
716                                 case 'ï': buf.append( "&#239;" ); break;
717                                 case 'Ï': buf.append( "&#207;" ); break;
718                                 case '«': buf.append( "&#171;" ); break;
719                                 case '»': buf.append( "&#187;" ); break;
720                                 case '\'': buf.append( "&acute;" ); break;
721                                 case '\"': buf.append( "&quot;" ); break;
722                                 //case '\u8211': buf.append( "&#8211;" ); break;
723                                 //case '\u8212': buf.append( "&#8212;" ); break;
724                                 //case '\u8220': buf.append( "&#8220;" ); break;
725                                 //case '\u8221': buf.append( "&#8221;" ); break;
726                                 //case '\u8222': buf.append( "&#8222;" ); break;
727                                 //case '\"': buf.append( "&#34;" ); break;
728                                 default: buf.append( s.charAt(i) );
729                         }
730
731                 }
732                 return buf.toString();
733         }
734
735
736         public static String decodeHTMLinTags(String s){
737                 StringBuffer buffer = new StringBuffer();
738                 boolean start = false;
739                 boolean stop = false;
740                 int startIndex = 0;
741                 int stopIndex = 0;
742                 int temp = 0;
743
744                 for(int i=0;i<s.length();i++){
745                         if(s.charAt(i)=='<'){
746                                 start = true;
747                                 startIndex = i;
748                         } else if(s.charAt(i)=='>'){
749                                 stop = true;
750                                 stopIndex = i;
751
752                                 if(start && stop){
753                                         buffer.append(s.substring(temp,startIndex));
754                                         buffer.append(replaceQuot(s.substring(startIndex,stopIndex+1)));
755                                         i= temp= stopIndex+1;
756                                         start= stop= false;
757                                 }
758                         }
759                 }
760                 if(stopIndex>0){
761                         buffer.append(s.substring(stopIndex+1));
762                         return buffer.toString();
763                 } else {
764                         return s;
765                 }
766         }
767
768         public static String replaceQuot(String s) {
769                 StringBuffer buffer = new StringBuffer();
770                 for(int j = 0; j < s.length();j++){
771                         if(s.charAt(j)=='&'){
772                                 if(s.indexOf( "&quot;",j) == j) {
773                                         buffer.append( "\"" );
774                                         j += 5;
775                                 }//if
776                         } else {
777                                 buffer.append(s.charAt(j));
778                         }//else
779                 }//for
780                 return buffer.toString();
781         }
782
783         /** wandelt Quotes in Sonderzeichen um
784          */
785         /**
786         public static String decodeHtml(String s) {
787                 StringBuffer buf = new StringBuffer();
788                 for(int i=0;i < s.length(); i++ ) {
789                         if( s.indexOf( "&ouml;", i ) == i ) {
790                                 buf.append( "ö" ); i += 5;
791                                 continue;
792                         }
793                         if( s.indexOf( "&auml;", i ) == i ) {
794                                 buf.append( "ä" ); i += 5;
795                                 continue;
796                         }
797                         if( s.indexOf( "&uuml;", i ) == i ) {
798                                 buf.append( "ü" ); i += 5;
799                                 continue;
800                         }
801                         if( s.indexOf( "&Ouml;", i ) == i ) {
802                                 buf.append( "Ö" ); i += 5;
803                                 continue;
804                         }
805                         if( s.indexOf( "&Auml;", i ) == i ) {
806                                 buf.append( "Ä" ); i += 5;
807                                 continue;
808                         }
809                         if( s.indexOf( "&Uuml;", i ) == i ) {
810                                 buf.append( "Ü" ); i += 5;
811                                 continue;
812                         }
813                         if( s.indexOf( "&szlig;", i ) == i ) {
814                                 buf.append( "ß" ); i += 6;
815                                 continue;
816                         }
817                         if( s.indexOf( "&quot;", i ) == i ) {
818                                 buf.append( "\"" ); i += 5;
819                                 continue;
820                         }
821                         buf.append( s.charAt(i) );
822                 }
823                 return buf.toString();
824         }
825          */
826
827         /**
828          * schnellere Variante der String.toLowerCase()-Routine
829          *
830          * @return String in Kleinbuchsten
831          */
832         public static String toLowerCase(String s) {
833                 int l = s.length();
834                 char[] a = new char[l];
835                 for (int i = 0; i < l; i++)
836                         a[i] = Character.toLowerCase(s.charAt(i));
837                 return new String(a);
838         }
839
840                 /**
841          * Findet <code>element</code> im String-Array <code>array</code>
842          * @param array
843          * @param element
844          * @return Fundstelle als int oder -1
845          */
846         public static int indexOf(String[] array, String element) {
847                 if (array != null)
848                         for (int i = 0; i < array.length; i++)
849                                 if (array[i].equals(element))
850                                         return i;
851                 return -1;
852         }
853
854         /**
855          * Testet auf Vorkommen von <code>element</code> in <code>array</code>
856          * @param array String-Array
857          * @param element
858          * @return true wenn <code>element</code> vorkommt, sonst false
859          */
860         public static boolean contains(String[] array, String element) {
861                 return indexOf(array, element) >= 0;
862         }
863
864                 /**
865          * Ermittelt CRC-Prüfsumme von String <code>s</code>
866          * @param s
867          * @return CRC-Prüfsumme
868          */
869         public static int getCRC(String s) {
870                 int h = 0;
871                 char val[] = s.toCharArray();
872                 int len = val.length;
873
874                 for (int i = 0 ; i < len; i++) {
875                         h &= 0x7fffffff;
876                         h = (((h >> 30) | (h << 1)) ^ (val[i]+i));
877                 }
878
879                 return (h << 8) | (len & 0xff);
880         }
881
882                 /**
883          * Liefert Default-Wert def zurück, wenn String <code>s</code>
884          * kein Integer ist.
885          *
886          * @param s
887          * @param def
888          * @return geparster int aus s oder def
889          */
890         public static int parseInt(String s, int def) {
891                 if (s == null) return def;
892                 try {
893                         return Integer.parseInt(s);
894                 } catch (NumberFormatException e) {
895                         return def;
896                 }
897         }
898
899         /**
900          * Liefert Defaultwert def zurück, wenn s nicht zu einem float geparsed werden kann.
901          * @param s
902          * @param def
903          * @return geparster float oder def
904          */
905         public static float parseFloat(String s, float def) {
906                 if (s == null) return def;
907                 try {
908                         return new Float(s).floatValue();
909                 } catch (NumberFormatException e) {
910                         return def;
911                 }
912         }
913
914                 /**
915          * Findet Ende eines Satzes in String <code>text</code>
916          * @param text
917          * @param startIndex
918          * @return index des Satzendes, oder -1
919          */
920         public static int findEndOfSentence(String text, int startIndex) {
921                  while (true) {
922                          int i = text.indexOf('.', startIndex);
923                          if (i < 0) return -1;
924                          if (i > 0 && !Character.isDigit(text.charAt(i-1)) &&
925                                         (i+1 >= text.length()
926                                         || text.charAt(i+1) == ' '
927                                         || text.charAt(i+1) == '\n'
928                                         || text.charAt(i+1) == '\t'))
929                                         return i+1;
930                          startIndex = i+1;
931                  }
932         }
933
934                 /**
935          * Findet Wortende in String <code>text</code> ab <code>startIndex</code>
936          * @param text
937          * @param startIndex
938          * @return Index des Wortendes, oder -1
939          */
940         public static int findEndOfWord(String text, int startIndex) {
941                 int i = text.indexOf(' ', startIndex),
942                         j = text.indexOf('\n', startIndex);
943                 if (i < 0) i = text.length();
944                 if (j < 0) j = text.length();
945                 return Math.min(i, j);
946         }
947
948
949         /**
950          *  convertNewline2P ist eine regex-routine zum umwandeln von 2 oder mehr newlines (\n)
951          *  in den html-tag <p>
952          *  nur sinnvoll, wenn text nicht im html-format eingegeben
953          */
954         public static String convertNewline2P(String haystack) {
955                         return re_brbr2p.substituteAll(haystack,"\n</p><p>");
956         }
957
958         /**
959          *  convertNewline2Break ist eine regex-routine zum umwandeln von 1 newline (\n)
960          *  in den html-tag <br>
961          *  nur sinnvoll, wenn text nicht im html-format eingegeben
962          */
963         public static String convertNewline2Break(String haystack) {
964                 return re_newline2br.substituteAll(haystack,"$0<br />");
965         }
966
967         /**
968          *  createMailLinks wandelt text im email-adressenformat
969          *  in einen klickbaren link um
970          *  nur sinnvoll, wenn text nicht im html-format eingegeben
971          */
972         public static String createMailLinks(String haystack) {
973                         return re_mail.substituteAll(haystack,"<a href=\"mailto:$0\">$0</a>");
974         }
975
976
977         /**
978          *  createMailLinks wandelt text im email-adressenformat
979          *  in einen klickbaren link um
980          *  nur sinnvoll, wenn text nicht im html-format eingegeben
981          */
982         public static String createMailLinks(String haystack, String imageRoot, String mailImage) {
983                 return re_mail.substituteAll(haystack,"<img src=\""+imageRoot+"/"+mailImage+"\" border=\"0\"/>&#160;<a href=\"mailto:$0\">$0</a>");
984         }
985
986
987         /**
988          *  createURLLinks wandelt text im url-format
989          *  in einen klickbaren link um
990          *  nur sinnvoll, wenn text nicht im html-format eingegeben
991          */
992         public static String createURLLinks(String haystack) {
993                 return re_url.substituteAll(haystack,"<a href=\"$0\">$0</a>");
994         }
995
996         /**
997          * this routine takes text in url format and makes
998          * a clickaeble "<href>" link removing any "illegal" html tags
999          * @param haystack, the url
1000          * @param title, the href link text
1001          * @param imagRoot, the place to find icons
1002          * @param extImage, the url of the icon to show next to the link
1003          * @return a String containing the url
1004          */
1005         public static String createURLLinks(String haystack, String title, String imageRoot,String extImage) {
1006                 if (title == null) {
1007                         return re_url.substituteAll(haystack,"<img src=\""+imageRoot+"/"+extImage+"\" border=\"0\"/>&#160;<a href=\"$0\">$0</a>");
1008                 } else {
1009                         title = removeHTMLTags(title);
1010                         return re_url.substituteAll(haystack,"<img src=\""+imageRoot+"/"+extImage+"\" border=\"0\"/>&#160;<a href=\"$0\">"+title+"</a>");
1011                 }
1012         }
1013
1014         /**
1015          * this routine takes text in url format and makes
1016          * a clickaeble "<href>" link removing any "illegal" html tags
1017          * @param haystack, the url
1018          * @param imageRoot, the place to find icons
1019          * @param extImage, the url of the icon to show next to the link
1020          * @param intImage, unused
1021          * @return a String containing the url
1022          */
1023         public static String createURLLinks(String haystack, String title, String imageRoot,String extImage,String intImage) {
1024                 return createURLLinks(haystack, title, imageRoot, extImage);
1025         }
1026
1027          /**
1028          *  deleteForbiddenTags
1029          *  this method deletes all <script>, <body> and <head>-tags
1030          */
1031         public static final String deleteForbiddenTags(String haystack) {
1032                 try {
1033                         RE regex = new RE("<[ \t\r\n](.*?)script(.*?)/script(.*?)>",RE.REG_ICASE);
1034                         haystack = regex.substituteAll(haystack,"");
1035                         regex = new RE("<head>(.*?)</head>");
1036                         haystack = regex.substituteAll(haystack,"");
1037                         regex = new RE("<[ \t\r\n/]*body(.*?)>");
1038                         haystack = regex.substituteAll(haystack,"");
1039                         return haystack;
1040                 } catch(REException ex){
1041                         return null;
1042                 }
1043         }
1044
1045         /**
1046          * this method deletes all html tags
1047          */
1048         public static final String removeHTMLTags(String haystack){
1049                         return re_tags.substituteAll(haystack,"");
1050         }
1051
1052
1053         /**
1054          * this method deletes all but the approved tags html tags
1055          * it also deletes approved tags which contain malicious-looking attributes and doesn't work at all
1056          */
1057         public static String approveHTMLTags(String haystack){
1058                 try {
1059                         String approvedTags="a|img|h1|h2|h3|h4|h5|h6|br|b|i|strong|p";
1060                         String badAttributes="onAbort|onBlur|onChange|onClick|onDblClick|onDragDrop|onError|onFocus|onKeyDown|onKeyPress|onKeyUp|onLoad|onMouseDown|onMouseMove|onMouseOut|onMouseOver|onMouseUp|onMove|onReset|onResize|onSelect|onSubmit|onUnload";
1061                         String approvedProtocols="rtsp|http|ftp|https|freenet|mailto";
1062
1063                         // kill all the bad tags that have attributes
1064                         String s = "<\\s*/?\\s*(?!(("+approvedTags+")\\s))\\w+\\s[^>]*>";
1065                         RE regex = new RE(s,RE.REG_ICASE);
1066                         haystack = regex.substituteAll(haystack,"");
1067
1068                         // kill all the bad tags that are attributeless
1069                         regex = new RE("<\\s*/?\\s*(?!(("+approvedTags+")\\s*>))\\w+\\s*>",RE.REG_ICASE);
1070                         haystack = regex.substituteAll(haystack,"");
1071
1072                         // kill all the tags which have a javascript attribute like onLoad
1073                         regex = new RE("<[^>]*("+badAttributes+")[^>]*>",RE.REG_ICASE);
1074                         haystack = regex.substituteAll(haystack,"");
1075
1076                         // kill all the tags which include a url to an unacceptable protocol
1077                         regex = new RE("<\\s*a\\s+[^>]*href=(?!(\'|\")?("+approvedProtocols+"))[^>]*>",RE.REG_ICASE);
1078                         haystack = regex.substituteAll(haystack,"");
1079
1080                         return haystack;
1081                 } catch(REException ex){
1082                         ex.printStackTrace();
1083                         return null;
1084                 }
1085         }
1086
1087
1088         /**
1089          *  createHTML ruft alle regex-methoden zum unwandeln eines nicht
1090          *  htmlcodierten string auf und returnt einen htmlcodierten String
1091          */
1092         public static String createHTML(String content){
1093                 content=convertNewline2Break(content);
1094                 content=convertNewline2P(content);
1095                 content=createMailLinks(content);
1096                 content=createURLLinks(content);
1097                 return content;
1098         }
1099
1100
1101         /**
1102          *  createHTML ruft alle regex-methoden zum unwandeln eines nicht
1103          *  htmlcodierten string auf und returnt einen htmlcodierten String
1104          */
1105         public static String createHTML(String content,String producerDocRoot,String mailImage,String extImage,String intImage){
1106                 content=convertNewline2Break(content);
1107                 content=convertNewline2P(content);
1108                 content=createMailLinks(content,producerDocRoot,mailImage);
1109                 content=createURLLinks(content,null,producerDocRoot,extImage,intImage);
1110                 return content;
1111         }
1112
1113 }
1114