2 * Copyright (C) 2001, 2002 The Mir-coders group
4 * This file is part of Mir.
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.
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.
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
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.
37 import java.text.NumberFormat;
41 * Statische Hilfsmethoden zur Stringbehandlung
43 * @version $Id: StringUtil.java,v 1.29 2002/12/02 12:33:23 zapata Exp $
44 * @author mir-coders group
47 public final class StringUtil {
49 private static RE re_newline2br, re_brbr2p, re_mail, re_url, re_tags;
51 private StringUtil() { } // this avoids contruction
56 re_newline2br = new RE("(\r?\n){1}");
57 re_brbr2p = new RE("(<br>\r?\n<br>){1,}");
58 re_mail = new RE("([a-zA-Z0-9_.-]+)@([a-zA-Z0-9_-]+)\\.([a-zA-Z0-9_.-]+)");
59 re_url = new RE("((https://)|(http://)|(ftp://)){1}([a-zA-Z0-9_-]+).([a-zA-Z0-9_.:-]+)/?([^ \t\r\n<>\\)\\]]+[^ \t\r\n.,<>\\)\\]])");
60 re_tags = new RE("<[^>]*>",RE.REG_ICASE);
62 catch (REException e){
63 System.err.println("FATAL: StringUtil: could not precompile REGEX: "+e.toString());
68 * Formats a number with the specified minimum and maximum number of digits.
70 public static synchronized String zeroPaddingNumber(long value, int minDigits,
73 NumberFormat numberFormat = NumberFormat.getInstance();
74 numberFormat.setMinimumIntegerDigits(minDigits);
75 numberFormat.setMaximumIntegerDigits(maxDigits);
76 return numberFormat.format(value);
80 * Wandelt Datum in einen 8-ziffrigen String um (yyyymmdd)
82 * @return 8-ziffriger String (yyyymmdd)
85 public static final String date2webdbDate (GregorianCalendar theDate) {
86 StringBuffer webdbDate = new StringBuffer();
87 webdbDate.append(String.valueOf(theDate.get(Calendar.YEAR)));
88 webdbDate.append(pad2(theDate.get(Calendar.MONTH) + 1));
89 webdbDate.append(pad2(theDate.get(Calendar.DATE)));
90 return webdbDate.toString();
94 * Wandelt Calendar in einen 12-ziffrigen String um (yyyymmddhhmm)
96 * @return 12-ziffriger String (yyyymmdd)
99 public static final String date2webdbDateTime (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 webdbDate.append(pad2(theDate.get(Calendar.HOUR)));
105 webdbDate.append(pad2(theDate.get(Calendar.MINUTE)));
106 return webdbDate.toString();
110 * Return a http://www.w3.org/TR/NOTE-datetime formatted date (yyyy-mm-ddThh:mm:ssTZ)
112 * @return w3approved datetime
115 public static final String date2w3DateTime (GregorianCalendar theDate) {
116 StringBuffer webdbDate = new StringBuffer();
117 webdbDate.append(String.valueOf(theDate.get(Calendar.YEAR)));
118 webdbDate.append("-");
119 webdbDate.append(pad2(theDate.get(Calendar.MONTH) + 1));
120 webdbDate.append("-");
121 webdbDate.append(pad2(theDate.get(Calendar.DATE)));
122 webdbDate.append("T");
123 webdbDate.append(pad2(theDate.get(Calendar.HOUR)));
124 webdbDate.append(":");
125 webdbDate.append(pad2(theDate.get(Calendar.MINUTE)));
126 webdbDate.append(":");
127 webdbDate.append(pad2(theDate.get(Calendar.SECOND)));
128 //assumes you are an hour-multiple away from UTC....
129 int offset=(theDate.get(Calendar.ZONE_OFFSET)/(60*60*1000));
131 webdbDate.append("-");
134 webdbDate.append("+");
136 webdbDate.append(pad2(Math.abs(offset)));
137 webdbDate.append(":00");
138 return webdbDate.toString();
142 * wandelt Calendar in dd.mm.yyyy / hh.mm um
144 * @return String mit (dd.mm.yyyy / hh.mm um)
146 public static String date2readableDateTime (GregorianCalendar theDate) {
147 String readable = "";
149 readable += pad2(theDate.get(Calendar.DATE));
150 readable += "." + pad2(theDate.get(Calendar.MONTH) + 1);
151 readable += "." + String.valueOf(theDate.get(Calendar.YEAR));
152 hour = theDate.get(Calendar.HOUR);
153 if (theDate.get(Calendar.AM_PM) == Calendar.PM)
155 readable += " / " + pad2(hour);
156 readable += ":" + pad2(theDate.get(Calendar.MINUTE));
161 * deleteForbiddenTags
162 * this method deletes all <script>, <body> and <head>-tags
164 public static final String deleteForbiddenTags(String haystack) {
166 RE regex = new RE("<[ \t\r\n](.*?)script(.*?)/script(.*?)>",RE.REG_ICASE);
167 haystack = regex.substituteAll(haystack,"");
168 regex = new RE("<head>(.*?)</head>");
169 haystack = regex.substituteAll(haystack,"");
170 regex = new RE("<[ \t\r\n/]*body(.*?)>");
171 haystack = regex.substituteAll(haystack,"");
173 } catch(REException ex){
179 * wandelt eine Datum in einen 8-buchstabigen String, der durch <code>/</code>
183 * @return String mit <code>/yyyy/mm/dd</code>
185 public static final String webdbDate2path (String webdbDate) {
186 StringBuffer path = new StringBuffer();
187 path.append("/").append(webdbDate.substring(0, 4));
188 path.append("/").append(webdbDate.substring(4, 6));
191 //path.append("/").append(webdbDate.substring(6, 8));
192 return path.toString();
196 * converts string from format: yyyy-mm-dd__hh:mm:ss.d
197 * to dd.mm.yyyy hh:mm
199 public static String dateToReadableDate(String date) {
200 StringBuffer returnDate = new StringBuffer();
203 returnDate.append(date.substring(8,10)).append('.');
204 returnDate.append(date.substring(5,7)).append('.');
205 returnDate.append(date.substring(0,4)).append(' ');
206 returnDate.append(date.substring(11,16));
208 return returnDate.toString();
212 * converts string from format: yyyy-mm-dd__hh:mm:ss.d
215 public static String dateToYear (String date) {
216 StringBuffer returnDate = new StringBuffer();
219 returnDate.append(date.substring(0,4));
221 return returnDate.toString();
225 * converts string from format: yyyy-mm-dd__hh:mm:ss.d
228 public static String dateToMonth (String date) {
229 StringBuffer returnDate = new StringBuffer();
231 if (!date.substring(5,6).equalsIgnoreCase("0")) returnDate.append(date.substring(5,7));
232 else returnDate.append(date.substring(6,7));
234 return returnDate.toString();
238 * converts string from format: yyyy-mm-dd__hh:mm:ss.d
241 public static String dateToDayOfMonth (String date) {
242 StringBuffer returnDate = new StringBuffer();
244 if (!date.substring(8,9).equalsIgnoreCase("0")) returnDate.append(date.substring(8,10));
245 else returnDate.append(date.substring(9,10));
247 return returnDate.toString();
251 * converts string from format: yyyy-mm-dd__hh:mm:ss.d
254 public static String dateToTime (String date) {
255 StringBuffer returnDate = new StringBuffer();
257 returnDate.append(date.substring(11,16));
259 return returnDate.toString();
263 * Splits the provided CSV text into a list. stolen wholesale from
264 * from Jakarta Turbine StrinUtils.java -mh
266 * @param text The CSV list of values to split apart.
267 * @param separator The separator character.
268 * @return The list of values.
270 public static String[] split(String text, String separator)
272 StringTokenizer st = new StringTokenizer(text, separator);
273 String[] values = new String[st.countTokens()];
275 while (st.hasMoreTokens())
277 values[pos++] = st.nextToken();
283 * Joins the elements of the provided array into a single string
284 * containing a list of CSV elements. Stolen wholesale from Jakarta
285 * Turbine StringUtils.java. -mh
287 * @param list The list of values to join together.
288 * @param separator The separator character.
289 * @return The CSV text.
291 public static String join(String[] list, String separator)
293 StringBuffer csv = new StringBuffer();
294 for (int i = 0; i < list.length; i++)
298 csv.append(separator);
302 return csv.toString();
307 * schließt einen String in Anführungsszeichen ein, falls er Leerzeichen o.ä. enthält
309 * @return gequoteter String
311 public static String quoteIfNecessary(String s) {
312 for (int i = 0; i < s.length(); i++)
313 if (!(Character.isLetterOrDigit(s.charAt(i)) || s.charAt(i) == '.'))
314 return quote(s, '"');
319 * schließt <code>s</code> in <code>'</code> ein und setzt Backslashes vor
320 * "gefährliche" Zeichen innerhalb des Strings
321 * Quotes special SQL-characters in <code>s</code>
323 * @return geqoteter String
325 public static String quote(String s)
327 //String s2 = quote(s, '\'');
328 //Quickhack ÊÊ Ê Ê Ê Ê Ê Ê
329 //Because of '?-Bug in Postgresql-JDBC-Driver
330 StringBuffer temp = new StringBuffer();
331 for(int i=0;i<s.length();i++){
332 if(s.charAt(i)=='\''){
333 temp.append("'");
335 temp.append(s.charAt(i));
338 String s2 = temp.toString();
341 s2 = quote(s2, '\"');
346 * schließt <code>s</code> in <code>'</code> ein und setzt Backslashes vor
347 * "gefährliche" Zeichen innerhalb des Strings
349 * @param s String, der gequoted werden soll
350 * @param quoteChar zu quotendes Zeichen
351 * @return gequoteter String
353 public static String quote(String s, char quoteChar)
355 StringBuffer buf = new StringBuffer(s.length());
357 while (pos < s.length()) {
358 int i = s.indexOf(quoteChar, pos);
359 if (i < 0) i = s.length();
360 buf.append(s.substring(pos, i));
362 if (pos < s.length()) {
364 buf.append(quoteChar);
368 return buf.toString();
372 * replaces dangerous characters in <code>s</code>
376 public static String unquote(String s)
379 StringBuffer buf = new StringBuffer(s.length());
381 String searchString = "\\"+quoteChar;
382 while (pos < s.length()) {
383 int i = s.indexOf(searchString, pos);
384 if (i < 0) i = s.length();
385 buf.append(s.substring(pos, i));
388 return buf.toString();
392 * Wandelet String in byte[] um.
394 * @return byte[] des String
397 public static byte[] stringToBytes(String s) {
398 String crlf = System.getProperty("line.separator");
399 if (!crlf.equals("\n"))
400 s = replace(s, "\n", crlf);
401 // byte[] buf = new byte[s.length()];
402 byte[] buf = s.getBytes();
407 * Ersetzt in String <code>s</code> das <code>pattern</code> durch <code>substitute</code>
411 * @return String mit den Ersetzungen
413 public static String replace(String s, String pattern, String substitute) {
414 int i = 0, pLen = pattern.length(), sLen = substitute.length();
415 StringBuffer buf = new StringBuffer(s.length());
417 int j = s.indexOf(pattern, i);
419 buf.append(s.substring(i));
422 buf.append(s.substring(i, j));
423 buf.append(substitute);
427 return buf.toString();
431 * Ersetzt in String <code>s</code> das Regexp <code>pattern</code> durch <code>substitute</code>
435 * @return String mit den Ersetzungen
437 public static String regexpReplace(String haystack, String pattern, String substitute) {
439 RE regex = new RE(pattern);
440 return regex.substituteAll(haystack,substitute);
441 } catch(REException ex){
450 * Fügt einen Separator an den Pfad an
452 * @return Pfad mit Separator am Ende
454 public static final String addSeparator (String path) {
455 return path.length() == 0 || path.endsWith(File.separator) ? path : path
456 + File.separatorChar;
460 * Fügt ein <code>/</code> ans ende des Strings and
462 * @return Pfad mit <code>/</code> am Ende
464 public static final String addSlash (String path) {
465 return path.length() == 0 || path.endsWith("/") ? path : path + '/';
469 * Löscht <code>/</code> am Ende des Strings, falls vorhanden
471 * @return String ohne <code>/</code> am Ende
473 public static final String removeSlash (String path) {
474 return path.length() > 1 && path.endsWith("/") ? path.substring(0, path.length()
479 * Checks to see if the path is absolute by looking for a leading file
484 public static boolean isAbsolutePath (String path) {
485 return path.startsWith(File.separator);
489 * Löscht Slash am Anfang des Strings
493 public static String removeFirstSlash (String path) {
494 return path.startsWith("/") ? path.substring(1) : path;
498 * formatiert eine Zahl (0-99) zweistellig (z.B. 5 -> 05)
499 * @return zwistellige Zahl
501 public static String pad2 (int number) {
502 return number < 10 ? "0" + number : String.valueOf(number);
506 * formatiert eine Zahl (0-999) dreistellig (z.B. 7 -> 007)
508 * @return 3-stellige Zahl
510 public static String pad3 (int number) {
511 return number < 10 ? "00" + number : number < 100 ? "0" + number : String.valueOf(number);
515 * Konvertiert Unix-Linefeeds in Win-Linefeeds
517 * @return Konvertierter String
519 public static String unixLineFeedsToWin(String s) {
522 i = s.indexOf('\n', i+1);
524 if ((i == 0 || s.charAt(i-1) != '\r') &&
525 (i == s.length()-1 || s.charAt(i+1) != '\r')) {
526 s = s.substring(0, i)+'\r'+s.substring(i);
533 public static String replaceQuot(String s) {
534 StringBuffer buffer = new StringBuffer();
535 for(int j = 0; j < s.length();j++){
536 if(s.charAt(j)=='&'){
537 if(s.indexOf( """,j) == j) {
538 buffer.append( "\"" );
542 buffer.append(s.charAt(j));
545 return buffer.toString();
549 * schnellere Variante der String.toLowerCase()-Routine
551 * @return String in Kleinbuchsten
553 public static String toLowerCase(String s) {
555 char[] a = new char[l];
556 for (int i = 0; i < l; i++)
557 a[i] = Character.toLowerCase(s.charAt(i));
558 return new String(a);
562 * Findet <code>element</code> im String-Array <code>array</code>
565 * @return Fundstelle als int oder -1
567 public static int indexOf(String[] array, String element) {
569 for (int i = 0; i < array.length; i++)
570 if (array[i].equals(element))
576 * Testet auf Vorkommen von <code>element</code> in <code>array</code>
577 * @param array String-Array
579 * @return true wenn <code>element</code> vorkommt, sonst false
581 public static boolean contains(String[] array, String element) {
582 return indexOf(array, element) >= 0;
586 * Ermittelt CRC-Prüfsumme von String <code>s</code>
588 * @return CRC-Prüfsumme
590 public static int getCRC(String s) {
592 char val[] = s.toCharArray();
593 int len = val.length;
595 for (int i = 0 ; i < len; i++) {
597 h = (((h >> 30) | (h << 1)) ^ (val[i]+i));
600 return (h << 8) | (len & 0xff);
604 * Liefert Default-Wert def zurück, wenn String <code>s</code>
609 * @return geparster int aus s oder def
611 public static int parseInt(String s, int def) {
612 if (s == null) return def;
614 return Integer.parseInt(s);
615 } catch (NumberFormatException e) {
621 * Liefert Defaultwert def zurück, wenn s nicht zu einem float geparsed werden kann.
624 * @return geparster float oder def
626 public static float parseFloat(String s, float def) {
627 if (s == null) return def;
629 return new Float(s).floatValue();
630 } catch (NumberFormatException e) {
636 * Findet Ende eines Satzes in String <code>text</code>
639 * @return index des Satzendes, oder -1
641 public static int findEndOfSentence(String text, int startIndex) {
643 int i = text.indexOf('.', startIndex);
644 if (i < 0) return -1;
645 if (i > 0 && !Character.isDigit(text.charAt(i-1)) &&
646 (i+1 >= text.length()
647 || text.charAt(i+1) == ' '
648 || text.charAt(i+1) == '\n'
649 || text.charAt(i+1) == '\t'))
656 * Findet Wortende in String <code>text</code> ab <code>startIndex</code>
659 * @return Index des Wortendes, oder -1
661 public static int findEndOfWord(String text, int startIndex) {
662 int i = text.indexOf(' ', startIndex),
663 j = text.indexOf('\n', startIndex);
664 if (i < 0) i = text.length();
665 if (j < 0) j = text.length();
666 return Math.min(i, j);
671 * convertNewline2P ist eine regex-routine zum umwandeln von 2 oder mehr newlines (\n)
672 * in den html-tag <p>
673 * nur sinnvoll, wenn text nicht im html-format eingegeben
675 public static String convertNewline2P(String haystack) {
676 return re_brbr2p.substituteAll(haystack,"\n</p><p>");
680 * convertNewline2Break ist eine regex-routine zum umwandeln von 1 newline (\n)
681 * in den html-tag <br>
682 * nur sinnvoll, wenn text nicht im html-format eingegeben
684 public static String convertNewline2Break(String haystack) {
685 return re_newline2br.substituteAll(haystack,"$0<br />");
689 * createMailLinks wandelt text im email-adressenformat
690 * in einen klickbaren link um
691 * nur sinnvoll, wenn text nicht im html-format eingegeben
693 public static String createMailLinks(String haystack) {
694 return re_mail.substituteAll(haystack,"<a href=\"mailto:$0\">$0</a>");
699 * createMailLinks wandelt text im email-adressenformat
700 * in einen klickbaren link um
701 * nur sinnvoll, wenn text nicht im html-format eingegeben
703 public static String createMailLinks(String haystack, String imageRoot, String mailImage) {
704 return re_mail.substituteAll(haystack,"<img src=\""+imageRoot+"/"+mailImage+"\" border=\"0\"/> <a href=\"mailto:$0\">$0</a>");
709 * createURLLinks wandelt text im url-format
710 * in einen klickbaren link um
711 * nur sinnvoll, wenn text nicht im html-format eingegeben
713 public static String createURLLinks(String haystack) {
714 return re_url.substituteAll(haystack,"<a href=\"$0\">$0</a>");
718 * this routine takes text in url format and makes
719 * a clickaeble "<href>" link removing any "illegal" html tags
720 * @param haystack, the url
721 * @param title, the href link text
722 * @param imagRoot, the place to find icons
723 * @param extImage, the url of the icon to show next to the link
724 * @return a String containing the url
726 public static String createURLLinks(String haystack, String title, String imageRoot,String extImage) {
728 return re_url.substituteAll(haystack,"<img src=\""+imageRoot+"/"+extImage+"\" border=\"0\"/> <a href=\"$0\">$0</a>");
730 title = removeHTMLTags(title);
731 return re_url.substituteAll(haystack,"<img src=\""+imageRoot+"/"+extImage+"\" border=\"0\"/> <a href=\"$0\">"+title+"</a>");
736 * this routine takes text in url format and makes
737 * a clickaeble "<href>" link removing any "illegal" html tags
738 * @param haystack, the url
739 * @param imageRoot, the place to find icons
740 * @param extImage, the url of the icon to show next to the link
741 * @param intImage, unused
742 * @return a String containing the url
744 public static String createURLLinks(String haystack, String title, String imageRoot,String extImage,String intImage) {
745 return createURLLinks(haystack, title, imageRoot, extImage);
749 * this method deletes all html tags
751 public static final String removeHTMLTags(String haystack){
752 return re_tags.substituteAll(haystack,"");
756 * this method deletes all but the approved tags html tags
757 * it also deletes approved tags which contain malicious-looking attributes and doesn't work at all
759 public static String approveHTMLTags(String haystack){
761 String approvedTags="a|img|h1|h2|h3|h4|h5|h6|br|b|i|strong|p";
762 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";
763 String approvedProtocols="rtsp|http|ftp|https|freenet|mailto";
765 // kill all the bad tags that have attributes
766 String s = "<\\s*/?\\s*(?!(("+approvedTags+")\\s))\\w+\\s[^>]*>";
767 RE regex = new RE(s,RE.REG_ICASE);
768 haystack = regex.substituteAll(haystack,"");
770 // kill all the bad tags that are attributeless
771 regex = new RE("<\\s*/?\\s*(?!(("+approvedTags+")\\s*>))\\w+\\s*>",RE.REG_ICASE);
772 haystack = regex.substituteAll(haystack,"");
774 // kill all the tags which have a javascript attribute like onLoad
775 regex = new RE("<[^>]*("+badAttributes+")[^>]*>",RE.REG_ICASE);
776 haystack = regex.substituteAll(haystack,"");
778 // kill all the tags which include a url to an unacceptable protocol
779 regex = new RE("<\\s*a\\s+[^>]*href=(?!(\'|\")?("+approvedProtocols+"))[^>]*>",RE.REG_ICASE);
780 haystack = regex.substituteAll(haystack,"");
783 } catch(REException ex){
784 ex.printStackTrace();
791 * createHTML ruft alle regex-methoden zum unwandeln eines nicht
792 * htmlcodierten string auf und returnt einen htmlcodierten String
794 public static String createHTML(String content){
795 content=convertNewline2Break(content);
796 content=convertNewline2P(content);
797 content=createMailLinks(content);
798 content=createURLLinks(content);
804 * createHTML ruft alle regex-methoden zum unwandeln eines nicht
805 * htmlcodierten string auf und returnt einen htmlcodierten String
807 public static String createHTML(String content,String producerDocRoot,String mailImage,String extImage,String intImage){
808 content=convertNewline2Break(content);
809 content=convertNewline2P(content);
810 content=createMailLinks(content,producerDocRoot,mailImage);
811 content=createURLLinks(content,null,producerDocRoot,extImage,intImage);