1 /*
2 * Copyright (C) 2014 jsonwebtoken.io
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package io.jsonwebtoken.lang;
17
18 import java.nio.charset.Charset;
19 import java.util.ArrayList;
20 import java.util.Arrays;
21 import java.util.Collection;
22 import java.util.Enumeration;
23 import java.util.Iterator;
24 import java.util.LinkedList;
25 import java.util.List;
26 import java.util.Locale;
27 import java.util.Properties;
28 import java.util.Set;
29 import java.util.StringTokenizer;
30 import java.util.TreeSet;
31
32 public final class Strings {
33
34 private static final Strings INSTANCE = new Strings(); //for code coverage
35
36 private static final String FOLDER_SEPARATOR = "/";
37
38 private static final String WINDOWS_FOLDER_SEPARATOR = "\\";
39
40 private static final String TOP_PATH = "..";
41
42 private static final String CURRENT_PATH = ".";
43
44 private static final char EXTENSION_SEPARATOR = '.';
45
46 public static final Charset UTF_8 = Charset.forName("UTF-8");
47
48 private Strings(){}
49
50 //---------------------------------------------------------------------
51 // General convenience methods for working with Strings
52 //---------------------------------------------------------------------
53
54 /**
55 * Check that the given CharSequence is neither <code>null</code> nor of length 0.
56 * Note: Will return <code>true</code> for a CharSequence that purely consists of whitespace.
57 * <p><pre>
58 * Strings.hasLength(null) = false
59 * Strings.hasLength("") = false
60 * Strings.hasLength(" ") = true
61 * Strings.hasLength("Hello") = true
62 * </pre>
63 * @param str the CharSequence to check (may be <code>null</code>)
64 * @return <code>true</code> if the CharSequence is not null and has length
65 * @see #hasText(String)
66 */
67 public static boolean hasLength(CharSequence str) {
68 return (str != null && str.length() > 0);
69 }
70
71 /**
72 * Check that the given String is neither <code>null</code> nor of length 0.
73 * Note: Will return <code>true</code> for a String that purely consists of whitespace.
74 * @param str the String to check (may be <code>null</code>)
75 * @return <code>true</code> if the String is not null and has length
76 * @see #hasLength(CharSequence)
77 */
78 public static boolean hasLength(String str) {
79 return hasLength((CharSequence) str);
80 }
81
82 /**
83 * Check whether the given CharSequence has actual text.
84 * More specifically, returns <code>true</code> if the string not <code>null</code>,
85 * its length is greater than 0, and it contains at least one non-whitespace character.
86 * <p><pre>
87 * Strings.hasText(null) = false
88 * Strings.hasText("") = false
89 * Strings.hasText(" ") = false
90 * Strings.hasText("12345") = true
91 * Strings.hasText(" 12345 ") = true
92 * </pre>
93 * @param str the CharSequence to check (may be <code>null</code>)
94 * @return <code>true</code> if the CharSequence is not <code>null</code>,
95 * its length is greater than 0, and it does not contain whitespace only
96 * @see java.lang.Character#isWhitespace
97 */
98 public static boolean hasText(CharSequence str) {
99 if (!hasLength(str)) {
100 return false;
101 }
102 int strLen = str.length();
103 for (int i = 0; i < strLen; i++) {
104 if (!Character.isWhitespace(str.charAt(i))) {
105 return true;
106 }
107 }
108 return false;
109 }
110
111 /**
112 * Check whether the given String has actual text.
113 * More specifically, returns <code>true</code> if the string not <code>null</code>,
114 * its length is greater than 0, and it contains at least one non-whitespace character.
115 * @param str the String to check (may be <code>null</code>)
116 * @return <code>true</code> if the String is not <code>null</code>, its length is
117 * greater than 0, and it does not contain whitespace only
118 * @see #hasText(CharSequence)
119 */
120 public static boolean hasText(String str) {
121 return hasText((CharSequence) str);
122 }
123
124 /**
125 * Check whether the given CharSequence contains any whitespace characters.
126 * @param str the CharSequence to check (may be <code>null</code>)
127 * @return <code>true</code> if the CharSequence is not empty and
128 * contains at least 1 whitespace character
129 * @see java.lang.Character#isWhitespace
130 */
131 public static boolean containsWhitespace(CharSequence str) {
132 if (!hasLength(str)) {
133 return false;
134 }
135 int strLen = str.length();
136 for (int i = 0; i < strLen; i++) {
137 if (Character.isWhitespace(str.charAt(i))) {
138 return true;
139 }
140 }
141 return false;
142 }
143
144 /**
145 * Check whether the given String contains any whitespace characters.
146 * @param str the String to check (may be <code>null</code>)
147 * @return <code>true</code> if the String is not empty and
148 * contains at least 1 whitespace character
149 * @see #containsWhitespace(CharSequence)
150 */
151 public static boolean containsWhitespace(String str) {
152 return containsWhitespace((CharSequence) str);
153 }
154
155 /**
156 * Trim leading and trailing whitespace from the given String.
157 * @param str the String to check
158 * @return the trimmed String
159 * @see java.lang.Character#isWhitespace
160 */
161 public static String trimWhitespace(String str) {
162 return (String) trimWhitespace((CharSequence)str);
163 }
164
165
166 private static CharSequence trimWhitespace(CharSequence str) {
167 if (!hasLength(str)) {
168 return str;
169 }
170 final int length = str.length();
171
172 int start = 0;
173 while (start < length && Character.isWhitespace(str.charAt(start))) {
174 start++;
175 }
176
177 int end = length;
178 while (start < length && Character.isWhitespace(str.charAt(end - 1))) {
179 end--;
180 }
181
182 return ((start > 0) || (end < length)) ? str.subSequence(start, end) : str;
183 }
184
185 public static String clean(String str) {
186 CharSequence result = clean((CharSequence) str);
187
188 return result!=null?result.toString():null;
189 }
190
191 public static CharSequence clean(CharSequence str) {
192 str = trimWhitespace(str);
193 if (!hasLength(str)) {
194 return null;
195 }
196 return str;
197 }
198
199 /**
200 * Trim <i>all</i> whitespace from the given String:
201 * leading, trailing, and inbetween characters.
202 * @param str the String to check
203 * @return the trimmed String
204 * @see java.lang.Character#isWhitespace
205 */
206 public static String trimAllWhitespace(String str) {
207 if (!hasLength(str)) {
208 return str;
209 }
210 StringBuilder sb = new StringBuilder(str);
211 int index = 0;
212 while (sb.length() > index) {
213 if (Character.isWhitespace(sb.charAt(index))) {
214 sb.deleteCharAt(index);
215 }
216 else {
217 index++;
218 }
219 }
220 return sb.toString();
221 }
222
223 /**
224 * Trim leading whitespace from the given String.
225 * @param str the String to check
226 * @return the trimmed String
227 * @see java.lang.Character#isWhitespace
228 */
229 public static String trimLeadingWhitespace(String str) {
230 if (!hasLength(str)) {
231 return str;
232 }
233 StringBuilder sb = new StringBuilder(str);
234 while (sb.length() > 0 && Character.isWhitespace(sb.charAt(0))) {
235 sb.deleteCharAt(0);
236 }
237 return sb.toString();
238 }
239
240 /**
241 * Trim trailing whitespace from the given String.
242 * @param str the String to check
243 * @return the trimmed String
244 * @see java.lang.Character#isWhitespace
245 */
246 public static String trimTrailingWhitespace(String str) {
247 if (!hasLength(str)) {
248 return str;
249 }
250 StringBuilder sb = new StringBuilder(str);
251 while (sb.length() > 0 && Character.isWhitespace(sb.charAt(sb.length() - 1))) {
252 sb.deleteCharAt(sb.length() - 1);
253 }
254 return sb.toString();
255 }
256
257 /**
258 * Trim all occurences of the supplied leading character from the given String.
259 * @param str the String to check
260 * @param leadingCharacter the leading character to be trimmed
261 * @return the trimmed String
262 */
263 public static String trimLeadingCharacter(String str, char leadingCharacter) {
264 if (!hasLength(str)) {
265 return str;
266 }
267 StringBuilder sb = new StringBuilder(str);
268 while (sb.length() > 0 && sb.charAt(0) == leadingCharacter) {
269 sb.deleteCharAt(0);
270 }
271 return sb.toString();
272 }
273
274 /**
275 * Trim all occurences of the supplied trailing character from the given String.
276 * @param str the String to check
277 * @param trailingCharacter the trailing character to be trimmed
278 * @return the trimmed String
279 */
280 public static String trimTrailingCharacter(String str, char trailingCharacter) {
281 if (!hasLength(str)) {
282 return str;
283 }
284 StringBuilder sb = new StringBuilder(str);
285 while (sb.length() > 0 && sb.charAt(sb.length() - 1) == trailingCharacter) {
286 sb.deleteCharAt(sb.length() - 1);
287 }
288 return sb.toString();
289 }
290
291
292 /**
293 * Test if the given String starts with the specified prefix,
294 * ignoring upper/lower case.
295 * @param str the String to check
296 * @param prefix the prefix to look for
297 * @see java.lang.String#startsWith
298 */
299 public static boolean startsWithIgnoreCase(String str, String prefix) {
300 if (str == null || prefix == null) {
301 return false;
302 }
303 if (str.startsWith(prefix)) {
304 return true;
305 }
306 if (str.length() < prefix.length()) {
307 return false;
308 }
309 String lcStr = str.substring(0, prefix.length()).toLowerCase();
310 String lcPrefix = prefix.toLowerCase();
311 return lcStr.equals(lcPrefix);
312 }
313
314 /**
315 * Test if the given String ends with the specified suffix,
316 * ignoring upper/lower case.
317 * @param str the String to check
318 * @param suffix the suffix to look for
319 * @see java.lang.String#endsWith
320 */
321 public static boolean endsWithIgnoreCase(String str, String suffix) {
322 if (str == null || suffix == null) {
323 return false;
324 }
325 if (str.endsWith(suffix)) {
326 return true;
327 }
328 if (str.length() < suffix.length()) {
329 return false;
330 }
331
332 String lcStr = str.substring(str.length() - suffix.length()).toLowerCase();
333 String lcSuffix = suffix.toLowerCase();
334 return lcStr.equals(lcSuffix);
335 }
336
337 /**
338 * Test whether the given string matches the given substring
339 * at the given index.
340 * @param str the original string (or StringBuilder)
341 * @param index the index in the original string to start matching against
342 * @param substring the substring to match at the given index
343 */
344 public static boolean substringMatch(CharSequence str, int index, CharSequence substring) {
345 for (int j = 0; j < substring.length(); j++) {
346 int i = index + j;
347 if (i >= str.length() || str.charAt(i) != substring.charAt(j)) {
348 return false;
349 }
350 }
351 return true;
352 }
353
354 /**
355 * Count the occurrences of the substring in string s.
356 * @param str string to search in. Return 0 if this is null.
357 * @param sub string to search for. Return 0 if this is null.
358 */
359 public static int countOccurrencesOf(String str, String sub) {
360 if (str == null || sub == null || str.length() == 0 || sub.length() == 0) {
361 return 0;
362 }
363 int count = 0;
364 int pos = 0;
365 int idx;
366 while ((idx = str.indexOf(sub, pos)) != -1) {
367 ++count;
368 pos = idx + sub.length();
369 }
370 return count;
371 }
372
373 /**
374 * Replace all occurences of a substring within a string with
375 * another string.
376 * @param inString String to examine
377 * @param oldPattern String to replace
378 * @param newPattern String to insert
379 * @return a String with the replacements
380 */
381 public static String replace(String inString, String oldPattern, String newPattern) {
382 if (!hasLength(inString) || !hasLength(oldPattern) || newPattern == null) {
383 return inString;
384 }
385 StringBuilder sb = new StringBuilder();
386 int pos = 0; // our position in the old string
387 int index = inString.indexOf(oldPattern);
388 // the index of an occurrence we've found, or -1
389 int patLen = oldPattern.length();
390 while (index >= 0) {
391 sb.append(inString.substring(pos, index));
392 sb.append(newPattern);
393 pos = index + patLen;
394 index = inString.indexOf(oldPattern, pos);
395 }
396 sb.append(inString.substring(pos));
397 // remember to append any characters to the right of a match
398 return sb.toString();
399 }
400
401 /**
402 * Delete all occurrences of the given substring.
403 * @param inString the original String
404 * @param pattern the pattern to delete all occurrences of
405 * @return the resulting String
406 */
407 public static String delete(String inString, String pattern) {
408 return replace(inString, pattern, "");
409 }
410
411 /**
412 * Delete any character in a given String.
413 * @param inString the original String
414 * @param charsToDelete a set of characters to delete.
415 * E.g. "az\n" will delete 'a's, 'z's and new lines.
416 * @return the resulting String
417 */
418 public static String deleteAny(String inString, String charsToDelete) {
419 if (!hasLength(inString) || !hasLength(charsToDelete)) {
420 return inString;
421 }
422 StringBuilder sb = new StringBuilder();
423 for (int i = 0; i < inString.length(); i++) {
424 char c = inString.charAt(i);
425 if (charsToDelete.indexOf(c) == -1) {
426 sb.append(c);
427 }
428 }
429 return sb.toString();
430 }
431
432
433 //---------------------------------------------------------------------
434 // Convenience methods for working with formatted Strings
435 //---------------------------------------------------------------------
436
437 /**
438 * Quote the given String with single quotes.
439 * @param str the input String (e.g. "myString")
440 * @return the quoted String (e.g. "'myString'"),
441 * or <code>null</code> if the input was <code>null</code>
442 */
443 public static String quote(String str) {
444 return (str != null ? "'" + str + "'" : null);
445 }
446
447 /**
448 * Turn the given Object into a String with single quotes
449 * if it is a String; keeping the Object as-is else.
450 * @param obj the input Object (e.g. "myString")
451 * @return the quoted String (e.g. "'myString'"),
452 * or the input object as-is if not a String
453 */
454 public static Object quoteIfString(Object obj) {
455 return (obj instanceof String ? quote((String) obj) : obj);
456 }
457
458 /**
459 * Unqualify a string qualified by a '.' dot character. For example,
460 * "this.name.is.qualified", returns "qualified".
461 * @param qualifiedName the qualified name
462 */
463 public static String unqualify(String qualifiedName) {
464 return unqualify(qualifiedName, '.');
465 }
466
467 /**
468 * Unqualify a string qualified by a separator character. For example,
469 * "this:name:is:qualified" returns "qualified" if using a ':' separator.
470 * @param qualifiedName the qualified name
471 * @param separator the separator
472 */
473 public static String unqualify(String qualifiedName, char separator) {
474 return qualifiedName.substring(qualifiedName.lastIndexOf(separator) + 1);
475 }
476
477 /**
478 * Capitalize a <code>String</code>, changing the first letter to
479 * upper case as per {@link Character#toUpperCase(char)}.
480 * No other letters are changed.
481 * @param str the String to capitalize, may be <code>null</code>
482 * @return the capitalized String, <code>null</code> if null
483 */
484 public static String capitalize(String str) {
485 return changeFirstCharacterCase(str, true);
486 }
487
488 /**
489 * Uncapitalize a <code>String</code>, changing the first letter to
490 * lower case as per {@link Character#toLowerCase(char)}.
491 * No other letters are changed.
492 * @param str the String to uncapitalize, may be <code>null</code>
493 * @return the uncapitalized String, <code>null</code> if null
494 */
495 public static String uncapitalize(String str) {
496 return changeFirstCharacterCase(str, false);
497 }
498
499 private static String changeFirstCharacterCase(String str, boolean capitalize) {
500 if (str == null || str.length() == 0) {
501 return str;
502 }
503 StringBuilder sb = new StringBuilder(str.length());
504 if (capitalize) {
505 sb.append(Character.toUpperCase(str.charAt(0)));
506 }
507 else {
508 sb.append(Character.toLowerCase(str.charAt(0)));
509 }
510 sb.append(str.substring(1));
511 return sb.toString();
512 }
513
514 /**
515 * Extract the filename from the given path,
516 * e.g. "mypath/myfile.txt" -> "myfile.txt".
517 * @param path the file path (may be <code>null</code>)
518 * @return the extracted filename, or <code>null</code> if none
519 */
520 public static String getFilename(String path) {
521 if (path == null) {
522 return null;
523 }
524 int separatorIndex = path.lastIndexOf(FOLDER_SEPARATOR);
525 return (separatorIndex != -1 ? path.substring(separatorIndex + 1) : path);
526 }
527
528 /**
529 * Extract the filename extension from the given path,
530 * e.g. "mypath/myfile.txt" -> "txt".
531 * @param path the file path (may be <code>null</code>)
532 * @return the extracted filename extension, or <code>null</code> if none
533 */
534 public static String getFilenameExtension(String path) {
535 if (path == null) {
536 return null;
537 }
538 int extIndex = path.lastIndexOf(EXTENSION_SEPARATOR);
539 if (extIndex == -1) {
540 return null;
541 }
542 int folderIndex = path.lastIndexOf(FOLDER_SEPARATOR);
543 if (folderIndex > extIndex) {
544 return null;
545 }
546 return path.substring(extIndex + 1);
547 }
548
549 /**
550 * Strip the filename extension from the given path,
551 * e.g. "mypath/myfile.txt" -> "mypath/myfile".
552 * @param path the file path (may be <code>null</code>)
553 * @return the path with stripped filename extension,
554 * or <code>null</code> if none
555 */
556 public static String stripFilenameExtension(String path) {
557 if (path == null) {
558 return null;
559 }
560 int extIndex = path.lastIndexOf(EXTENSION_SEPARATOR);
561 if (extIndex == -1) {
562 return path;
563 }
564 int folderIndex = path.lastIndexOf(FOLDER_SEPARATOR);
565 if (folderIndex > extIndex) {
566 return path;
567 }
568 return path.substring(0, extIndex);
569 }
570
571 /**
572 * Apply the given relative path to the given path,
573 * assuming standard Java folder separation (i.e. "/" separators).
574 * @param path the path to start from (usually a full file path)
575 * @param relativePath the relative path to apply
576 * (relative to the full file path above)
577 * @return the full file path that results from applying the relative path
578 */
579 public static String applyRelativePath(String path, String relativePath) {
580 int separatorIndex = path.lastIndexOf(FOLDER_SEPARATOR);
581 if (separatorIndex != -1) {
582 String newPath = path.substring(0, separatorIndex);
583 if (!relativePath.startsWith(FOLDER_SEPARATOR)) {
584 newPath += FOLDER_SEPARATOR;
585 }
586 return newPath + relativePath;
587 }
588 else {
589 return relativePath;
590 }
591 }
592
593 /**
594 * Normalize the path by suppressing sequences like "path/.." and
595 * inner simple dots.
596 * <p>The result is convenient for path comparison. For other uses,
597 * notice that Windows separators ("\") are replaced by simple slashes.
598 * @param path the original path
599 * @return the normalized path
600 */
601 public static String cleanPath(String path) {
602 if (path == null) {
603 return null;
604 }
605 String pathToUse = replace(path, WINDOWS_FOLDER_SEPARATOR, FOLDER_SEPARATOR);
606
607 // Strip prefix from path to analyze, to not treat it as part of the
608 // first path element. This is necessary to correctly parse paths like
609 // "file:core/../core/io/Resource.class", where the ".." should just
610 // strip the first "core" directory while keeping the "file:" prefix.
611 int prefixIndex = pathToUse.indexOf(":");
612 String prefix = "";
613 if (prefixIndex != -1) {
614 prefix = pathToUse.substring(0, prefixIndex + 1);
615 pathToUse = pathToUse.substring(prefixIndex + 1);
616 }
617 if (pathToUse.startsWith(FOLDER_SEPARATOR)) {
618 prefix = prefix + FOLDER_SEPARATOR;
619 pathToUse = pathToUse.substring(1);
620 }
621
622 String[] pathArray = delimitedListToStringArray(pathToUse, FOLDER_SEPARATOR);
623 List<String> pathElements = new LinkedList<String>();
624 int tops = 0;
625
626 for (int i = pathArray.length - 1; i >= 0; i--) {
627 String element = pathArray[i];
628 if (CURRENT_PATH.equals(element)) {
629 // Points to current directory - drop it.
630 }
631 else if (TOP_PATH.equals(element)) {
632 // Registering top path found.
633 tops++;
634 }
635 else {
636 if (tops > 0) {
637 // Merging path element with element corresponding to top path.
638 tops--;
639 }
640 else {
641 // Normal path element found.
642 pathElements.add(0, element);
643 }
644 }
645 }
646
647 // Remaining top paths need to be retained.
648 for (int i = 0; i < tops; i++) {
649 pathElements.add(0, TOP_PATH);
650 }
651
652 return prefix + collectionToDelimitedString(pathElements, FOLDER_SEPARATOR);
653 }
654
655 /**
656 * Compare two paths after normalization of them.
657 * @param path1 first path for comparison
658 * @param path2 second path for comparison
659 * @return whether the two paths are equivalent after normalization
660 */
661 public static boolean pathEquals(String path1, String path2) {
662 return cleanPath(path1).equals(cleanPath(path2));
663 }
664
665 /**
666 * Parse the given <code>localeString</code> value into a {@link java.util.Locale}.
667 * <p>This is the inverse operation of {@link java.util.Locale#toString Locale's toString}.
668 * @param localeString the locale string, following <code>Locale's</code>
669 * <code>toString()</code> format ("en", "en_UK", etc);
670 * also accepts spaces as separators, as an alternative to underscores
671 * @return a corresponding <code>Locale</code> instance
672 */
673 public static Locale parseLocaleString(String localeString) {
674 String[] parts = tokenizeToStringArray(localeString, "_ ", false, false);
675 String language = (parts.length > 0 ? parts[0] : "");
676 String country = (parts.length > 1 ? parts[1] : "");
677 validateLocalePart(language);
678 validateLocalePart(country);
679 String variant = "";
680 if (parts.length >= 2) {
681 // There is definitely a variant, and it is everything after the country
682 // code sans the separator between the country code and the variant.
683 int endIndexOfCountryCode = localeString.indexOf(country) + country.length();
684 // Strip off any leading '_' and whitespace, what's left is the variant.
685 variant = trimLeadingWhitespace(localeString.substring(endIndexOfCountryCode));
686 if (variant.startsWith("_")) {
687 variant = trimLeadingCharacter(variant, '_');
688 }
689 }
690 return (language.length() > 0 ? new Locale(language, country, variant) : null);
691 }
692
693 private static void validateLocalePart(String localePart) {
694 for (int i = 0; i < localePart.length(); i++) {
695 char ch = localePart.charAt(i);
696 if (ch != '_' && ch != ' ' && !Character.isLetterOrDigit(ch)) {
697 throw new IllegalArgumentException(
698 "Locale part \"" + localePart + "\" contains invalid characters");
699 }
700 }
701 }
702
703 /**
704 * Determine the RFC 3066 compliant language tag,
705 * as used for the HTTP "Accept-Language" header.
706 * @param locale the Locale to transform to a language tag
707 * @return the RFC 3066 compliant language tag as String
708 */
709 public static String toLanguageTag(Locale locale) {
710 return locale.getLanguage() + (hasText(locale.getCountry()) ? "-" + locale.getCountry() : "");
711 }
712
713
714 //---------------------------------------------------------------------
715 // Convenience methods for working with String arrays
716 //---------------------------------------------------------------------
717
718 /**
719 * Append the given String to the given String array, returning a new array
720 * consisting of the input array contents plus the given String.
721 * @param array the array to append to (can be <code>null</code>)
722 * @param str the String to append
723 * @return the new array (never <code>null</code>)
724 */
725 public static String[] addStringToArray(String[] array, String str) {
726 if (Objects.isEmpty(array)) {
727 return new String[] {str};
728 }
729 String[] newArr = new String[array.length + 1];
730 System.arraycopy(array, 0, newArr, 0, array.length);
731 newArr[array.length] = str;
732 return newArr;
733 }
734
735 /**
736 * Concatenate the given String arrays into one,
737 * with overlapping array elements included twice.
738 * <p>The order of elements in the original arrays is preserved.
739 * @param array1 the first array (can be <code>null</code>)
740 * @param array2 the second array (can be <code>null</code>)
741 * @return the new array (<code>null</code> if both given arrays were <code>null</code>)
742 */
743 public static String[] concatenateStringArrays(String[] array1, String[] array2) {
744 if (Objects.isEmpty(array1)) {
745 return array2;
746 }
747 if (Objects.isEmpty(array2)) {
748 return array1;
749 }
750 String[] newArr = new String[array1.length + array2.length];
751 System.arraycopy(array1, 0, newArr, 0, array1.length);
752 System.arraycopy(array2, 0, newArr, array1.length, array2.length);
753 return newArr;
754 }
755
756 /**
757 * Merge the given String arrays into one, with overlapping
758 * array elements only included once.
759 * <p>The order of elements in the original arrays is preserved
760 * (with the exception of overlapping elements, which are only
761 * included on their first occurrence).
762 * @param array1 the first array (can be <code>null</code>)
763 * @param array2 the second array (can be <code>null</code>)
764 * @return the new array (<code>null</code> if both given arrays were <code>null</code>)
765 */
766 public static String[] mergeStringArrays(String[] array1, String[] array2) {
767 if (Objects.isEmpty(array1)) {
768 return array2;
769 }
770 if (Objects.isEmpty(array2)) {
771 return array1;
772 }
773 List<String> result = new ArrayList<String>();
774 result.addAll(Arrays.asList(array1));
775 for (String str : array2) {
776 if (!result.contains(str)) {
777 result.add(str);
778 }
779 }
780 return toStringArray(result);
781 }
782
783 /**
784 * Turn given source String array into sorted array.
785 * @param array the source array
786 * @return the sorted array (never <code>null</code>)
787 */
788 public static String[] sortStringArray(String[] array) {
789 if (Objects.isEmpty(array)) {
790 return new String[0];
791 }
792 Arrays.sort(array);
793 return array;
794 }
795
796 /**
797 * Copy the given Collection into a String array.
798 * The Collection must contain String elements only.
799 * @param collection the Collection to copy
800 * @return the String array (<code>null</code> if the passed-in
801 * Collection was <code>null</code>)
802 */
803 public static String[] toStringArray(Collection<String> collection) {
804 if (collection == null) {
805 return null;
806 }
807 return collection.toArray(new String[collection.size()]);
808 }
809
810 /**
811 * Copy the given Enumeration into a String array.
812 * The Enumeration must contain String elements only.
813 * @param enumeration the Enumeration to copy
814 * @return the String array (<code>null</code> if the passed-in
815 * Enumeration was <code>null</code>)
816 */
817 public static String[] toStringArray(Enumeration<String> enumeration) {
818 if (enumeration == null) {
819 return null;
820 }
821 List<String> list = java.util.Collections.list(enumeration);
822 return list.toArray(new String[list.size()]);
823 }
824
825 /**
826 * Trim the elements of the given String array,
827 * calling <code>String.trim()</code> on each of them.
828 * @param array the original String array
829 * @return the resulting array (of the same size) with trimmed elements
830 */
831 public static String[] trimArrayElements(String[] array) {
832 if (Objects.isEmpty(array)) {
833 return new String[0];
834 }
835 String[] result = new String[array.length];
836 for (int i = 0; i < array.length; i++) {
837 String element = array[i];
838 result[i] = (element != null ? element.trim() : null);
839 }
840 return result;
841 }
842
843 /**
844 * Remove duplicate Strings from the given array.
845 * Also sorts the array, as it uses a TreeSet.
846 * @param array the String array
847 * @return an array without duplicates, in natural sort order
848 */
849 public static String[] removeDuplicateStrings(String[] array) {
850 if (Objects.isEmpty(array)) {
851 return array;
852 }
853 Set<String> set = new TreeSet<String>();
854 for (String element : array) {
855 set.add(element);
856 }
857 return toStringArray(set);
858 }
859
860 /**
861 * Split a String at the first occurrence of the delimiter.
862 * Does not include the delimiter in the result.
863 * @param toSplit the string to split
864 * @param delimiter to split the string up with
865 * @return a two element array with index 0 being before the delimiter, and
866 * index 1 being after the delimiter (neither element includes the delimiter);
867 * or <code>null</code> if the delimiter wasn't found in the given input String
868 */
869 public static String[] split(String toSplit, String delimiter) {
870 if (!hasLength(toSplit) || !hasLength(delimiter)) {
871 return null;
872 }
873 int offset = toSplit.indexOf(delimiter);
874 if (offset < 0) {
875 return null;
876 }
877 String beforeDelimiter = toSplit.substring(0, offset);
878 String afterDelimiter = toSplit.substring(offset + delimiter.length());
879 return new String[] {beforeDelimiter, afterDelimiter};
880 }
881
882 /**
883 * Take an array Strings and split each element based on the given delimiter.
884 * A <code>Properties</code> instance is then generated, with the left of the
885 * delimiter providing the key, and the right of the delimiter providing the value.
886 * <p>Will trim both the key and value before adding them to the
887 * <code>Properties</code> instance.
888 * @param array the array to process
889 * @param delimiter to split each element using (typically the equals symbol)
890 * @return a <code>Properties</code> instance representing the array contents,
891 * or <code>null</code> if the array to process was null or empty
892 */
893 public static Properties splitArrayElementsIntoProperties(String[] array, String delimiter) {
894 return splitArrayElementsIntoProperties(array, delimiter, null);
895 }
896
897 /**
898 * Take an array Strings and split each element based on the given delimiter.
899 * A <code>Properties</code> instance is then generated, with the left of the
900 * delimiter providing the key, and the right of the delimiter providing the value.
901 * <p>Will trim both the key and value before adding them to the
902 * <code>Properties</code> instance.
903 * @param array the array to process
904 * @param delimiter to split each element using (typically the equals symbol)
905 * @param charsToDelete one or more characters to remove from each element
906 * prior to attempting the split operation (typically the quotation mark
907 * symbol), or <code>null</code> if no removal should occur
908 * @return a <code>Properties</code> instance representing the array contents,
909 * or <code>null</code> if the array to process was <code>null</code> or empty
910 */
911 public static Properties splitArrayElementsIntoProperties(
912 String[] array, String delimiter, String charsToDelete) {
913
914 if (Objects.isEmpty(array)) {
915 return null;
916 }
917 Properties result = new Properties();
918 for (String element : array) {
919 if (charsToDelete != null) {
920 element = deleteAny(element, charsToDelete);
921 }
922 String[] splittedElement = split(element, delimiter);
923 if (splittedElement == null) {
924 continue;
925 }
926 result.setProperty(splittedElement[0].trim(), splittedElement[1].trim());
927 }
928 return result;
929 }
930
931 /**
932 * Tokenize the given String into a String array via a StringTokenizer.
933 * Trims tokens and omits empty tokens.
934 * <p>The given delimiters string is supposed to consist of any number of
935 * delimiter characters. Each of those characters can be used to separate
936 * tokens. A delimiter is always a single character; for multi-character
937 * delimiters, consider using <code>delimitedListToStringArray</code>
938 * @param str the String to tokenize
939 * @param delimiters the delimiter characters, assembled as String
940 * (each of those characters is individually considered as delimiter).
941 * @return an array of the tokens
942 * @see java.util.StringTokenizer
943 * @see java.lang.String#trim()
944 * @see #delimitedListToStringArray
945 */
946 public static String[] tokenizeToStringArray(String str, String delimiters) {
947 return tokenizeToStringArray(str, delimiters, true, true);
948 }
949
950 /**
951 * Tokenize the given String into a String array via a StringTokenizer.
952 * <p>The given delimiters string is supposed to consist of any number of
953 * delimiter characters. Each of those characters can be used to separate
954 * tokens. A delimiter is always a single character; for multi-character
955 * delimiters, consider using <code>delimitedListToStringArray</code>
956 * @param str the String to tokenize
957 * @param delimiters the delimiter characters, assembled as String
958 * (each of those characters is individually considered as delimiter)
959 * @param trimTokens trim the tokens via String's <code>trim</code>
960 * @param ignoreEmptyTokens omit empty tokens from the result array
961 * (only applies to tokens that are empty after trimming; StringTokenizer
962 * will not consider subsequent delimiters as token in the first place).
963 * @return an array of the tokens (<code>null</code> if the input String
964 * was <code>null</code>)
965 * @see java.util.StringTokenizer
966 * @see java.lang.String#trim()
967 * @see #delimitedListToStringArray
968 */
969 public static String[] tokenizeToStringArray(
970 String str, String delimiters, boolean trimTokens, boolean ignoreEmptyTokens) {
971
972 if (str == null) {
973 return null;
974 }
975 StringTokenizer st = new StringTokenizer(str, delimiters);
976 List<String> tokens = new ArrayList<String>();
977 while (st.hasMoreTokens()) {
978 String token = st.nextToken();
979 if (trimTokens) {
980 token = token.trim();
981 }
982 if (!ignoreEmptyTokens || token.length() > 0) {
983 tokens.add(token);
984 }
985 }
986 return toStringArray(tokens);
987 }
988
989 /**
990 * Take a String which is a delimited list and convert it to a String array.
991 * <p>A single delimiter can consists of more than one character: It will still
992 * be considered as single delimiter string, rather than as bunch of potential
993 * delimiter characters - in contrast to <code>tokenizeToStringArray</code>.
994 * @param str the input String
995 * @param delimiter the delimiter between elements (this is a single delimiter,
996 * rather than a bunch individual delimiter characters)
997 * @return an array of the tokens in the list
998 * @see #tokenizeToStringArray
999 */
1000 public static String[] delimitedListToStringArray(String str, String delimiter) {
1001 return delimitedListToStringArray(str, delimiter, null);
1002 }
1003
1004 /**
1005 * Take a String which is a delimited list and convert it to a String array.
1006 * <p>A single delimiter can consists of more than one character: It will still
1007 * be considered as single delimiter string, rather than as bunch of potential
1008 * delimiter characters - in contrast to <code>tokenizeToStringArray</code>.
1009 * @param str the input String
1010 * @param delimiter the delimiter between elements (this is a single delimiter,
1011 * rather than a bunch individual delimiter characters)
1012 * @param charsToDelete a set of characters to delete. Useful for deleting unwanted
1013 * line breaks: e.g. "\r\n\f" will delete all new lines and line feeds in a String.
1014 * @return an array of the tokens in the list
1015 * @see #tokenizeToStringArray
1016 */
1017 public static String[] delimitedListToStringArray(String str, String delimiter, String charsToDelete) {
1018 if (str == null) {
1019 return new String[0];
1020 }
1021 if (delimiter == null) {
1022 return new String[] {str};
1023 }
1024 List<String> result = new ArrayList<String>();
1025 if ("".equals(delimiter)) {
1026 for (int i = 0; i < str.length(); i++) {
1027 result.add(deleteAny(str.substring(i, i + 1), charsToDelete));
1028 }
1029 }
1030 else {
1031 int pos = 0;
1032 int delPos;
1033 while ((delPos = str.indexOf(delimiter, pos)) != -1) {
1034 result.add(deleteAny(str.substring(pos, delPos), charsToDelete));
1035 pos = delPos + delimiter.length();
1036 }
1037 if (str.length() > 0 && pos <= str.length()) {
1038 // Add rest of String, but not in case of empty input.
1039 result.add(deleteAny(str.substring(pos), charsToDelete));
1040 }
1041 }
1042 return toStringArray(result);
1043 }
1044
1045 /**
1046 * Convert a CSV list into an array of Strings.
1047 * @param str the input String
1048 * @return an array of Strings, or the empty array in case of empty input
1049 */
1050 public static String[] commaDelimitedListToStringArray(String str) {
1051 return delimitedListToStringArray(str, ",");
1052 }
1053
1054 /**
1055 * Convenience method to convert a CSV string list to a set.
1056 * Note that this will suppress duplicates.
1057 * @param str the input String
1058 * @return a Set of String entries in the list
1059 */
1060 public static Set<String> commaDelimitedListToSet(String str) {
1061 Set<String> set = new TreeSet<String>();
1062 String[] tokens = commaDelimitedListToStringArray(str);
1063 for (String token : tokens) {
1064 set.add(token);
1065 }
1066 return set;
1067 }
1068
1069 /**
1070 * Convenience method to return a Collection as a delimited (e.g. CSV)
1071 * String. E.g. useful for <code>toString()</code> implementations.
1072 * @param coll the Collection to display
1073 * @param delim the delimiter to use (probably a ",")
1074 * @param prefix the String to start each element with
1075 * @param suffix the String to end each element with
1076 * @return the delimited String
1077 */
1078 public static String collectionToDelimitedString(Collection<?> coll, String delim, String prefix, String suffix) {
1079 if (Collections.isEmpty(coll)) {
1080 return "";
1081 }
1082 StringBuilder sb = new StringBuilder();
1083 Iterator<?> it = coll.iterator();
1084 while (it.hasNext()) {
1085 sb.append(prefix).append(it.next()).append(suffix);
1086 if (it.hasNext()) {
1087 sb.append(delim);
1088 }
1089 }
1090 return sb.toString();
1091 }
1092
1093 /**
1094 * Convenience method to return a Collection as a delimited (e.g. CSV)
1095 * String. E.g. useful for <code>toString()</code> implementations.
1096 * @param coll the Collection to display
1097 * @param delim the delimiter to use (probably a ",")
1098 * @return the delimited String
1099 */
1100 public static String collectionToDelimitedString(Collection<?> coll, String delim) {
1101 return collectionToDelimitedString(coll, delim, "", "");
1102 }
1103
1104 /**
1105 * Convenience method to return a Collection as a CSV String.
1106 * E.g. useful for <code>toString()</code> implementations.
1107 * @param coll the Collection to display
1108 * @return the delimited String
1109 */
1110 public static String collectionToCommaDelimitedString(Collection<?> coll) {
1111 return collectionToDelimitedString(coll, ",");
1112 }
1113
1114 /**
1115 * Convenience method to return a String array as a delimited (e.g. CSV)
1116 * String. E.g. useful for <code>toString()</code> implementations.
1117 * @param arr the array to display
1118 * @param delim the delimiter to use (probably a ",")
1119 * @return the delimited String
1120 */
1121 public static String arrayToDelimitedString(Object[] arr, String delim) {
1122 if (Objects.isEmpty(arr)) {
1123 return "";
1124 }
1125 if (arr.length == 1) {
1126 return Objects.nullSafeToString(arr[0]);
1127 }
1128 StringBuilder sb = new StringBuilder();
1129 for (int i = 0; i < arr.length; i++) {
1130 if (i > 0) {
1131 sb.append(delim);
1132 }
1133 sb.append(arr[i]);
1134 }
1135 return sb.toString();
1136 }
1137
1138 /**
1139 * Convenience method to return a String array as a CSV String.
1140 * E.g. useful for <code>toString()</code> implementations.
1141 * @param arr the array to display
1142 * @return the delimited String
1143 */
1144 public static String arrayToCommaDelimitedString(Object[] arr) {
1145 return arrayToDelimitedString(arr, ",");
1146 }
1147
1148 }
1149
1150