OpenConcerto

Dépôt officiel du code source de l'ERP OpenConcerto
sonarqube

svn://code.openconcerto.org/openconcerto

Rev

Rev 149 | Rev 177 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
17 ilm 1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
5
 *
6
 * The contents of this file are subject to the terms of the GNU General Public License Version 3
7
 * only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
8
 * copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
9
 * language governing permissions and limitations under the License.
10
 *
11
 * When distributing the software, include this License Header Notice in each file.
12
 */
13
 
14
 /*
15
 * Créé le 3 mars 2005
16
 */
17
package org.openconcerto.utils;
18
 
83 ilm 19
import java.awt.FontMetrics;
20
import java.math.BigDecimal;
19 ilm 21
import java.nio.charset.Charset;
17 ilm 22
import java.util.ArrayList;
23
import java.util.Collections;
24
import java.util.HashMap;
25
import java.util.HashSet;
83 ilm 26
import java.util.Iterator;
17 ilm 27
import java.util.LinkedHashMap;
28
import java.util.List;
29
import java.util.Map;
30
import java.util.Set;
174 ilm 31
import java.util.regex.Matcher;
28 ilm 32
import java.util.regex.Pattern;
17 ilm 33
 
34
/**
35
 * @author Sylvain CUAZ
36
 */
37
public class StringUtils {
38
 
80 ilm 39
    // required encoding see Charset
40
    public static final Charset UTF8 = Charset.forName("UTF-8");
41
    public static final Charset UTF16 = Charset.forName("UTF-16");
42
    public static final Charset ASCII = Charset.forName("US-ASCII");
43
    public static final Charset ISO8859_1 = Charset.forName("ISO-8859-1");
44
    // included in rt.jar see
28 ilm 45
    // http://docs.oracle.com/javase/7/docs/technotes/guides/intl/encoding.doc.html
80 ilm 46
    public static final Charset ISO8859_15 = Charset.forName("ISO-8859-15");
28 ilm 47
    public static final Charset Cp1252 = Charset.forName("Cp1252");
48
    public static final Charset Cp850 = Charset.forName("Cp850");
19 ilm 49
 
144 ilm 50
    public static final char BOM = '\ufeff';
51
 
93 ilm 52
    final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
53
 
17 ilm 54
    /**
55
     * Retourne la chaine avec la première lettre en majuscule et le reste en minuscule.
56
     *
57
     * @param s la chaîne à transformer.
58
     * @return la chaine avec la première lettre en majuscule et le reste en minuscule.
59
     */
60
    public static String firstUpThenLow(String s) {
61
        if (s.length() == 0) {
62
            return s;
63
        }
64
        if (s.length() == 1) {
65
            return s.toUpperCase();
66
        }
67
        return s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();
68
    }
69
 
70
    public static String firstUp(String s) {
71
        if (s.length() == 0) {
72
            return s;
73
        }
74
        if (s.length() == 1) {
75
            return s.toUpperCase();
76
        }
77
        return s.substring(0, 1).toUpperCase() + s.substring(1);
78
    }
79
 
19 ilm 80
    static public abstract class Shortener {
81
 
82
        private final int hashSize;
83
        private final int hashPartSize;
84
        private final String prefix;
85
        private final String suffix;
86
        private final int minStringLength;
87
 
88
        protected Shortener(int hashSize, String prefix, String suffix, int minCharsBeforeAndAfter) {
89
            super();
90
            this.hashSize = hashSize;
91
            this.prefix = prefix;
92
            this.suffix = suffix;
93
            this.hashPartSize = this.hashSize + this.prefix.length() + this.suffix.length();
94
            if (minCharsBeforeAndAfter < 1)
95
                throw new IllegalArgumentException("minCharsBeforeAndAfter must be at least 1: " + minCharsBeforeAndAfter);
96
            this.minStringLength = this.hashPartSize + minCharsBeforeAndAfter * 2;
97
        }
98
 
99
        public final int getMinStringLength() {
100
            return this.minStringLength;
101
        }
102
 
103
        public final String getBoundedLengthString(final String s, final int maxLength) {
104
            // don't test first for s.length, it's more predictable
105
            // (otherwise boundedString("a", 2) would succeed)
106
            if (maxLength < this.getMinStringLength())
107
                throw new IllegalArgumentException("Maximum too low : " + maxLength + "<" + getMinStringLength());
108
            if (s.length() <= maxLength)
109
                return s;
110
            else
111
                return this.shorten(s, maxLength);
112
        }
113
 
114
        final String shorten(final String s, final int maxLength) {
115
            assert s.length() >= this.getMinStringLength();
116
            final int toRemoveLength = s.length() - maxLength + this.hashPartSize;
117
            // remove the middle part of encoded
118
            final int toRemoveStartIndex = s.length() / 2 - toRemoveLength / 2;
119
            final String toHash = s.substring(toRemoveStartIndex, toRemoveStartIndex + toRemoveLength);
120
 
121
            final String hash = shorten(toHash);
122
            assert this.hashSize == hash.length();
123
 
124
            final String res = s.substring(0, toRemoveStartIndex) + this.prefix + hash + this.suffix + s.substring(toRemoveStartIndex + toRemoveLength);
125
            assert res.length() == maxLength;
126
            return res;
127
        }
128
 
129
        protected abstract String shorten(String s);
130
 
131
        static public final Shortener Ellipsis = new Shortener(1, "", "", 1) {
132
            @Override
133
            protected String shorten(String s) {
134
                return "…";
135
            }
136
        };
137
 
138
        // String.hashCode() is an int written in hex
139
        static public final Shortener JavaHashCode = new Shortener(Integer.SIZE / 8 * 2, "#", "#", 3) {
140
            @Override
141
            protected String shorten(String s) {
142
                return MessageDigestUtils.asHex(MessageDigestUtils.int2bytes(s.hashCode()));
143
            }
144
        };
145
 
146
        // 128 bits written in hex
147
        static public final Shortener MD5 = new Shortener(128 / 8 * 2, "#", "#", 11) {
148
            @Override
149
            protected String shorten(String s) {
150
                return MessageDigestUtils.getHashString(MessageDigestUtils.getMD5(), s.getBytes(UTF8));
151
            }
152
        };
153
 
154
        // order descendant by getMinStringLength()
155
        static final Shortener[] ORDERED = new Shortener[] { MD5, JavaHashCode, Ellipsis };
156
    }
157
 
158
    /**
159
     * The minimum value for {@link #getBoundedLengthString(String, int)}.
160
     *
161
     * @return the minimum value for <code>maxLength</code>.
162
     */
163
    public static final int getLeastMaximum() {
164
        return Shortener.ORDERED[Shortener.ORDERED.length - 1].getMinStringLength();
165
    }
166
 
167
    private static final Shortener getShortener(final int l) {
168
        for (final Shortener sh : Shortener.ORDERED) {
169
            if (l >= sh.getMinStringLength())
170
                return sh;
171
        }
172
        return null;
173
    }
174
 
175
    /**
176
     * Return a string built from <code>s</code> that is at most <code>maxLength</code> long.
177
     *
178
     * @param s the string to bound.
179
     * @param maxLength the maximum length the result must have.
180
     * @return a string built from <code>s</code>.
181
     * @throws IllegalArgumentException if <code>maxLength</code> is too small.
182
     * @see #getLeastMaximum()
183
     * @see Shortener#getBoundedLengthString(String, int)
184
     */
185
    public static final String getBoundedLengthString(final String s, final int maxLength) throws IllegalArgumentException {
186
        // don't test first for s.length, it's more predictable
187
        // (otherwise boundedString("a", 2) would succeed)
188
        if (maxLength < getLeastMaximum())
189
            throw new IllegalArgumentException("Maximum too low : " + maxLength + "<" + getLeastMaximum());
190
 
191
        final String res;
192
        if (s.length() <= maxLength) {
193
            res = s;
194
        } else {
195
            // use maxLength to choose the shortener since it's generally a constant
196
            // and thus the strings returned by this method have the same pattern
197
            res = getShortener(maxLength).shorten(s, maxLength);
198
        }
199
        return res;
200
    }
201
 
80 ilm 202
    static public enum Side {
203
        LEFT, RIGHT
204
    }
205
 
206
    public static String getFixedWidthString(final String s, final int width, final Side align) {
207
        return getFixedWidthString(s, width, align, false);
208
    }
209
 
132 ilm 210
    public static String getFixedWidthString(final String s, final int width, final Side align, final boolean allowShorten) {
80 ilm 211
        final int length = s.length();
212
        final String res;
213
        if (length == width) {
214
            res = s;
215
        } else if (length < width) {
132 ilm 216
            // we already tested length, so no need to allow shorten
217
            res = appendFixedWidthString(new StringBuilder(width), s, width, align, ' ', false).toString();
218
        } else {
219
            res = getTooWideString(s, width, allowShorten);
220
        }
221
        assert res.length() == width;
222
        return res;
223
    }
224
 
225
    private static String getTooWideString(final String s, final int width, final boolean allowShorten) {
226
        assert s.length() > width;
227
        if (!allowShorten)
228
            throw new IllegalArgumentException("Too wide : " + s.length() + " > " + width);
229
        return getBoundedLengthString(s, width);
230
    }
231
 
232
    public static StringBuilder appendFixedWidthString(final StringBuilder sb, final String s, final int width, final Side align, final char filler, final boolean allowShorten) {
233
        final int origBuilderLen = sb.length();
234
        final int length = s.length();
235
        if (length <= width) {
236
            sb.ensureCapacity(origBuilderLen + width);
80 ilm 237
            if (align == Side.LEFT)
238
                sb.append(s);
132 ilm 239
            for (int i = length; i < width; i++) {
240
                sb.append(filler);
80 ilm 241
            }
242
            if (align == Side.RIGHT)
243
                sb.append(s);
244
        } else {
132 ilm 245
            sb.append(getTooWideString(s, width, allowShorten));
80 ilm 246
        }
132 ilm 247
        assert sb.length() == origBuilderLen + width;
248
        return sb;
80 ilm 249
    }
250
 
17 ilm 251
    public static final List<String> fastSplit(final String string, final char sep) {
252
        final List<String> l = new ArrayList<String>();
253
        final int length = string.length();
254
        final char[] cars = string.toCharArray();
255
        int rfirst = 0;
256
 
257
        for (int i = 0; i < length; i++) {
258
            if (cars[i] == sep) {
259
                l.add(new String(cars, rfirst, i - rfirst));
260
                rfirst = i + 1;
261
            }
262
        }
263
 
264
        if (rfirst < length) {
265
            l.add(new String(cars, rfirst, length - rfirst));
266
        }
267
        return l;
268
    }
269
 
83 ilm 270
    public static final List<String> fastSplitTrimmed(final String string, final char sep) {
271
        final List<String> l = new ArrayList<String>();
272
        final int length = string.length();
273
        final char[] cars = string.toCharArray();
274
        int rfirst = 0;
275
 
276
        for (int i = 0; i < length; i++) {
277
            if (cars[i] == sep) {
278
                l.add(new String(cars, rfirst, i - rfirst).trim());
279
                rfirst = i + 1;
280
            }
281
        }
282
 
283
        if (rfirst < length) {
284
            l.add(new String(cars, rfirst, length - rfirst).trim());
285
        }
286
        return l;
287
    }
288
 
19 ilm 289
    /**
290
     * Split une string s tous les nbCharMaxLine
291
     *
292
     * @param s
293
     * @param nbCharMaxLine
294
     * @return
295
     */
296
    public static String splitString(String s, int nbCharMaxLine) {
297
 
298
        if (s == null) {
299
            return s;
300
        }
301
 
302
        if (s.trim().length() < nbCharMaxLine) {
303
            return s;
304
        }
305
        StringBuffer lastString = new StringBuffer();
306
        StringBuffer result = new StringBuffer();
307
        for (int i = 0; i < s.length(); i++) {
308
 
309
            if (lastString.length() == nbCharMaxLine) {
310
                int esp = lastString.lastIndexOf(" ");
25 ilm 311
                if (result.length() > 0 && result.charAt(result.length() - 1) != '\n') {
19 ilm 312
                    result.append("\n");
313
                }
314
                if (esp > 0) {
315
                    result.append(lastString.substring(0, esp).toString().trim());
316
                    lastString = new StringBuffer(lastString.substring(esp, lastString.length()));
317
                } else {
318
                    result.append(lastString.toString().trim());
319
                    lastString = new StringBuffer();
320
                }
25 ilm 321
                result.append("\n");
19 ilm 322
            }
323
 
324
            char charAt = s.charAt(i);
325
            if (charAt == '\n') {
326
                lastString.append(charAt);
21 ilm 327
                result.append(lastString);
19 ilm 328
                lastString = new StringBuffer();
329
            } else {
330
                lastString.append(charAt);
331
            }
332
        }
333
 
25 ilm 334
        if (result.length() > 0 && result.charAt(result.length() - 1) != '\n') {
19 ilm 335
            result.append("\n");
336
        }
337
 
338
        result.append(lastString.toString().trim());
339
 
340
        return result.toString();
341
    }
342
 
83 ilm 343
    static public int firstIndexOf(final String s, final char[] chars) {
344
        return firstIndexOf(s, 0, chars);
345
    }
346
 
347
    static public int firstIndexOf(final String s, final int offset, final char[] chars) {
348
        int res = -1;
349
        for (final char c : chars) {
350
            final int index = s.indexOf(c, offset);
351
            if (index >= 0 && (res == -1 || index < res))
352
                res = index;
353
        }
354
        return res;
355
    }
356
 
61 ilm 357
    static private final Pattern quotePatrn = Pattern.compile("\"", Pattern.LITERAL);
358
    static private final Pattern slashPatrn = Pattern.compile("(\\\\+)");
28 ilm 359
 
360
    static public String doubleQuote(String s) {
142 ilm 361
        return doubleQuote(s, true);
362
    }
363
 
364
    static public String doubleQuote(String s, final boolean escapeEscapeChar) {
61 ilm 365
        // http://developer.apple.com/library/mac/#documentation/applescript/conceptual/applescriptlangguide/reference/ASLR_classes.html#//apple_ref/doc/uid/TP40000983-CH1g-SW6
366
        // http://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.10.5
367
        // https://developer.mozilla.org/en/JavaScript/Guide/Values%2C_Variables%2C_and_Literals#Escaping_characters
28 ilm 368
        if (s.length() > 0) {
142 ilm 369
            if (escapeEscapeChar)
370
                s = slashPatrn.matcher(s).replaceAll("$1$1");
61 ilm 371
            s = quotePatrn.matcher(s).replaceAll("\\\\\"");
28 ilm 372
        }
373
        return '"' + s + '"';
374
    }
375
 
83 ilm 376
    /**
377
     * Unquote a double quoted string.
378
     *
379
     * @param s the string to unquote, e.g. "foo\\bar".
380
     * @return the unquoted form, e.g. foo\bar.
381
     * @throws IllegalArgumentException if the string is not quoted, or if there's some extra
382
     *         content at the end.
383
     */
384
    static public String unDoubleQuote(String s) {
385
        final Tuple2<String, Integer> res = unDoubleQuote(s, 0);
386
        if (res.get1().intValue() != s.length())
387
            throw new IllegalArgumentException("Extra content at the end : " + s.substring(res.get1()));
388
        return res.get0();
389
    }
390
 
391
    /**
392
     * Unquote part of a double quoted string.
393
     *
394
     * @param s the string to unquote, e.g. pre"foo\\bar"post.
395
     * @param offset the start index of the quotes, e.g. 3.
396
     * @return the unquoted form and the index after the end quote, e.g. foo\bar and 13.
397
     * @throws IllegalArgumentException if the string is not quoted.
398
     */
399
    static public Tuple2<String, Integer> unDoubleQuote(String s, int offset) {
400
        if (s.charAt(offset) != '"')
401
            throw new IllegalArgumentException("Expected quote but got : " + s.charAt(offset));
402
        final int l = s.length();
403
        if (offset + 1 < l && s.charAt(offset + 1) == '"')
404
            return Tuple2.create("", offset + 2);
405
 
406
        offset++;
407
        final char[] chars = new char[] { '"', '\\' };
408
        final StringBuilder sb = new StringBuilder(512);
409
        boolean foundEnd = false;
410
        while (offset < l && !foundEnd) {
411
            final int index = firstIndexOf(s, offset, chars);
412
            if (index < 0)
413
                throw new IllegalArgumentException("End quote not found after " + offset);
414
            sb.append(s.substring(offset, index));
415
            if (s.charAt(index) == '"') {
416
                offset = index + 1;
417
                foundEnd = true;
418
            } else {
419
                assert s.charAt(index) == '\\';
420
                sb.append(s.charAt(index + 1));
421
                offset = index + 2;
422
            }
423
        }
424
        if (!foundEnd)
425
            throw new IllegalArgumentException("End quote not found after " + offset);
426
        return Tuple2.create(sb.toString(), offset);
427
    }
428
 
17 ilm 429
    public static final class Escaper {
430
 
431
        // eg '
432
        private final char esc;
433
 
434
        // eg { '=> S, " => D}
435
        private final Map<Character, Character> substitution;
436
        private final Map<Character, Character> inv;
437
 
438
        /**
439
         * A new escaper that will have <code>esc</code> as escape character.
440
         *
441
         * @param esc the escape character, eg '
442
         * @param name the character that will be appended to <code>esc</code>, eg with S all
443
         *        occurrences of ' will be replaced by 'S
444
         */
445
        public Escaper(char esc, char name) {
446
            super();
447
            this.esc = esc;
448
            this.substitution = new LinkedHashMap<Character, Character>();
449
            this.inv = new HashMap<Character, Character>();
450
            this.add(esc, name);
451
        }
452
 
453
        public Escaper add(char toRemove, char escapedName) {
454
            if (this.inv.containsKey(escapedName))
455
                throw new IllegalArgumentException(escapedName + " already replaces " + this.inv.get(escapedName));
456
            this.substitution.put(toRemove, escapedName);
457
            this.inv.put(escapedName, toRemove);
458
            return this;
459
        }
460
 
461
        public final Set<Character> getEscapedChars() {
462
            final Set<Character> res = new HashSet<Character>(this.substitution.keySet());
463
            res.remove(this.esc);
464
            return res;
465
        }
466
 
467
        /**
468
         * Escape <code>s</code>, so that the resulting string has none of
469
         * {@link #getEscapedChars()}.
470
         *
471
         * @param s a string to escape.
472
         * @return the escaped form.
473
         */
474
        public final String escape(String s) {
475
            String res = s;
476
            // this.esc en premier
477
            for (final Character toEsc : this.substitution.keySet()) {
478
                // use Pattern.LITERAL to avoid interpretion
479
                res = res.replace(toEsc + "", getEscaped(toEsc));
480
            }
481
            return res;
482
        }
483
 
484
        private String getEscaped(final Character toEsc) {
485
            return this.esc + "" + this.substitution.get(toEsc);
486
        }
487
 
488
        public final String unescape(String escaped) {
489
            String res = escaped;
490
            final List<Character> toEscs = new ArrayList<Character>(this.substitution.keySet());
491
            Collections.reverse(toEscs);
492
            for (final Character toEsc : toEscs) {
493
                res = res.replaceAll(getEscaped(toEsc), toEsc + "");
494
            }
495
            return res;
496
        }
497
 
498
        @Override
499
        public boolean equals(Object obj) {
500
            if (obj instanceof Escaper) {
501
                final Escaper o = (Escaper) obj;
502
                return this.esc == o.esc && this.substitution.equals(o.substitution);
503
            } else
504
                return false;
505
        }
506
 
507
        @Override
508
        public int hashCode() {
509
            return this.esc + this.substitution.hashCode();
510
        }
511
    }
512
 
25 ilm 513
    public static String rightAlign(String s, int width) {
514
        String r = s;
515
        int n = width - s.length();
516
        for (int i = 0; i < n; i++) {
517
            r = ' ' + r;
518
        }
519
        return r;
520
    }
521
 
522
    public static String leftAlign(String s, int width) {
523
        String r = s;
524
        int n = width - s.length();
525
        for (int i = 0; i < n; i++) {
526
            r += ' ';
527
        }
528
        return r;
529
    }
73 ilm 530
 
531
    public static String trim(final String s, final boolean leading) {
532
        // from String.trim()
533
        int end = s.length();
534
        int st = 0;
535
 
536
        if (leading) {
537
            while ((st < end) && (s.charAt(st) <= ' ')) {
538
                st++;
539
            }
540
        } else {
541
            while ((st < end) && (s.charAt(end - 1) <= ' ')) {
542
                end--;
543
            }
544
        }
545
        return ((st > 0) || (end < s.length())) ? s.substring(st, end) : s;
546
    }
80 ilm 547
 
548
    public static String limitLength(String s, int maxLength) {
549
        if (s.length() <= maxLength) {
550
            return s;
551
        }
552
        return s.substring(0, maxLength);
553
    }
554
 
555
    public static String removeAllSpaces(String text) {
556
        final int length = text.length();
557
        final StringBuilder builder = new StringBuilder(length);
558
        for (int i = 0; i < length; i++) {
559
            char c = text.charAt(i);
560
            if (c <= ' ' && c != 160) {
561
                // remove non printable chars
562
                // spaces
563
                // non breakable space (160)
564
                builder.append(c);
565
            }
566
        }
567
        return builder.toString();
568
    }
569
 
570
    public static String removeNonDecimalChars(String text) {
571
        final int length = text.length();
572
        final StringBuilder builder = new StringBuilder(length);
573
        for (int i = 0; i < length; i++) {
574
            char c = text.charAt(i);
575
            if (Character.isDigit(c) || c == '.' || c == '+' || c == '-') {
576
                builder.append(c);
577
            }
578
        }
579
        return builder.toString();
580
    }
83 ilm 581
 
582
    public static BigDecimal getBigDecimalFromUserText(String text) {
583
        text = text.trim();
584
        if (text.isEmpty() || text.equals("-")) {
585
            return BigDecimal.ZERO;
586
        }
587
        text = removeNonDecimalChars(text);
588
        BigDecimal result = null;
589
        try {
590
            result = new BigDecimal(text);
591
        } catch (Exception e) {
592
            Log.get().info(text + " is not a valid decimal");
593
        }
594
        return result;
595
    }
596
 
597
    /**
598
     * Returns an array of strings, one for each line in the string after it has been wrapped to fit
599
     * lines of <var>maxWidth</var>. Lines end with any of cr, lf, or cr lf. A line ending at the
600
     * end of the string will not output a further, empty string.
601
     * <p>
602
     * This code assumes <var>str</var> is not <code>null</code>.
603
     *
604
     * @param str the string to split
605
     * @param fm needed for string width calculations
606
     * @param maxWidth the max line width, in points
607
     * @return a non-empty list of strings
608
     */
609
    public static List<String> wrap(String str, FontMetrics fm, int maxWidth) {
610
        List<String> lines = splitIntoLines(str);
611
        if (lines.size() == 0)
612
            return lines;
613
 
614
        List<String> strings = new ArrayList<String>();
615
        for (Iterator<String> iter = lines.iterator(); iter.hasNext();) {
616
            wrapLineInto(iter.next(), strings, fm, maxWidth);
617
        }
618
        return strings;
619
    }
620
 
621
    /**
622
     * Given a line of text and font metrics information, wrap the line and add the new line(s) to
623
     * <var>list</var>.
624
     *
625
     * @param line a line of text
626
     * @param list an output list of strings
627
     * @param fm font metrics
628
     * @param maxWidth maximum width of the line(s)
629
     */
630
    public static void wrapLineInto(String line, List<String> list, FontMetrics fm, int maxWidth) {
631
        int len = line.length();
632
        int width;
633
        while (len > 0 && (width = fm.stringWidth(line)) > maxWidth) {
634
            // Guess where to split the line. Look for the next space before
635
            // or after the guess.
636
            int guess = len * maxWidth / width;
637
            String before = line.substring(0, guess).trim();
638
 
639
            width = fm.stringWidth(before);
640
            int pos;
641
            if (width > maxWidth) // Too long
642
                pos = findBreakBefore(line, guess);
643
            else { // Too short or possibly just right
644
                pos = findBreakAfter(line, guess);
645
                if (pos != -1) { // Make sure this doesn't make us too long
646
                    before = line.substring(0, pos).trim();
647
                    if (fm.stringWidth(before) > maxWidth)
648
                        pos = findBreakBefore(line, guess);
649
                }
650
            }
651
            if (pos == -1)
652
                pos = guess; // Split in the middle of the word
653
 
654
            list.add(line.substring(0, pos).trim());
655
            line = line.substring(pos).trim();
656
            len = line.length();
657
        }
658
        if (len > 0) {
659
            list.add(line);
660
        }
661
    }
662
 
663
    /**
664
     * Returns the index of the first whitespace character or '-' in <var>line</var> that is at or
665
     * before <var>start</var>. Returns -1 if no such character is found.
666
     *
667
     * @param line a string
668
     * @param start where to star looking
669
     */
670
    public static int findBreakBefore(String line, int start) {
671
        for (int i = start; i >= 0; --i) {
672
            char c = line.charAt(i);
673
            if (Character.isWhitespace(c) || c == '-')
674
                return i;
675
        }
676
        return -1;
677
    }
678
 
679
    /**
680
     * Returns the index of the first whitespace character or '-' in <var>line</var> that is at or
681
     * after <var>start</var>. Returns -1 if no such character is found.
682
     *
683
     * @param line a string
684
     * @param start where to star looking
685
     */
686
    public static int findBreakAfter(String line, int start) {
687
        int len = line.length();
688
        for (int i = start; i < len; ++i) {
689
            char c = line.charAt(i);
690
            if (Character.isWhitespace(c) || c == '-')
691
                return i;
692
        }
693
        return -1;
694
    }
695
 
696
    /**
697
     * Returns an array of strings, one for each line in the string. Lines end with any of cr, lf,
698
     * or cr lf. A line ending at the end of the string will not output a further, empty string.
699
     * <p>
700
     * This code assumes <var>str</var> is not <code>null</code>.
701
     *
702
     * @param str the string to split
703
     * @return a non-empty list of strings
704
     */
705
    public static List<String> splitIntoLines(String str) {
706
        List<String> strings = new ArrayList<String>();
707
 
708
        int len = str.length();
709
        if (len == 0) {
710
            strings.add("");
711
            return strings;
712
        }
713
 
714
        int lineStart = 0;
715
 
716
        for (int i = 0; i < len; ++i) {
717
            char c = str.charAt(i);
718
            if (c == '\r') {
719
                int newlineLength = 1;
720
                if ((i + 1) < len && str.charAt(i + 1) == '\n')
721
                    newlineLength = 2;
722
                strings.add(str.substring(lineStart, i));
723
                lineStart = i + newlineLength;
724
                if (newlineLength == 2) // skip \n next time through loop
725
                    ++i;
726
            } else if (c == '\n') {
727
                strings.add(str.substring(lineStart, i));
728
                lineStart = i + 1;
729
            }
730
        }
731
        if (lineStart < len)
732
            strings.add(str.substring(lineStart));
733
 
734
        return strings;
735
    }
736
 
93 ilm 737
    /**
738
     * convert a byte array to its hexa representation
132 ilm 739
     */
93 ilm 740
    public static String bytesToHexString(byte[] bytes) {
741
        final int length = bytes.length;
742
        char[] hexChars = new char[length * 2];
743
        for (int j = 0; j < length; j++) {
744
            int v = bytes[j] & 0xFF;
745
            hexChars[j * 2] = hexArray[v >>> 4];
746
            hexChars[j * 2 + 1] = hexArray[v & 0x0F];
747
        }
748
        return new String(hexChars);
749
    }
142 ilm 750
 
751
    /**
752
     * Whether the parameter is empty.
753
     *
754
     * @param s the string to test.
755
     * @return <code>true</code> if <code>null</code> or {@link String#isEmpty() empty}.
756
     */
757
    public static boolean isEmpty(final String s) {
758
        return isEmpty(s, false);
759
    }
760
 
761
    public static boolean isEmpty(final String s, final boolean trim) {
762
        return s == null || (trim ? s.trim() : s).isEmpty();
763
    }
764
 
765
    /**
766
     * Return the first parameter that is non-empty.
767
     *
768
     * @param s1 the string to test.
769
     * @param s2 the alternate value.
770
     * @return <code>s1</code> if not <code>null</code> and not {@link String#isEmpty() empty},
771
     *         <code>s2</code> otherwise.
772
     */
773
    public static String coalesce(String s1, String s2) {
774
        return isEmpty(s1) ? s2 : s1;
775
    }
776
 
777
    /**
778
     * Return the first value that is non-empty.
779
     *
780
     * @param values values to test for emptiness.
781
     * @return the first value that is neither <code>null</code> nor {@link String#isEmpty() empty}.
782
     */
783
    public static String coalesce(String... values) {
784
        return coalesce(false, values);
785
    }
786
 
787
    public static String coalesce(final boolean trim, String... values) {
788
        for (final String s : values)
789
            if (!isEmpty(s, trim))
790
                return s;
791
        return null;
792
    }
149 ilm 793
 
794
    public static String toAsciiString(String str) {
795
        if (str == null) {
796
            return null;
797
        }
798
        final int length = str.length();
799
        final StringBuilder b = new StringBuilder(length);
800
        for (int i = 0; i < length; i++) {
801
            final char c = str.charAt(i);
802
            final char newChar;
803
            if (c < 128) {
804
                newChar = c;
805
            } else if (c == 'é' || c == 'è' || c == 'ê') {
806
                newChar = 'e';
807
            } else if (c == 'â' || c == 'à') {
808
                newChar = 'a';
809
            } else if (c == 'î') {
810
                newChar = 'i';
811
            } else if (c == 'ù' || c == 'û') {
812
                newChar = 'u';
813
            } else if (c == 'ô') {
814
                newChar = 'o';
815
            } else if (c == 'ç') {
816
                newChar = 'c';
817
            } else {
818
                newChar = ' ';
819
            }
820
            b.append(newChar);
821
        }
822
        return b.toString();
823
    }
174 ilm 824
 
825
    public static final Matcher findFirstContaining(final String s, final Pattern... patterns) {
826
        for (final Pattern p : patterns) {
827
            final Matcher matcher = p.matcher(s);
828
            if (matcher.find())
829
                return matcher;
830
        }
831
        return null;
832
    }
17 ilm 833
}