Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: d823cd3f2d9d7b095befee4fb1f671afbcf53f58 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
/***************************************************************************
 * Copyright (c) 2004, 2005, 2006 Eike Stepper, Fuggerstr. 39, 10777 Berlin, Germany.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * 
 * Contributors:
 *    Eike Stepper - initial API and implementation
 **************************************************************************/
package org.eclipse.net4j.util;


import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import java.nio.ByteBuffer;


public class StringHelper
{

  public static final char HEX_DIGITS[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a',
      'b', 'c', 'd', 'e', 'f',};

  public static final String UTF8_CHARS = "                                "
      + " !\"#$%&'()*+,-./0123456789:;<=>?" + "@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_"
      + "`abcdefghijklmnopqrstuvwxyz{|}~";

  public static final char SEPARATOR = '\n';

  /**
   * This method is used to insert HTML block dynamically
   * 
   * @param source
   *          the HTML code to be processes
   * @param bReplaceNl
   *          if true '\n' will be replaced by <br>
   * @param bReplaceTag
   *          if true ' <' will be replaced by &lt; and '>' will be replaced by &gt;
   * @param bReplaceQuote
   *          if true '\"' will be replaced by &quot;
   */
  public static String formatHtml(String source, boolean bReplaceNl, boolean bReplaceTag,
      boolean bReplaceQuote)
  {

    StringBuffer sb = new StringBuffer();
    int len = source.length();
    for (int i = 0; i < len; i++)
    {
      char c = source.charAt(i);
      switch (c)
      {
        case '\"':
          if (bReplaceQuote)
            sb.append("&quot;");
          else
            sb.append(c);
          break;

        case '<':
          if (bReplaceTag)
            sb.append("&lt;");
          else
            sb.append(c);
          break;

        case '>':
          if (bReplaceTag)
            sb.append("&gt;");
          else
            sb.append(c);
          break;

        case '\n':
          if (bReplaceNl)
          {
            if (bReplaceTag)
              sb.append("&lt;br&gt;");
            else
              sb.append("<br>");
          }
          else
          {
            sb.append(c);
          }
          break;

        case '\r':
          break;

        case '&':
          sb.append("&amp;");
          break;

        default:
          sb.append(c);
          break;
      }
    }
    return sb.toString();
  }

  public static String getLastToken(String str, char separator)
  {
    int pos = str.lastIndexOf(separator);
    if (pos != -1)
    {
      str = str.substring(pos + 1);
    }
    return str;
  }

  public static String getSimpleClassName(Class aClass)
  {
    return getSimpleClassName(aClass.getName());
  }

  public static String getSimpleClassName(String qualifiedClassName)
  {
    return getLastToken(qualifiedClassName, '.');
  }

  /**
   * Pad string object
   */
  public static String pad(String src, char padChar, boolean rightPad, int totalLength)
  {

    int srcLength = src.length();
    if (srcLength >= totalLength)
    {
      return src;
    }

    int padLength = totalLength - srcLength;
    StringBuffer sb = new StringBuffer(padLength);
    for (int i = 0; i < padLength; ++i)
    {
      sb.append(padChar);
    }

    if (rightPad)
    {
      return src + sb.toString();
    }
    else
    {
      return sb.toString() + src;
    }
  }

  public static String removePrefix(String str, String prefix)
  {
    if (str.startsWith(prefix))
    {
      return str.substring(prefix.length());
    }
    return str;
  }

  public static String removeSuffix(String str, String suffix)
  {
    if (str.endsWith(suffix))
    {
      return str.substring(0, str.length() - suffix.length());
    }
    return str;
  }

  /**
   * Replace string
   */
  public static String replaceString(String source, Map args)
  {
    int startIndex = 0;
    int openIndex = source.indexOf('{', startIndex);
    if (openIndex == -1)
    {
      return source;
    }

    int closeIndex = source.indexOf('}', startIndex);
    if ((closeIndex == -1) || (openIndex > closeIndex))
    {
      return source;
    }

    StringBuffer sb = new StringBuffer();
    sb.append(source.substring(startIndex, openIndex));
    while (true)
    {
      String key = source.substring(openIndex + 1, closeIndex);
      Object val = args.get(key);
      if (val != null)
      {
        sb.append(val);
      }

      startIndex = closeIndex + 1;
      openIndex = source.indexOf('{', startIndex);
      if (openIndex == -1)
      {
        sb.append(source.substring(startIndex));
        break;
      }

      closeIndex = source.indexOf('}', startIndex);
      if ((closeIndex == -1) || (openIndex > closeIndex))
      {
        sb.append(source.substring(startIndex));
        break;
      }
      sb.append(source.substring(startIndex, openIndex));
    }
    return sb.toString();
  }

  /**
   * Replace string
   */
  public static String replaceString(String source, Object[] args)
  {
    int startIndex = 0;
    int openIndex = source.indexOf('{', startIndex);
    if (openIndex == -1)
    {
      return source;
    }

    int closeIndex = source.indexOf('}', startIndex);
    if ((closeIndex == -1) || (openIndex > closeIndex))
    {
      return source;
    }

    StringBuffer sb = new StringBuffer();
    sb.append(source.substring(startIndex, openIndex));
    while (true)
    {
      String intStr = source.substring(openIndex + 1, closeIndex);
      int index = Integer.parseInt(intStr);
      sb.append(args[index]);

      startIndex = closeIndex + 1;
      openIndex = source.indexOf('{', startIndex);
      if (openIndex == -1)
      {
        sb.append(source.substring(startIndex));
        break;
      }

      closeIndex = source.indexOf('}', startIndex);
      if ((closeIndex == -1) || (openIndex > closeIndex))
      {
        sb.append(source.substring(startIndex));
        break;
      }
      sb.append(source.substring(startIndex, openIndex));
    }
    return sb.toString();
  }

  /**
   * This is a string replacement method.
   */
  public static String replaceString(String source, String oldStr, String newStr)
  {
    StringBuffer sb = new StringBuffer(source.length());
    int sind = 0;
    int cind = 0;
    while ((cind = source.indexOf(oldStr, sind)) != -1)
    {
      sb.append(source.substring(sind, cind));
      sb.append(newStr);
      sind = cind + oldStr.length();
    }
    sb.append(source.substring(sind));
    return sb.toString();
  }

  public static String replaceWildcards(String source, String param, Object[] args)
  {
    String tmp = source;
    for (int i = 0; i < args.length; i++)
    {
      int pos = tmp.indexOf(param);
      if (pos == -1)
        throw new IllegalArgumentException("source '" + source + "' must contain at least "
            + args.length + " params '" + param + "'");

      String arg = args[i] == null ? "null" : args[i].toString();
      tmp = tmp.substring(0, pos) + arg + tmp.substring(pos + 1);
    }
    return tmp;
  }

  /**
   * Get byte array from hex string
   */
  public static byte[] toByteArray(String hexString)
  {
    int arrLength = hexString.length() >> 1;
    byte buff[] = new byte[arrLength];
    for (int i = 0; i < arrLength; i++)
    {
      int index = i << 1;
      String digit = hexString.substring(index, index + 2);
      buff[i] = (byte) Integer.parseInt(digit, 16);
    }
    return buff;
  }

  /**
   * Append hex string from byte to StringBuffer
   */
  public static void appendHexString(StringBuffer buffer, byte data)
  {
    int positive = data < 0 ? ~data : data;
    buffer.append(HEX_DIGITS[positive >> 4]);
    buffer.append(HEX_DIGITS[positive & 0xf]);
  }

  /**
   * Get hex string from byte
   */
  public static String toHexString(byte data)
  {
    StringBuffer buffer = new StringBuffer();
    appendHexString(buffer, data);
    return buffer.toString();
  }

  /**
   * Get hex string from byte array
   */
  public static String toHexString(byte[] data)
  {
    StringBuffer buffer = new StringBuffer();
    for (int i = 0; i < data.length; i++)
    {
      appendHexString(buffer, data[i]);
      buffer.append(' ');
    }

    return buffer.toString();
  }

  public static String toHexString(ByteBuffer buffer)
  {
    StringBuffer line = new StringBuffer();

    while (buffer.hasRemaining())
    {
      byte dec = buffer.get();
      StringHelper.appendHexString(line, dec);
      line.append(' ');
    }

    return line.toString();
  }

  /**
   * Append hex string from byte to StringBuffer
   */
  public static void appendUTF8String(StringBuffer buffer, byte data, boolean flat)
  {
    if (32 <= data && data < 127)
    {
      char c = UTF8_CHARS.charAt(data);
      buffer.append(c);
    }
    else
    {
      if (!flat)
      {
        buffer.append(".");
      }
    }
  }

  /**
   * Get hex string from byte
   */
  public static String toUTF8String(byte data, boolean flat)
  {
    StringBuffer buffer = new StringBuffer();
    appendUTF8String(buffer, data, flat);
    return buffer.toString();
  }

  /**
   * Get hex string from byte array
   */
  public static String toUTF8String(byte[] data, boolean flat)
  {
    StringBuffer buffer = new StringBuffer();
    for (int i = 0; i < data.length; i++)
    {
      appendUTF8String(buffer, data[i], flat);
    }

    return buffer.toString();
  }

  public static String toUTF8String(ByteBuffer buffer, boolean flat)
  {
    StringBuffer line = new StringBuffer();

    while (buffer.hasRemaining())
    {
      byte dec = buffer.get();
      StringHelper.appendUTF8String(line, dec, flat);
    }

    return line.toString();
  }

  public static boolean parseBoolean(String str) throws NumberFormatException
  {
    if (str.equals("true")) return true;
    if (str.equals("false")) return false;
    throw new NumberFormatException("'" + str + "' is neither 'true' nor 'false'");
  }

  public static String implode(Collection collection, String separator)
  {
    if (collection == null) return null;
    if (collection.size() == 0) return "";

    Iterator iter = collection.iterator();
    StringBuffer result = new StringBuffer(iter.next().toString());

    while (iter.hasNext())
    {
      if (separator != null) result.append(separator);
      result.append(iter.next().toString());
    }

    return result.toString();
  }

  public static String implode(Object[] array, String separator)
  {
    if (array == null) return null;
    if (array.length == 0) return "";

    StringBuffer result = new StringBuffer(array[0].toString());

    for (int i = 1; i < array.length; i++)
    {
      if (separator != null) result.append(separator);
      result.append(array[i].toString());
    }

    return result.toString();
  }

  public static int getChoice(String str, String[] choices)
  {
    if (choices == null) throw new IllegalArgumentException("choices should be non-null");

    for (int i = 0; i < choices.length; i++)
    {
      if ((str == null && choices[i] == null) || str.equals(choices[i]))
      {
        return i;
      }
    }

    return -1;
  }

  public static List parseName(String name, char separator)
  {
    List result = new ArrayList();
    StringBuffer currentWord = new StringBuffer();

    int length = name.length();
    boolean lastIsLower = false;

    for (int index = 0; index < length; index++)
    {
      char curChar = name.charAt(index);
      if (Character.isUpperCase(curChar) || (!lastIsLower && Character.isDigit(curChar))
          || curChar == separator)
      {
        if (lastIsLower || curChar == separator)
        {
          result.add(currentWord.toString());
          currentWord = new StringBuffer();
        }
        lastIsLower = false;
      }
      else
      {
        if (!lastIsLower)
        {
          int currentWordLength = currentWord.length();
          if (currentWordLength > 1)
          {
            char lastChar = currentWord.charAt(--currentWordLength);
            currentWord.setLength(currentWordLength);
            result.add(currentWord.toString());
            currentWord = new StringBuffer();
            currentWord.append(lastChar);
          }
        }
        lastIsLower = true;
      }
      if (curChar != separator)
      {
        currentWord.append(curChar);
      }
    }

    result.add(currentWord.toString());
    return result;
  }

  /**
   * @param text
   */
  public static String firstToLower(String text)
  {
    if (text == null || text.length() == 0) return text;
    if (Character.isUpperCase(text.charAt(0)))
    {
      return text.substring(0, 1).toLowerCase() + text.substring(1);
    }
    return text;
  }

  /**
   * @param text
   */
  public static String firstToUpper(String text)
  {
    if (text == null || text.length() == 0) return text;
    if (Character.isLowerCase(text.charAt(0)))
    {
      return text.substring(0, 1).toUpperCase() + text.substring(1);
    }
    return text;
  }

  public static int toInt(String intValue, int defaultValue)
  {
    try
    {
      return Integer.valueOf(intValue).intValue();
    }
    catch (Exception e)
    {
      return defaultValue;
    }
  }

  public static boolean equals(Object obj1, Object obj2)
  {
    if (obj1 == null) return obj2 == null;
    return obj1.equals(obj2);
  }

  public static String formatNull(String str, String nullReplacement)
  {
    return str == null ? nullReplacement : str;
  }

  public static String toNonNull(String str)
  {
    return formatNull(str, "");
  }
}

Back to the top