2956bd839a640f4dcbba913438c63cf4e67091f6
[mir.git] / source / mir / misc / StringUtil.java
1 /*
2  * Copyright (C) 2001, 2002  The Mir-coders group
3  *
4  * This file is part of Mir.
5  *
6  * Mir is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * Mir is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with Mir; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  *
20  * In addition, as a special exception, The Mir-coders gives permission to link
21  * the code of this program with the com.oreilly.servlet library, any library
22  * licensed under the Apache Software License, The Sun (tm) Java Advanced
23  * Imaging library (JAI), The Sun JIMI library (or with modified versions of
24  * the above that use the same license as the above), and distribute linked
25  * combinations including the two.  You must obey the GNU General Public
26  * License in all respects for all of the code used other than the above
27  * mentioned libraries.  If you modify this file, you may extend this exception
28  * to your version of the file, but you are not obligated to do so.  If you do
29  * not wish to do so, delete this exception statement from your version.
30  */
31
32 package  mir.misc;
33
34 import  java.io.*;
35 import  java.lang.*;
36 import  java.util.*;
37 import  java.text.NumberFormat;
38 import  gnu.regexp.*;
39
40 /**
41  * Statische Hilfsmethoden zur Stringbehandlung
42  *
43  * @version $Revision: 1.25 $ $Date: 2002/09/14 03:32:12 $
44  * @author $Author: zapata $
45  *
46  * $Log: StringUtil.java,v $
47  * Revision 1.25  2002/09/14 03:32:12  zapata
48  * fixed a small email address filtering bug
49  *
50  * Revision 1.24  2002/09/01 22:05:50  mh
51  * Mir goes GPL
52  *
53  * Revision 1.23.2.1  2002/09/01 21:31:40  mh
54  * Mir goes GPL
55  *
56  * Revision 1.23  2002/06/28 20:39:37  mh
57  * added numberformat helper. make webdbDate2readableDate use webdb_create instead. make the order and appearance of it more consistent. cvs macros. and finally code tidying
58  *
59  *
60  */
61 public final class StringUtil {
62
63         private static RE   re_newline2br, re_brbr2p, re_mail, re_url, re_tags;
64
65         private StringUtil() { }  // this avoids contruction
66
67         static {
68                 try {
69                         //precompile regex
70                         re_newline2br = new RE("(\r?\n){1}");
71                         re_brbr2p     = new RE("(<br>\r?\n<br>){1,}");
72                         re_mail       = new RE("([a-zA-Z0-9_.-]+)@([a-zA-Z0-9_-]+)\\.([a-zA-Z0-9_.-]+)");
73                         re_url        = new RE("((https://)|(http://)|(ftp://)){1}([a-zA-Z0-9_-]+).([a-zA-Z0-9_.:-]+)/?([^ \t\r\n<>\\)\\]]+[^ \t\r\n.,<>\\)\\]])");
74                         re_tags       = new RE("<[^>]*>",RE.REG_ICASE);
75                 }
76                 catch (REException e){
77                         System.err.println("FATAL: StringUtil: could not precompile REGEX: "+e.toString());
78                 }
79         }
80
81   /**
82    * Formats a number with the specified minimum and maximum number of digits.
83    **/
84   public static synchronized String zeroPaddingNumber(long value, int minDigits,
85                                                       int maxDigits)
86   {
87     NumberFormat numberFormat = NumberFormat.getInstance();
88     numberFormat.setMinimumIntegerDigits(minDigits);
89     numberFormat.setMaximumIntegerDigits(maxDigits);
90     return numberFormat.format(value);
91   }
92
93         /**
94          * Wandelt Datum in einen 8-ziffrigen String um (yyyymmdd)
95          * @param theDate
96          * @return 8-ziffriger String (yyyymmdd)
97          */
98
99         public static final String date2webdbDate (GregorianCalendar theDate) {
100                 StringBuffer webdbDate = new StringBuffer();
101                 webdbDate.append(String.valueOf(theDate.get(Calendar.YEAR)));
102                 webdbDate.append(pad2(theDate.get(Calendar.MONTH) + 1));
103                 webdbDate.append(pad2(theDate.get(Calendar.DATE)));
104                 return  webdbDate.toString();
105         }
106
107         /**
108          * Wandelt Calendar in einen 12-ziffrigen String um (yyyymmddhhmm)
109          * @param theDate
110          * @return 12-ziffriger String (yyyymmdd)
111          */
112
113         public static final String date2webdbDateTime (GregorianCalendar theDate) {
114                 StringBuffer webdbDate = new StringBuffer();
115                 webdbDate.append(String.valueOf(theDate.get(Calendar.YEAR)));
116                 webdbDate.append(pad2(theDate.get(Calendar.MONTH) + 1));
117                 webdbDate.append(pad2(theDate.get(Calendar.DATE)));
118                 webdbDate.append(pad2(theDate.get(Calendar.HOUR)));
119                 webdbDate.append(pad2(theDate.get(Calendar.MINUTE)));
120                 return  webdbDate.toString();
121         }
122
123         /**
124          * Return a http://www.w3.org/TR/NOTE-datetime formatted date (yyyy-mm-ddThh:mm:ssTZ)
125          * @param theDate
126          * @return w3approved datetime
127          */
128
129         public static final String date2w3DateTime (GregorianCalendar theDate) {
130                 StringBuffer webdbDate = new StringBuffer();
131                 webdbDate.append(String.valueOf(theDate.get(Calendar.YEAR)));
132                 webdbDate.append("-");
133                 webdbDate.append(pad2(theDate.get(Calendar.MONTH) + 1));
134                 webdbDate.append("-");
135                 webdbDate.append(pad2(theDate.get(Calendar.DATE)));
136                 webdbDate.append("T");
137                 webdbDate.append(pad2(theDate.get(Calendar.HOUR)));
138                 webdbDate.append(":");
139                 webdbDate.append(pad2(theDate.get(Calendar.MINUTE)));
140                 webdbDate.append(":");
141                 webdbDate.append(pad2(theDate.get(Calendar.SECOND)));
142                 //assumes you are an hour-multiple away from UTC....
143                 int offset=(theDate.get(Calendar.ZONE_OFFSET)/(60*60*1000));
144                 if (offset < 0){
145                 webdbDate.append("-");
146                 }
147                 else{
148                 webdbDate.append("+");
149                 }
150                 webdbDate.append(pad2(Math.abs(offset)));
151                 webdbDate.append(":00");
152                 return  webdbDate.toString();
153         }
154
155         /**
156          * wandelt Calendar in dd.mm.yyyy / hh.mm um
157          * @param theDate
158          * @return String mit (dd.mm.yyyy / hh.mm um)
159          */
160         public static String date2readableDateTime (GregorianCalendar theDate) {
161                 String readable = "";
162                 int hour;
163                 readable += pad2(theDate.get(Calendar.DATE));
164                 readable += "." + pad2(theDate.get(Calendar.MONTH) + 1);
165                 readable += "." + String.valueOf(theDate.get(Calendar.YEAR));
166                 hour = theDate.get(Calendar.HOUR);
167                 if (theDate.get(Calendar.AM_PM) == Calendar.PM)
168                         hour += 12;
169                 readable += " / " + pad2(hour);
170                 readable += ":" + pad2(theDate.get(Calendar.MINUTE));
171                 return  readable;
172         }
173
174         /**
175          * wandelt eine Datum in einen 8-buchstabigen String, der durch <code>/</code>
176          * getrennt ist.
177          *
178          * @param webdbDate
179          * @return String mit <code>/yyyy/mm/dd</code>
180          */
181         public static final String webdbDate2path (String webdbDate) {
182                 StringBuffer path = new StringBuffer();
183                 path.append("/").append(webdbDate.substring(0, 4));
184                 path.append("/").append(webdbDate.substring(4, 6));
185                 path.append("/");
186                 //who did this?
187                 //path.append("/").append(webdbDate.substring(6, 8));
188                 return  path.toString();
189         }
190
191         /**
192          * wandelt Calendar in dd.mm.yyyy um
193          *
194          * @param theDate
195          * @return String mit  <code>yyyy.mm.dd</code>
196          */
197         public static final String webdbDate2readableDate (String webdbDate) {
198                 String date = "";
199                 date += webdbDate.substring(0, 4);
200                 date += "-" + webdbDate.substring(5, 7);
201                 date += "-"+webdbDate.substring(8, 10);
202                 return  date;
203         }
204
205
206         /**
207          * converts string from format: yyyy-mm-dd__hh:mm:ss.d
208          * to dd.mm.yyyy hh:mm
209          */
210         public static String dateToReadableDate(String date) {
211                 StringBuffer returnDate = new StringBuffer();
212                 if (date!=null) {
213
214                         returnDate.append(date.substring(8,10)).append('.');
215                         returnDate.append(date.substring(5,7)).append('.');
216                         returnDate.append(date.substring(0,4)).append(' ');
217                         returnDate.append(date.substring(11,16));
218                 }
219                 return returnDate.toString();
220         }
221
222   /**
223          * converts string from format: yyyy-mm-dd__hh:mm:ss.dddddd+TZ
224          * to yyyy-mm-ddThh:mm:ss+TZ:00 (w3 format for Dublin Core)
225          */
226         public static String webdbdateToDCDate(String date) {
227                 StringBuffer returnDate = new StringBuffer();
228                 if (date!=null) {
229       returnDate.append(date.substring(0,10));
230       returnDate.append("T");
231       returnDate.append(date.substring(11,19));
232       //String tzInfo=date.substring(26,29);
233       //if (tzInfo.equals("+00")){
234       //UTC gets a special code in w3 dates
235       //    returnDate.append("Z");
236       //}
237       //else{
238       //need to see what a newfoundland postgres
239       //timestamp looks like before making this robust
240       //    returnDate.append(tzInfo);
241       //    returnDate.append(":00");
242       //}
243
244                 }
245                 return returnDate.toString();
246         }
247
248
249         /**
250          * converts string from format: yyyy-mm-dd__hh:mm:ss.d
251          * to yyyy
252          */
253         public static String dateToYear (String date) {
254                 StringBuffer returnDate = new StringBuffer();
255                 if (date!=null) {
256
257                         returnDate.append(date.substring(0,4));
258                 }
259                 return returnDate.toString();
260         }
261
262         /**
263          * converts string from format: yyyy-mm-dd__hh:mm:ss.d
264          * to [m]m
265          */
266         public static String dateToMonth (String date) {
267                 StringBuffer returnDate = new StringBuffer();
268                 if (date!=null) {
269                         if (!date.substring(5,6).equalsIgnoreCase("0")) returnDate.append(date.substring(5,7));
270                         else returnDate.append(date.substring(6,7));
271                 }
272                 return returnDate.toString();
273         }
274
275         /**
276          * converts string from format: yyyy-mm-dd__hh:mm:ss.d
277          * to [d]d
278          */
279         public static String dateToDayOfMonth (String date) {
280                 StringBuffer returnDate = new StringBuffer();
281                 if (date!=null) {
282                         if (!date.substring(8,9).equalsIgnoreCase("0")) returnDate.append(date.substring(8,10));
283                         else returnDate.append(date.substring(9,10));
284                 }
285                 return returnDate.toString();
286         }
287
288         /**
289          * converts string from format: yyyy-mm-dd__hh:mm:ss.d
290          * to hh:mm
291          */
292         public static String dateToTime (String date) {
293                 StringBuffer returnDate = new StringBuffer();
294                 if (date!=null) {
295                         returnDate.append(date.substring(11,16));
296                 }
297                 return returnDate.toString();
298         }
299
300     /**
301      * Splits the provided CSV text into a list. stolen wholesale from
302      * from Jakarta Turbine StrinUtils.java -mh
303      *
304      * @param text      The CSV list of values to split apart.
305      * @param separator The separator character.
306      * @return          The list of values.
307      */
308     public static String[] split(String text, String separator)
309     {
310         StringTokenizer st = new StringTokenizer(text, separator);
311         String[] values = new String[st.countTokens()];
312         int pos = 0;
313         while (st.hasMoreTokens())
314         {
315             values[pos++] = st.nextToken();
316         }
317         return values;
318     }
319
320     /**
321      * Joins the elements of the provided array into a single string
322      * containing a list of CSV elements. Stolen wholesale from Jakarta
323      * Turbine StringUtils.java. -mh
324      *
325      * @param list      The list of values to join together.
326      * @param separator The separator character.
327      * @return          The CSV text.
328      */
329     public static String join(String[] list, String separator)
330     {
331         StringBuffer csv = new StringBuffer();
332         for (int i = 0; i < list.length; i++)
333         {
334             if (i > 0)
335             {
336                 csv.append(separator);
337             }
338             csv.append(list[i]);
339         }
340         return csv.toString();
341     }
342
343
344         /**
345          * schließt einen String in Anführungsszeichen ein, falls er Leerzeichen o.ä. enthält
346          *
347          * @return gequoteter String
348          */
349          public static String quoteIfNecessary(String s) {
350                 for (int i = 0; i < s.length(); i++)
351                         if (!(Character.isLetterOrDigit(s.charAt(i)) || s.charAt(i) == '.'))
352                                 return quote(s, '"');
353                 return s;
354         }
355
356          /**
357          * schließt <code>s</code> in <code>'</code> ein und setzt Backslashes vor
358          * "gefährliche" Zeichen innerhalb des Strings
359          * Quotes special SQL-characters in <code>s</code>
360          *
361          * @return geqoteter String
362          */
363         public static String quote(String s)
364         {
365                 //String s2 = quote(s, '\'');
366                 //Quickhack     ÃŠÃŠ ÃŠ ÃŠ ÃŠ ÃŠ ÃŠ ÃŠ
367                 //Because of '?-Bug in Postgresql-JDBC-Driver
368                 StringBuffer temp = new StringBuffer();
369                 for(int i=0;i<s.length();i++){
370                         if(s.charAt(i)=='\''){
371                                 temp.append("&#39;");
372                         } else {
373                                 temp.append(s.charAt(i));
374                         }
375                 }
376                 String s2 = temp.toString();
377                 //end Quickhack
378
379                 s2 = quote(s2, '\"');
380                 return s2;
381         }
382
383         /**
384          * schließt <code>s</code> in <code>'</code> ein und setzt Backslashes vor
385          * "gefährliche" Zeichen innerhalb des Strings
386          *
387          * @param s String, der gequoted werden soll
388          * @param quoteChar zu quotendes Zeichen
389          * @return gequoteter String
390          */
391         public static String quote(String s, char quoteChar)
392         {
393                 StringBuffer buf = new StringBuffer(s.length());
394                 int pos = 0;
395                 while (pos < s.length()) {
396                         int i = s.indexOf(quoteChar, pos);
397                         if (i < 0) i = s.length();
398                         buf.append(s.substring(pos, i));
399                         pos = i;
400                         if (pos < s.length()) {
401                                 buf.append('\\');
402                                 buf.append(quoteChar);
403                                 pos++;
404                         }
405                 }
406                 return buf.toString();
407         }
408
409         /**
410          * replaces dangerous characters in <code>s</code>
411          *
412          */
413
414         public static String unquote(String s)
415         {
416                 char quoteChar='\'';
417                 StringBuffer buf = new StringBuffer(s.length());
418                 int pos = 0;
419                 String searchString = "\\"+quoteChar;
420                 while (pos < s.length()) {
421                         int i = s.indexOf(searchString, pos);
422                         if (i < 0) i = s.length();
423                         buf.append(s.substring(pos, i));
424                         pos = i+1;
425                 }
426                 return buf.toString();
427         }
428
429         /**
430          * Wandelet String in byte[] um.
431          * @param s
432          * @return byte[] des String
433          */
434
435         public static byte[] stringToBytes(String s) {
436                 String crlf = System.getProperty("line.separator");
437                 if (!crlf.equals("\n"))
438                         s = replace(s, "\n", crlf);
439                 // byte[] buf = new byte[s.length()];
440                 byte[] buf = s.getBytes();
441                 return buf;
442         }
443
444                 /**
445          * Ersetzt in String <code>s</code> das <code>pattern</code> durch <code>substitute</code>
446          * @param s
447          * @param pattern
448          * @param substitute
449          * @return String mit den Ersetzungen
450          */
451         public static String replace(String s, String pattern, String substitute) {
452                 int i = 0, pLen = pattern.length(), sLen = substitute.length();
453                 StringBuffer buf = new StringBuffer(s.length());
454                 while (true) {
455                         int j = s.indexOf(pattern, i);
456                         if (j < 0) {
457                                 buf.append(s.substring(i));
458                                 break;
459                         } else {
460                                 buf.append(s.substring(i, j));
461                                 buf.append(substitute);
462                                 i = j+pLen;
463                         }
464                 }
465                 return buf.toString();
466         }
467
468         /**
469          * Ersetzt in String <code>s</code> das Regexp <code>pattern</code> durch <code>substitute</code>
470          * @param s
471          * @param pattern
472          * @param substitute
473          * @return String mit den Ersetzungen
474          */
475         public static String regexpReplace(String haystack, String pattern, String substitute) {
476                 try {
477                         RE regex = new RE(pattern);
478                         return regex.substituteAll(haystack,substitute);
479                 } catch(REException ex){
480                         return null;
481                 }
482         }
483
484
485
486
487         /**
488          * Fügt einen Separator an den Pfad an
489          * @param path
490          * @return Pfad mit Separator am Ende
491          */
492         public static final String addSeparator (String path) {
493                 return  path.length() == 0 || path.endsWith(File.separator) ? path : path
494                                 + File.separatorChar;
495         }
496
497         /**
498          * Fügt ein <code>/</code> ans ende des Strings and
499          * @param path
500          * @return Pfad mit <code>/</code> am Ende
501          */
502         public static final String addSlash (String path) {
503                 return  path.length() == 0 || path.endsWith("/") ? path : path + '/';
504         }
505
506         /**
507          * Löscht <code>/</code> am Ende des Strings, falls vorhanden
508          * @param path
509          * @return String ohne <code>/</code> am Ende
510          */
511         public static final String removeSlash (String path) {
512                 return  path.length() > 1 && path.endsWith("/") ? path.substring(0, path.length()
513                                 - 1) : path;
514         }
515
516         /**
517          * Checks to see if the path is absolute by looking for a leading file
518          * separater
519          * @param path
520          * @return
521          */
522         public static boolean isAbsolutePath (String path) {
523                 return  path.startsWith(File.separator);
524         }
525
526         /**
527          * Löscht Slash am Anfang des Strings
528          * @param path
529          * @return
530          */
531         public static String removeFirstSlash (String path) {
532                 return  path.startsWith("/") ? path.substring(1) : path;
533         }
534
535         /**
536          * formatiert eine Zahl (0-99) zweistellig (z.B. 5 -> 05)
537          * @return zwistellige Zahl
538          */
539         public static String pad2 (int number) {
540                 return  number < 10 ? "0" + number : String.valueOf(number);
541         }
542
543         /**
544          * formatiert eine Zahl (0-999) dreistellig (z.B. 7 -> 007)
545          *
546          * @return 3-stellige Zahl
547          */
548         public static String pad3 (int number) {
549                 return  number < 10 ? "00" + number : number < 100 ? "0" + number : String.valueOf(number);
550         }
551
552         /**
553          * Konvertiert Unix-Linefeeds in Win-Linefeeds
554          * @param s
555          * @return Konvertierter String
556          */
557         public static String unixLineFeedsToWin(String s) {
558                 int i = -1;
559                 while (true) {
560                         i = s.indexOf('\n', i+1);
561                         if (i < 0) break;
562                         if ((i == 0 || s.charAt(i-1) != '\r') &&
563                                 (i == s.length()-1 || s.charAt(i+1) != '\r')) {
564                                 s = s.substring(0, i)+'\r'+s.substring(i);
565                                 i++;
566                         }
567                 }
568                 return s;
569         }
570
571
572         /**
573          * verwandelt einen String in eine gültige Url, konvertiert Sonderzeichen
574          * und Spaces werden zu Underscores
575          *
576          * @return gültige Url
577          */
578         public static String convert2url(String s) {
579                 s = toLowerCase(s);
580                 StringBuffer buf = new StringBuffer();
581                 for(int i = 0; i < s.length(); i++ ) {
582                                 switch( s.charAt( i ) ) {
583                                 case 'ö':
584                         buf.append( "oe" ); break;
585                                 case 'ä':
586                         buf.append( "ae" ); break;
587                                 case 'ü':
588                         buf.append( "ue" ); break;
589                                 case 'ã':
590                         buf.append( "a" ); break;
591                                 case '´':
592                                 case '.':
593                         buf.append( "_" ); break;
594                                 case ' ':
595                         if( buf.charAt( buf.length() - 1 ) != '_' ) {
596                                         buf.append( "_" );
597                         }
598                         break;
599                                 default:
600                         buf.append( s.charAt( i ) );
601                                 }
602                 }
603                 return buf.toString();
604         }
605
606
607         public static String decodeHTMLinTags(String s){
608                 StringBuffer buffer = new StringBuffer();
609                 boolean start = false;
610                 boolean stop = false;
611                 int startIndex = 0;
612                 int stopIndex = 0;
613                 int temp = 0;
614
615                 for(int i=0;i<s.length();i++){
616                         if(s.charAt(i)=='<'){
617                                 start = true;
618                                 startIndex = i;
619                         } else if(s.charAt(i)=='>'){
620                                 stop = true;
621                                 stopIndex = i;
622
623                                 if(start && stop){
624                                         buffer.append(s.substring(temp,startIndex));
625                                         buffer.append(replaceQuot(s.substring(startIndex,stopIndex+1)));
626                                         i= temp= stopIndex+1;
627                                         start= stop= false;
628                                 }
629                         }
630                 }
631                 if(stopIndex>0){
632                         buffer.append(s.substring(stopIndex+1));
633                         return buffer.toString();
634                 } else {
635                         return s;
636                 }
637         }
638
639         public static String replaceQuot(String s) {
640                 StringBuffer buffer = new StringBuffer();
641                 for(int j = 0; j < s.length();j++){
642                         if(s.charAt(j)=='&'){
643                                 if(s.indexOf( "&quot;",j) == j) {
644                                         buffer.append( "\"" );
645                                         j += 5;
646                                 }//if
647                         } else {
648                                 buffer.append(s.charAt(j));
649                         }//else
650                 }//for
651                 return buffer.toString();
652         }
653
654         /** wandelt Quotes in Sonderzeichen um
655          */
656         /**
657         public static String decodeHtml(String s) {
658                 StringBuffer buf = new StringBuffer();
659                 for(int i=0;i < s.length(); i++ ) {
660                         if( s.indexOf( "&ouml;", i ) == i ) {
661                                 buf.append( "ö" ); i += 5;
662                                 continue;
663                         }
664                         if( s.indexOf( "&auml;", i ) == i ) {
665                                 buf.append( "ä" ); i += 5;
666                                 continue;
667                         }
668                         if( s.indexOf( "&uuml;", i ) == i ) {
669                                 buf.append( "ü" ); i += 5;
670                                 continue;
671                         }
672                         if( s.indexOf( "&Ouml;", i ) == i ) {
673                                 buf.append( "Ö" ); i += 5;
674                                 continue;
675                         }
676                         if( s.indexOf( "&Auml;", i ) == i ) {
677                                 buf.append( "Ä" ); i += 5;
678                                 continue;
679                         }
680                         if( s.indexOf( "&Uuml;", i ) == i ) {
681                                 buf.append( "Ãœ" ); i += 5;
682                                 continue;
683                         }
684                         if( s.indexOf( "&szlig;", i ) == i ) {
685                                 buf.append( "ß" ); i += 6;
686                                 continue;
687                         }
688                         if( s.indexOf( "&quot;", i ) == i ) {
689                                 buf.append( "\"" ); i += 5;
690                                 continue;
691                         }
692                         buf.append( s.charAt(i) );
693                 }
694                 return buf.toString();
695         }
696          */
697
698         /**
699          * schnellere Variante der String.toLowerCase()-Routine
700          *
701          * @return String in Kleinbuchsten
702          */
703         public static String toLowerCase(String s) {
704                 int l = s.length();
705                 char[] a = new char[l];
706                 for (int i = 0; i < l; i++)
707                         a[i] = Character.toLowerCase(s.charAt(i));
708                 return new String(a);
709         }
710
711                 /**
712          * Findet <code>element</code> im String-Array <code>array</code>
713          * @param array
714          * @param element
715          * @return Fundstelle als int oder -1
716          */
717         public static int indexOf(String[] array, String element) {
718                 if (array != null)
719                         for (int i = 0; i < array.length; i++)
720                                 if (array[i].equals(element))
721                                         return i;
722                 return -1;
723         }
724
725         /**
726          * Testet auf Vorkommen von <code>element</code> in <code>array</code>
727          * @param array String-Array
728          * @param element
729          * @return true wenn <code>element</code> vorkommt, sonst false
730          */
731         public static boolean contains(String[] array, String element) {
732                 return indexOf(array, element) >= 0;
733         }
734
735                 /**
736          * Ermittelt CRC-Prüfsumme von String <code>s</code>
737          * @param s
738          * @return CRC-Prüfsumme
739          */
740         public static int getCRC(String s) {
741                 int h = 0;
742                 char val[] = s.toCharArray();
743                 int len = val.length;
744
745                 for (int i = 0 ; i < len; i++) {
746                         h &= 0x7fffffff;
747                         h = (((h >> 30) | (h << 1)) ^ (val[i]+i));
748                 }
749
750                 return (h << 8) | (len & 0xff);
751         }
752
753                 /**
754          * Liefert Default-Wert def zurück, wenn String <code>s</code>
755          * kein Integer ist.
756          *
757          * @param s
758          * @param def
759          * @return geparster int aus s oder def
760          */
761         public static int parseInt(String s, int def) {
762                 if (s == null) return def;
763                 try {
764                         return Integer.parseInt(s);
765                 } catch (NumberFormatException e) {
766                         return def;
767                 }
768         }
769
770         /**
771          * Liefert Defaultwert def zurück, wenn s nicht zu einem float geparsed werden kann.
772          * @param s
773          * @param def
774          * @return geparster float oder def
775          */
776         public static float parseFloat(String s, float def) {
777                 if (s == null) return def;
778                 try {
779                         return new Float(s).floatValue();
780                 } catch (NumberFormatException e) {
781                         return def;
782                 }
783         }
784
785                 /**
786          * Findet Ende eines Satzes in String <code>text</code>
787          * @param text
788          * @param startIndex
789          * @return index des Satzendes, oder -1
790          */
791         public static int findEndOfSentence(String text, int startIndex) {
792                  while (true) {
793                          int i = text.indexOf('.', startIndex);
794                          if (i < 0) return -1;
795                          if (i > 0 && !Character.isDigit(text.charAt(i-1)) &&
796                                         (i+1 >= text.length()
797                                         || text.charAt(i+1) == ' '
798                                         || text.charAt(i+1) == '\n'
799                                         || text.charAt(i+1) == '\t'))
800                                         return i+1;
801                          startIndex = i+1;
802                  }
803         }
804
805                 /**
806          * Findet Wortende in String <code>text</code> ab <code>startIndex</code>
807          * @param text
808          * @param startIndex
809          * @return Index des Wortendes, oder -1
810          */
811         public static int findEndOfWord(String text, int startIndex) {
812                 int i = text.indexOf(' ', startIndex),
813                         j = text.indexOf('\n', startIndex);
814                 if (i < 0) i = text.length();
815                 if (j < 0) j = text.length();
816                 return Math.min(i, j);
817         }
818
819
820         /**
821          *  convertNewline2P ist eine regex-routine zum umwandeln von 2 oder mehr newlines (\n)
822          *  in den html-tag <p>
823          *  nur sinnvoll, wenn text nicht im html-format eingegeben
824          */
825         public static String convertNewline2P(String haystack) {
826                         return re_brbr2p.substituteAll(haystack,"\n</p><p>");
827         }
828
829         /**
830          *  convertNewline2Break ist eine regex-routine zum umwandeln von 1 newline (\n)
831          *  in den html-tag <br>
832          *  nur sinnvoll, wenn text nicht im html-format eingegeben
833          */
834         public static String convertNewline2Break(String haystack) {
835                 return re_newline2br.substituteAll(haystack,"$0<br />");
836         }
837
838         /**
839          *  createMailLinks wandelt text im email-adressenformat
840          *  in einen klickbaren link um
841          *  nur sinnvoll, wenn text nicht im html-format eingegeben
842          */
843         public static String createMailLinks(String haystack) {
844                         return re_mail.substituteAll(haystack,"<a href=\"mailto:$0\">$0</a>");
845         }
846
847
848         /**
849          *  createMailLinks wandelt text im email-adressenformat
850          *  in einen klickbaren link um
851          *  nur sinnvoll, wenn text nicht im html-format eingegeben
852          */
853         public static String createMailLinks(String haystack, String imageRoot, String mailImage) {
854                 return re_mail.substituteAll(haystack,"<img src=\""+imageRoot+"/"+mailImage+"\" border=\"0\"/>&#160;<a href=\"mailto:$0\">$0</a>");
855         }
856
857
858         /**
859          *  createURLLinks wandelt text im url-format
860          *  in einen klickbaren link um
861          *  nur sinnvoll, wenn text nicht im html-format eingegeben
862          */
863         public static String createURLLinks(String haystack) {
864                 return re_url.substituteAll(haystack,"<a href=\"$0\">$0</a>");
865         }
866
867         /**
868          * this routine takes text in url format and makes
869          * a clickaeble "<href>" link removing any "illegal" html tags
870          * @param haystack, the url
871          * @param title, the href link text
872          * @param imagRoot, the place to find icons
873          * @param extImage, the url of the icon to show next to the link
874          * @return a String containing the url
875          */
876         public static String createURLLinks(String haystack, String title, String imageRoot,String extImage) {
877                 if (title == null) {
878                         return re_url.substituteAll(haystack,"<img src=\""+imageRoot+"/"+extImage+"\" border=\"0\"/>&#160;<a href=\"$0\">$0</a>");
879                 } else {
880                         title = removeHTMLTags(title);
881                         return re_url.substituteAll(haystack,"<img src=\""+imageRoot+"/"+extImage+"\" border=\"0\"/>&#160;<a href=\"$0\">"+title+"</a>");
882                 }
883         }
884
885         /**
886          * this routine takes text in url format and makes
887          * a clickaeble "<href>" link removing any "illegal" html tags
888          * @param haystack, the url
889          * @param imageRoot, the place to find icons
890          * @param extImage, the url of the icon to show next to the link
891          * @param intImage, unused
892          * @return a String containing the url
893          */
894         public static String createURLLinks(String haystack, String title, String imageRoot,String extImage,String intImage) {
895                 return createURLLinks(haystack, title, imageRoot, extImage);
896         }
897
898          /**
899          *  deleteForbiddenTags
900          *  this method deletes all <script>, <body> and <head>-tags
901          */
902         public static final String deleteForbiddenTags(String haystack) {
903                 try {
904                         RE regex = new RE("<[ \t\r\n](.*?)script(.*?)/script(.*?)>",RE.REG_ICASE);
905                         haystack = regex.substituteAll(haystack,"");
906                         regex = new RE("<head>(.*?)</head>");
907                         haystack = regex.substituteAll(haystack,"");
908                         regex = new RE("<[ \t\r\n/]*body(.*?)>");
909                         haystack = regex.substituteAll(haystack,"");
910                         return haystack;
911                 } catch(REException ex){
912                         return null;
913                 }
914         }
915
916         /**
917          * this method deletes all html tags
918          */
919         public static final String removeHTMLTags(String haystack){
920                         return re_tags.substituteAll(haystack,"");
921         }
922
923
924         /**
925          * this method deletes all but the approved tags html tags
926          * it also deletes approved tags which contain malicious-looking attributes and doesn't work at all
927          */
928         public static String approveHTMLTags(String haystack){
929                 try {
930                         String approvedTags="a|img|h1|h2|h3|h4|h5|h6|br|b|i|strong|p";
931                         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";
932                         String approvedProtocols="rtsp|http|ftp|https|freenet|mailto";
933
934                         // kill all the bad tags that have attributes
935                         String s = "<\\s*/?\\s*(?!(("+approvedTags+")\\s))\\w+\\s[^>]*>";
936                         RE regex = new RE(s,RE.REG_ICASE);
937                         haystack = regex.substituteAll(haystack,"");
938
939                         // kill all the bad tags that are attributeless
940                         regex = new RE("<\\s*/?\\s*(?!(("+approvedTags+")\\s*>))\\w+\\s*>",RE.REG_ICASE);
941                         haystack = regex.substituteAll(haystack,"");
942
943                         // kill all the tags which have a javascript attribute like onLoad
944                         regex = new RE("<[^>]*("+badAttributes+")[^>]*>",RE.REG_ICASE);
945                         haystack = regex.substituteAll(haystack,"");
946
947                         // kill all the tags which include a url to an unacceptable protocol
948                         regex = new RE("<\\s*a\\s+[^>]*href=(?!(\'|\")?("+approvedProtocols+"))[^>]*>",RE.REG_ICASE);
949                         haystack = regex.substituteAll(haystack,"");
950
951                         return haystack;
952                 } catch(REException ex){
953                         ex.printStackTrace();
954                         return null;
955                 }
956         }
957
958
959         /**
960          *  createHTML ruft alle regex-methoden zum unwandeln eines nicht
961          *  htmlcodierten string auf und returnt einen htmlcodierten String
962          */
963         public static String createHTML(String content){
964                 content=convertNewline2Break(content);
965                 content=convertNewline2P(content);
966                 content=createMailLinks(content);
967                 content=createURLLinks(content);
968                 return content;
969         }
970
971
972         /**
973          *  createHTML ruft alle regex-methoden zum unwandeln eines nicht
974          *  htmlcodierten string auf und returnt einen htmlcodierten String
975          */
976         public static String createHTML(String content,String producerDocRoot,String mailImage,String extImage,String intImage){
977                 content=convertNewline2Break(content);
978                 content=convertNewline2P(content);
979                 content=createMailLinks(content,producerDocRoot,mailImage);
980                 content=createURLLinks(content,null,producerDocRoot,extImage,intImage);
981                 return content;
982         }
983
984 }
985