comparison backend/src/main/java/org/dive4elements/river/backend/utils/StringUtil.java @ 8187:3bb1c62ad732

Moved package org.dive4elements.river.utils to org.dive4elements.river.backend.utils.
author Sascha L. Teichmann <teichmann@intevation.de>
date Thu, 04 Sep 2014 15:03:25 +0200
parents backend/src/main/java/org/dive4elements/river/utils/StringUtil.java@4c3ccf2b0304
children d7c005e12af0
comparison
equal deleted inserted replaced
8186:a1ceacf15d3a 8187:3bb1c62ad732
1 /* Copyright (C) 2011, 2012, 2013 by Bundesanstalt für Gewässerkunde
2 * Software engineering by Intevation GmbH
3 *
4 * This file is Free Software under the GNU AGPL (>=v3)
5 * and comes with ABSOLUTELY NO WARRANTY! Check out the
6 * documentation coming with Dive4Elements River for details.
7 */
8
9 package org.dive4elements.river.backend.utils;
10
11 import java.util.Arrays;
12 import java.util.ArrayList;
13 import java.util.Locale;
14
15 import java.net.URLEncoder;
16 import java.net.URLDecoder;
17
18 import java.io.UnsupportedEncodingException;
19 import java.io.IOException;
20 import java.io.BufferedReader;
21 import java.io.StringReader;
22 import java.io.StringWriter;
23 import java.io.PrintWriter;
24
25
26 public final class StringUtil {
27 final static String NUMBER_SEPERATOR = ";";
28 final static String LINE_SEPERATOR = ":";
29
30 private StringUtil() {
31 }
32
33 public static final String double2DArrayToString(double[][] values) {
34
35 if (values == null) {
36 throw new IllegalArgumentException("keine double[][]-Werte");
37 }
38
39 StringBuilder strbuf = new StringBuilder();
40
41 for (int i=0; i < values.length; i++) {
42 if (i>0) {
43 strbuf.append(LINE_SEPERATOR);
44 }
45 for (int j=0; j < values[i].length; j++) {
46 if (j > 0) {
47 strbuf.append(NUMBER_SEPERATOR);
48 }
49 strbuf.append(values[i][j]);
50 }
51 }
52
53 return strbuf.toString();
54 }
55
56 public static final double[][] stringToDouble2DArray(String str) {
57 if (str == null || str.length() == 0) {
58 return null;
59 }
60
61 String[] lineSplit = str.split(LINE_SEPERATOR);
62 double[][] array2D = new double[lineSplit.length][];
63 for (int i=0; i < lineSplit.length; i++) {
64 String[] numberSplit = lineSplit[i].split(NUMBER_SEPERATOR);
65
66 double[] numbers = new double[numberSplit.length];
67 for (int j=0; j < numberSplit.length; j++) {
68 numbers[j] = Double.valueOf(numberSplit[j]).doubleValue();
69 }
70
71 array2D[i] = numbers;
72 }
73
74 return array2D;
75 }
76
77 /**
78 * Remove first occurrence of "[" and "]" (if both do occur).
79 * @param value String to be stripped of [] (might be null).
80 * @return input string but with [ and ] removed, or input string if no
81 * brackets were found.
82 */
83 public static final String unbracket(String value) {
84 // null- guard
85 if (value == null) return value;
86
87 int start = value.indexOf("[");
88 int end = value.indexOf("]");
89
90 if (start < 0 || end < 0) {
91 return value;
92 }
93
94 value = value.substring(start + 1, end);
95
96 return value;
97 }
98
99
100 /**
101 * From "Q=1" make "W(Q=1)".
102 * @return original string wraped in "W()" if it contains a "Q", original
103 * string otherwise.
104 */
105 public static String wWrap(String wOrQ) {
106 return (wOrQ != null && wOrQ.indexOf("Q") >=0)
107 ? "W(" + wOrQ + ")"
108 : wOrQ;
109 }
110
111
112 public static final String [] splitLines(String s) {
113 if (s == null) {
114 return null;
115 }
116 ArrayList<String> list = new ArrayList<String>();
117
118 BufferedReader in = null;
119
120 try {
121 in =
122 new BufferedReader(
123 new StringReader(s));
124
125 String line;
126
127 while ((line = in.readLine()) != null) {
128 list.add(line);
129 }
130 }
131 catch (IOException ioe) {
132 return null;
133 }
134 finally {
135 if (in != null)
136 try {
137 in.close();
138 }
139 catch (IOException ioe) {}
140 }
141
142 return list.toArray(new String[list.size()]);
143 }
144
145 public static final String concat(String [] s) {
146 return concat(s, null);
147 }
148
149 public static final String concat(String [] s, String glue) {
150 if (s == null) {
151 return null;
152 }
153 StringBuilder sb = new StringBuilder();
154 for (int i = 0; i < s.length; ++i) {
155 if (i > 0 && glue != null) {
156 sb.append(glue);
157 }
158 sb.append(s[i]);
159 }
160 return sb.toString();
161 }
162
163 public static final String [] splitAfter(String [] src, int N) {
164 if (src == null) {
165 return null;
166 }
167
168 ArrayList<String> list = new ArrayList<String>(src.length);
169 for (int i = 0; i < src.length; ++i) {
170 String s = src[i];
171 int R;
172 if (s == null || (R = s.length()) == 0) {
173 list.add(s);
174 }
175 else {
176 while (R > N) {
177 list.add(s.substring(0, N));
178 s = s.substring(N);
179 R = s.length();
180 }
181 list.add(s);
182 }
183 }
184 return list.toArray(new String[list.size()]);
185 }
186
187 public static final String [] splitQuoted(String s) {
188 return splitQuoted(s, '"');
189 }
190
191 public static final String[] fitArray(String [] src, String [] dst) {
192 if (src == null) {
193 return dst;
194 }
195 if (dst == null) {
196 return src;
197 }
198
199 if (src.length == dst.length) {
200 return src;
201 }
202
203 System.arraycopy(src, 0, dst, 0, Math.min(dst.length, src.length));
204
205 return dst;
206 }
207
208 public static final String [] splitQuoted(String s, char quoteChar) {
209 if (s == null) {
210 return null;
211 }
212 ArrayList<String> l = new ArrayList<String>();
213 int mode = 0, last_mode = 0;
214 StringBuilder sb = new StringBuilder();
215 for (int N = s.length(), i = 0; i < N; ++i) {
216 char c = s.charAt(i);
217 switch (mode) {
218 case 0: // unquoted mode
219 if (c == quoteChar) {
220 mode = 1; // to quoted mode
221 if (sb.length() > 0) {
222 l.add(sb.toString());
223 sb.setLength(0);
224 }
225 }
226 else if (c == '\\') {
227 last_mode = 0;
228 mode = 2; // escape mode
229 }
230 else if (!Character.isWhitespace(c)) {
231 sb.append(c);
232 }
233 else if (sb.length() > 0) {
234 l.add(sb.toString());
235 sb.setLength(0);
236 }
237 break;
238 case 1: // quote mode
239 if (c == '\\') {
240 last_mode = 1;
241 mode = 2; // escape mode
242 }
243 else if (c == quoteChar) { // leave quote mode
244 l.add(sb.toString());
245 sb.setLength(0);
246 mode = 0; // to unquoted mode
247 }
248 else {
249 sb.append(c);
250 }
251 break;
252 case 2: // escape mode
253 sb.append(c);
254 mode = last_mode;
255 break;
256 }
257 }
258 if (sb.length() > 0) {
259 l.add(sb.toString());
260 }
261 return l.toArray(new String[l.size()]);
262 }
263
264 public static final String [] splitUnique(String s) {
265 return splitUnique(s, "[\\s,]+");
266 }
267
268 public static final String [] splitUnique(String s, String sep) {
269 return s != null ? unique(s.split(sep)) : null;
270 }
271
272 public static final String [] unique(String [] str) {
273 if (str == null || str.length == 1) {
274 return str;
275 }
276
277 Arrays.sort(str);
278
279 for (int i = 1; i < str.length; ++i)
280 if (str[i].equals(str[i-1])) {
281 ArrayList<String> list = new ArrayList<String>(str.length);
282
283 for (int j = 0; j < i; ++j) {
284 list.add(str[j]);
285 }
286
287 String last = str[i];
288
289 for (++i; i < str.length; ++i)
290 if (!last.equals(str[i])) {
291 list.add(last = str[i]);
292 }
293
294 return list.toArray(new String[list.size()]);
295 }
296
297 return str;
298 }
299
300 public static final String [] ensureEmptyExistence(String [] str) {
301 if (str == null) {
302 return null;
303 }
304
305 for (int i = 0; i < str.length; ++i)
306 if (str[i].length() == 0) {
307 if (i != 0) { // copy to front
308 String t = str[0];
309 str[0] = str[i];
310 str[i] = t;
311 }
312 return str;
313 }
314
315 String [] n = new String[str.length+1];
316 n[0] = "";
317 System.arraycopy(str, 0, n, 1, str.length);
318 return n;
319 }
320
321 public static final String ensureWidthPadLeft(String s, int width, char pad) {
322 int N = s.length();
323 if (N >= width) {
324 return s;
325 }
326 StringBuilder sb = new StringBuilder(width);
327 for (; N < width; ++N) {
328 sb.append(pad);
329 }
330 sb.append(s);
331 return sb.toString();
332 }
333
334 public static final String [] splitWhiteSpaceWithNAsPad(
335 String s,
336 int N,
337 String pad
338 ) {
339 if (s == null) {
340 return null;
341 }
342
343 boolean copyChars = true;
344 int count = 0; // number of WS
345
346 int S = s.length();
347
348 ArrayList<String> parts = new ArrayList<String>();
349
350 StringBuilder part = new StringBuilder(S);
351
352 for (int i = 0; i < S; ++i) {
353 char c = s.charAt(i);
354 if (copyChars) { // char mode
355 if (Character.isWhitespace(c)) {
356 if (part.length() > 0) {
357 parts.add(part.toString());
358 part.setLength(0);
359 }
360 count = 1;
361 copyChars = false; // to WS mode
362 }
363 else {
364 part.append(c);
365 }
366 }
367 else { // counting WS
368 if (Character.isWhitespace(c)) {
369 ++count;
370 }
371 else {
372 while (count >= N) {// enough to insert pad?
373 parts.add(pad);
374 count -= N;
375 }
376 part.append(c);
377 count = 0;
378 copyChars = true; // back to char mode
379 }
380 }
381 } // for all chars
382
383 if (copyChars) {
384 if (part.length() > 0) {
385 parts.add(part.toString());
386 }
387 }
388 else {
389 while (count >= N) { // enough to insert pad?
390 parts.add(pad);
391 count -= N;
392 }
393 }
394
395 return parts.toArray(new String[parts.size()]);
396 }
397
398 public static final String encodeURL(String url) {
399 try {
400 return url != null
401 ? URLEncoder.encode(url, "UTF-8")
402 : "";
403 }
404 catch (UnsupportedEncodingException usee) {
405 throw new RuntimeException(usee.getLocalizedMessage());
406 }
407 }
408
409 public static final String decodeURL(String url) {
410 try {
411 return url != null
412 ? URLDecoder.decode(url, "UTF-8")
413 : "";
414 }
415 catch (UnsupportedEncodingException usee) {
416 throw new RuntimeException(usee.getLocalizedMessage());
417 }
418 }
419
420 public static final boolean isEmpty(String s) {
421 return s == null || s.length() == 0;
422 }
423
424 public static final String empty(String s) {
425 return s == null ? "" : s;
426 }
427
428
429 public static final String trim(String s) {
430 return s != null ? s.trim() : null;
431 }
432
433 public static final String uniqueWhitespaces(String s) {
434 if (s == null) {
435 return null;
436 }
437
438 boolean wasWS = false;
439 StringBuilder sb = new StringBuilder();
440
441 for (int N = s.length(), i = 0; i < N; ++i) {
442 char c = s.charAt(i);
443 if (Character.isWhitespace(c)) {
444 if (!wasWS) {
445 sb.append(c);
446 wasWS = true;
447 }
448 }
449 else {
450 sb.append(c);
451 wasWS = false;
452 }
453 }
454
455 return sb.toString();
456 }
457
458 public static final String replaceNewlines(String s) {
459 return s == null
460 ? null
461 : s.replace('\r', ' ').replace('\n', ' ');
462 }
463
464 /*
465 public static final String quoteReplacement(String s) {
466
467 if (s == null || (s.indexOf('\\') == -1 && s.indexOf('$') == -1))
468 return s;
469
470 StringBuilder sb = new StringBuilder();
471
472 for (int N = s.length(), i = 0; i < N; ++i) {
473 char c = s.charAt(i);
474 if (c == '\\' || c == '$') sb.append('\\');
475 sb.append(c);
476 }
477
478 return sb.toString();
479 }
480 */
481
482 public static final String quoteReplacement(String s) {
483
484 if (s == null) {
485 return null;
486 }
487
488 for (int N = s.length(), i = 0; i < N; ++i) { // plain check loop
489 char c = s.charAt(i);
490 if (c == '$' || c == '\\') { // first special -> StringBuilder
491 StringBuilder sb = new StringBuilder(s.substring(0, i))
492 .append('\\')
493 .append(c);
494 for (++i; i < N; ++i) { // build StringBuilder with rest
495 if ((c = s.charAt(i)) == '$' || c == '\\') {
496 sb.append('\\');
497 }
498 sb.append(c);
499 }
500 return sb.toString();
501 }
502 }
503
504 return s;
505 }
506
507 public static final String repeat(String what, int times) {
508 return repeat(what, times, new StringBuilder()).toString();
509 }
510
511 public static final StringBuilder repeat(String what, int times, StringBuilder sb) {
512 while (times-- > 0) {
513 sb.append(what);
514 }
515 return sb;
516 }
517
518 /**
519 * Returns the file name without extension.
520 */
521 public static final String cutExtension(String s) {
522 if (s == null) {
523 return null;
524 }
525 int dot = s.lastIndexOf('.');
526 return dot >= 0
527 ? s.substring(0, dot)
528 : s;
529 }
530
531 public static final String extension(String s) {
532 if (s == null) {
533 return null;
534 }
535 int dot = s.lastIndexOf('.');
536 return dot >= 0
537 ? s.substring(dot+1)
538 : s;
539 }
540
541 public static final String [] splitExtension(String x) {
542 if (x == null) {
543 return null;
544 }
545 int i = x.lastIndexOf('.');
546 return i < 0
547 ? new String[] { x, null }
548 : new String[] { x.substring(0, Math.max(0, i)), x.substring(i+1).toLowerCase() };
549 }
550
551 public static String entityEncode(String s) {
552 if (s == null || s.length() == 0) {
553 return s;
554 }
555
556 StringBuilder sb = new StringBuilder();
557 for (int i=0, N =s.length(); i < N; i++) {
558 char c = s.charAt(i);
559 switch (c) {
560 case '<':
561 sb.append("&lt;");
562 break;
563 case '>':
564 sb.append("&gt;");
565 break;
566 case '&':
567 sb.append("&amp;");
568 break;
569 default:
570 sb.append(c);
571 }
572 }
573 return sb.toString();
574 }
575
576 public static String entityDecode(String s) {
577 if (s == null || s.length() == 0) {
578 return s;
579 }
580
581 boolean amp = false;
582 StringBuilder sb = new StringBuilder();
583 StringBuilder ampbuf = new StringBuilder();
584 for (int i=0, N =s.length(); i < N; i++) {
585 char c = s.charAt(i);
586 if (amp) {
587 if (c == ';') {
588 amp = false;
589 String str = ampbuf.toString();
590 ampbuf.setLength(0);
591 if (str.equals("lt")) {
592 sb.append('<');
593 }
594 else if (str.equals("gt")) {
595 sb.append('>');
596 }
597 else if (str.equals("amp")) {
598 sb.append('&');
599 }
600 else {
601 sb.append('&').append(str).append(';');
602 }
603 }
604 else {
605 ampbuf.append(c);
606 }
607 }
608 else if (c=='&') {
609 amp = true;
610 }
611 else {
612 sb.append(c);
613 }
614
615 }
616 return sb.toString();
617 }
618
619 public static final String quote(String s) {
620 return quote(s, '"');
621 }
622
623 public static final String quote(String s, char quoteChar) {
624 if (s == null) {
625 return null;
626 }
627
628 int N = s.length();
629
630 if (N == 0)
631 return new StringBuilder(2)
632 .append(quoteChar)
633 .append(quoteChar)
634 .toString();
635
636 StringBuilder sb = null;
637
638 int i = 0;
639
640 for (; i < N; ++i) {
641 char c = s.charAt(i);
642
643 if (Character.isWhitespace(c)) {
644 sb = new StringBuilder()
645 .append(quoteChar)
646 .append(s.substring(0, i+1));
647 break;
648 }
649 else if (c == quoteChar) {
650 sb = new StringBuilder()
651 .append(quoteChar)
652 .append(s.substring(0, i))
653 .append('\\')
654 .append(quoteChar);
655 break;
656 }
657 }
658
659 if (sb == null) {
660 return s;
661 }
662
663 for (++i; i < N; ++i) {
664 char c = s.charAt(i);
665 if (c == quoteChar || c == '\\') {
666 sb.append('\\');
667 }
668
669 sb.append(c);
670 }
671
672 return sb.append(quoteChar).toString();
673 }
674
675 /*
676 public static String sprintf(String format, Object... args) {
677 return sprintf(null, format, args);
678 }
679 */
680
681 public static String sprintf(Locale locale, String format, Object ... args) {
682 StringWriter sw = new StringWriter();
683 PrintWriter pw = new PrintWriter(sw);
684 pw.printf(locale, format, args);
685 pw.flush();
686 return sw.toString();
687 }
688
689
690 public static void testQuote() {
691 System.err.println("testing quote:");
692
693 String cases [] = {
694 "", "''",
695 "test", "test",
696 "test test", "'test test'",
697 " test", "' test'",
698 "test ", "'test '",
699 " test ", "' test '",
700 "'test", "'\\'test'",
701 "'", "'\\''",
702 " ' ' ", "' \\' \\' '",
703 "te'st", "'te\\'st'"
704 };
705
706 int failed = 0;
707
708 for (int i = 0; i < cases.length; i += 2) {
709 String in = cases[i];
710 String out = cases[i+1];
711
712 String res = quote(in, '\'');
713 if (!res.equals(out)) {
714 ++failed;
715 System.err.println(
716 "quote failed on: >" + in +
717 "< result: >" + res +
718 "< expected: >" + out + "<");
719 }
720 }
721
722 int T = cases.length/2;
723
724 System.err.println("tests total: " + T);
725 System.err.println("tests failed: " + failed);
726 System.err.println("tests passed: " + (T - failed));
727 }
728
729 public static void testQuoteReplacement() {
730 System.err.println("testing quoteReplacement:");
731
732 String cases [] = {
733 "", "",
734 "test", "test",
735 "$", "\\$",
736 "\\", "\\\\",
737 "\\$", "\\\\\\$",
738 "test\\$", "test\\\\\\$",
739 "\\test", "\\\\test",
740 "test$", "test\\$",
741 "test$test", "test\\$test",
742 "$test$", "\\$test\\$"
743 };
744
745 int failed = 0;
746
747 for (int i = 0; i < cases.length; i += 2) {
748 String in = cases[i];
749 String out = cases[i+1];
750
751 String res = quoteReplacement(in);
752 if (!res.equals(out)) {
753 ++failed;
754 System.err.println(
755 "quoteReplacement failed on: '" + in +
756 "' result: '" + res +
757 "' expected: '" + out + "'");
758 }
759 }
760
761 int T = cases.length/2;
762
763 System.err.println("tests total: " + T);
764 System.err.println("tests failed: " + failed);
765 System.err.println("tests passed: " + (T - failed));
766 }
767
768 public static void testStringArray2D() {
769 int total = 0;
770 int fail = 0;
771 int passed = 0;
772
773 System.err.println("testing StringArray2D:");
774
775 double[][] testarray = {{1.0, 2.0, 3.0},
776 {1.1, 2.1, 3.1},
777 {100.2, 200.2}
778 };
779 String str = double2DArrayToString(testarray);
780
781 total += 1;
782 if (str.equals("1.0;2.0;3.0:1.1;2.1;3.1:100.2;200.2")) {
783 passed +=1;
784 }
785 else {
786 fail +=1;
787 System.err.println("Der Ergebnis-String ist nicht richtig:");
788 System.err.println(str);
789 }
790
791
792
793 double[][] testarray2 = stringToDouble2DArray(str);
794 boolean failed = false;
795
796 total +=1;
797 for (int i=0; i < testarray.length; i++)
798 for (int j=0; j < testarray[i].length; j++)
799 if (testarray[i][j] != testarray2[i][j]) {
800 System.err.println("Test scheitert bei i=" +i +" j=" +j);
801 System.err.println("alter Wert=" + testarray[i][j] +" neuer Wert=" +testarray2[i][j]);
802 failed = true;
803 }
804 if (failed) {
805 fail +=1;
806 }
807 else {
808 passed +=1;
809 }
810 System.err.println("tests total: "+ total);
811 System.err.println("tests failed: "+ fail);
812 System.err.println("tests passed: "+ passed);
813 }
814
815 public static void main(String [] args) {
816
817 testQuoteReplacement();
818 testQuote();
819 testStringArray2D();
820 }
821
822 /** Check for occurence of needle in hay, converting both to lowercase
823 * to be ignorant of cases. */
824 public static boolean containsIgnoreCase(String hay, String needle) {
825 return hay.toLowerCase().contains(needle.toLowerCase());
826 }
827 }
828 // end of file

http://dive4elements.wald.intevation.org