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