+/*\r
+ * Copyright 2002-2008 the original author or authors.\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ */\r
+\r
+package org.argeo.slc.osgiboot.internal.springutil;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Arrays;\r
+import java.util.Collection;\r
+import java.util.Collections;\r
+import java.util.Enumeration;\r
+import java.util.Iterator;\r
+import java.util.LinkedList;\r
+import java.util.List;\r
+import java.util.Locale;\r
+import java.util.Properties;\r
+import java.util.Set;\r
+import java.util.StringTokenizer;\r
+import java.util.TreeSet;\r
+\r
+/**\r
+ * Miscellaneous {@link String} utility methods.\r
+ *\r
+ * <p>Mainly for internal use within the framework; consider\r
+ * <a href="http://jakarta.apache.org/commons/lang/">Jakarta's Commons Lang</a>\r
+ * for a more comprehensive suite of String utilities.\r
+ *\r
+ * <p>This class delivers some simple functionality that should really\r
+ * be provided by the core Java <code>String</code> and {@link StringBuffer}\r
+ * classes, such as the ability to {@link #replace} all occurrences of a given\r
+ * substring in a target string. It also provides easy-to-use methods to convert\r
+ * between delimited strings, such as CSV strings, and collections and arrays.\r
+ *\r
+ * @author Rod Johnson\r
+ * @author Juergen Hoeller\r
+ * @author Keith Donald\r
+ * @author Rob Harrop\r
+ * @author Rick Evans\r
+ * @since 16 April 2001\r
+ * @see org.apache.commons.lang.StringUtils\r
+ */\r
+public abstract class StringUtils {\r
+\r
+ private static final String FOLDER_SEPARATOR = "/";\r
+\r
+ private static final String WINDOWS_FOLDER_SEPARATOR = "\\";\r
+\r
+ private static final String TOP_PATH = "..";\r
+\r
+ private static final String CURRENT_PATH = ".";\r
+\r
+ private static final char EXTENSION_SEPARATOR = '.';\r
+\r
+\r
+ //---------------------------------------------------------------------\r
+ // General convenience methods for working with Strings\r
+ //---------------------------------------------------------------------\r
+\r
+ /**\r
+ * Check that the given CharSequence is neither <code>null</code> nor of length 0.\r
+ * Note: Will return <code>true</code> for a CharSequence that purely consists of whitespace.\r
+ * <p><pre>\r
+ * StringUtils.hasLength(null) = false\r
+ * StringUtils.hasLength("") = false\r
+ * StringUtils.hasLength(" ") = true\r
+ * StringUtils.hasLength("Hello") = true\r
+ * </pre>\r
+ * @param str the CharSequence to check (may be <code>null</code>)\r
+ * @return <code>true</code> if the CharSequence is not null and has length\r
+ * @see #hasText(String)\r
+ */\r
+ public static boolean hasLength(CharSequence str) {\r
+ return (str != null && str.length() > 0);\r
+ }\r
+\r
+ /**\r
+ * Check that the given String is neither <code>null</code> nor of length 0.\r
+ * Note: Will return <code>true</code> for a String that purely consists of whitespace.\r
+ * @param str the String to check (may be <code>null</code>)\r
+ * @return <code>true</code> if the String is not null and has length\r
+ * @see #hasLength(CharSequence)\r
+ */\r
+ public static boolean hasLength(String str) {\r
+ return hasLength((CharSequence) str);\r
+ }\r
+\r
+ /**\r
+ * Check whether the given CharSequence has actual text.\r
+ * More specifically, returns <code>true</code> if the string not <code>null</code>,\r
+ * its length is greater than 0, and it contains at least one non-whitespace character.\r
+ * <p><pre>\r
+ * StringUtils.hasText(null) = false\r
+ * StringUtils.hasText("") = false\r
+ * StringUtils.hasText(" ") = false\r
+ * StringUtils.hasText("12345") = true\r
+ * StringUtils.hasText(" 12345 ") = true\r
+ * </pre>\r
+ * @param str the CharSequence to check (may be <code>null</code>)\r
+ * @return <code>true</code> if the CharSequence is not <code>null</code>,\r
+ * its length is greater than 0, and it does not contain whitespace only\r
+ * @see java.lang.Character#isWhitespace\r
+ */\r
+ public static boolean hasText(CharSequence str) {\r
+ if (!hasLength(str)) {\r
+ return false;\r
+ }\r
+ int strLen = str.length();\r
+ for (int i = 0; i < strLen; i++) {\r
+ if (!Character.isWhitespace(str.charAt(i))) {\r
+ return true;\r
+ }\r
+ }\r
+ return false;\r
+ }\r
+\r
+ /**\r
+ * Check whether the given String has actual text.\r
+ * More specifically, returns <code>true</code> if the string not <code>null</code>,\r
+ * its length is greater than 0, and it contains at least one non-whitespace character.\r
+ * @param str the String to check (may be <code>null</code>)\r
+ * @return <code>true</code> if the String is not <code>null</code>, its length is\r
+ * greater than 0, and it does not contain whitespace only\r
+ * @see #hasText(CharSequence)\r
+ */\r
+ public static boolean hasText(String str) {\r
+ return hasText((CharSequence) str);\r
+ }\r
+\r
+ /**\r
+ * Check whether the given CharSequence contains any whitespace characters.\r
+ * @param str the CharSequence to check (may be <code>null</code>)\r
+ * @return <code>true</code> if the CharSequence is not empty and\r
+ * contains at least 1 whitespace character\r
+ * @see java.lang.Character#isWhitespace\r
+ */\r
+ public static boolean containsWhitespace(CharSequence str) {\r
+ if (!hasLength(str)) {\r
+ return false;\r
+ }\r
+ int strLen = str.length();\r
+ for (int i = 0; i < strLen; i++) {\r
+ if (Character.isWhitespace(str.charAt(i))) {\r
+ return true;\r
+ }\r
+ }\r
+ return false;\r
+ }\r
+\r
+ /**\r
+ * Check whether the given String contains any whitespace characters.\r
+ * @param str the String to check (may be <code>null</code>)\r
+ * @return <code>true</code> if the String is not empty and\r
+ * contains at least 1 whitespace character\r
+ * @see #containsWhitespace(CharSequence)\r
+ */\r
+ public static boolean containsWhitespace(String str) {\r
+ return containsWhitespace((CharSequence) str);\r
+ }\r
+\r
+ /**\r
+ * Trim leading and trailing whitespace from the given String.\r
+ * @param str the String to check\r
+ * @return the trimmed String\r
+ * @see java.lang.Character#isWhitespace\r
+ */\r
+ public static String trimWhitespace(String str) {\r
+ if (!hasLength(str)) {\r
+ return str;\r
+ }\r
+ StringBuffer buf = new StringBuffer(str);\r
+ while (buf.length() > 0 && Character.isWhitespace(buf.charAt(0))) {\r
+ buf.deleteCharAt(0);\r
+ }\r
+ while (buf.length() > 0 && Character.isWhitespace(buf.charAt(buf.length() - 1))) {\r
+ buf.deleteCharAt(buf.length() - 1);\r
+ }\r
+ return buf.toString();\r
+ }\r
+\r
+ /**\r
+ * Trim <i>all</i> whitespace from the given String:\r
+ * leading, trailing, and inbetween characters.\r
+ * @param str the String to check\r
+ * @return the trimmed String\r
+ * @see java.lang.Character#isWhitespace\r
+ */\r
+ public static String trimAllWhitespace(String str) {\r
+ if (!hasLength(str)) {\r
+ return str;\r
+ }\r
+ StringBuffer buf = new StringBuffer(str);\r
+ int index = 0;\r
+ while (buf.length() > index) {\r
+ if (Character.isWhitespace(buf.charAt(index))) {\r
+ buf.deleteCharAt(index);\r
+ }\r
+ else {\r
+ index++;\r
+ }\r
+ }\r
+ return buf.toString();\r
+ }\r
+\r
+ /**\r
+ * Trim leading whitespace from the given String.\r
+ * @param str the String to check\r
+ * @return the trimmed String\r
+ * @see java.lang.Character#isWhitespace\r
+ */\r
+ public static String trimLeadingWhitespace(String str) {\r
+ if (!hasLength(str)) {\r
+ return str;\r
+ }\r
+ StringBuffer buf = new StringBuffer(str);\r
+ while (buf.length() > 0 && Character.isWhitespace(buf.charAt(0))) {\r
+ buf.deleteCharAt(0);\r
+ }\r
+ return buf.toString();\r
+ }\r
+\r
+ /**\r
+ * Trim trailing whitespace from the given String.\r
+ * @param str the String to check\r
+ * @return the trimmed String\r
+ * @see java.lang.Character#isWhitespace\r
+ */\r
+ public static String trimTrailingWhitespace(String str) {\r
+ if (!hasLength(str)) {\r
+ return str;\r
+ }\r
+ StringBuffer buf = new StringBuffer(str);\r
+ while (buf.length() > 0 && Character.isWhitespace(buf.charAt(buf.length() - 1))) {\r
+ buf.deleteCharAt(buf.length() - 1);\r
+ }\r
+ return buf.toString();\r
+ }\r
+\r
+ /**\r
+ * Trim all occurences of the supplied leading character from the given String.\r
+ * @param str the String to check\r
+ * @param leadingCharacter the leading character to be trimmed\r
+ * @return the trimmed String\r
+ */\r
+ public static String trimLeadingCharacter(String str, char leadingCharacter) {\r
+ if (!hasLength(str)) {\r
+ return str;\r
+ }\r
+ StringBuffer buf = new StringBuffer(str);\r
+ while (buf.length() > 0 && buf.charAt(0) == leadingCharacter) {\r
+ buf.deleteCharAt(0);\r
+ }\r
+ return buf.toString();\r
+ }\r
+\r
+ /**\r
+ * Trim all occurences of the supplied trailing character from the given String.\r
+ * @param str the String to check\r
+ * @param trailingCharacter the trailing character to be trimmed\r
+ * @return the trimmed String\r
+ */\r
+ public static String trimTrailingCharacter(String str, char trailingCharacter) {\r
+ if (!hasLength(str)) {\r
+ return str;\r
+ }\r
+ StringBuffer buf = new StringBuffer(str);\r
+ while (buf.length() > 0 && buf.charAt(buf.length() - 1) == trailingCharacter) {\r
+ buf.deleteCharAt(buf.length() - 1);\r
+ }\r
+ return buf.toString();\r
+ }\r
+\r
+\r
+ /**\r
+ * Test if the given String starts with the specified prefix,\r
+ * ignoring upper/lower case.\r
+ * @param str the String to check\r
+ * @param prefix the prefix to look for\r
+ * @see java.lang.String#startsWith\r
+ */\r
+ public static boolean startsWithIgnoreCase(String str, String prefix) {\r
+ if (str == null || prefix == null) {\r
+ return false;\r
+ }\r
+ if (str.startsWith(prefix)) {\r
+ return true;\r
+ }\r
+ if (str.length() < prefix.length()) {\r
+ return false;\r
+ }\r
+ String lcStr = str.substring(0, prefix.length()).toLowerCase();\r
+ String lcPrefix = prefix.toLowerCase();\r
+ return lcStr.equals(lcPrefix);\r
+ }\r
+\r
+ /**\r
+ * Test if the given String ends with the specified suffix,\r
+ * ignoring upper/lower case.\r
+ * @param str the String to check\r
+ * @param suffix the suffix to look for\r
+ * @see java.lang.String#endsWith\r
+ */\r
+ public static boolean endsWithIgnoreCase(String str, String suffix) {\r
+ if (str == null || suffix == null) {\r
+ return false;\r
+ }\r
+ if (str.endsWith(suffix)) {\r
+ return true;\r
+ }\r
+ if (str.length() < suffix.length()) {\r
+ return false;\r
+ }\r
+\r
+ String lcStr = str.substring(str.length() - suffix.length()).toLowerCase();\r
+ String lcSuffix = suffix.toLowerCase();\r
+ return lcStr.equals(lcSuffix);\r
+ }\r
+\r
+ /**\r
+ * Test whether the given string matches the given substring\r
+ * at the given index.\r
+ * @param str the original string (or StringBuffer)\r
+ * @param index the index in the original string to start matching against\r
+ * @param substring the substring to match at the given index\r
+ */\r
+ public static boolean substringMatch(CharSequence str, int index, CharSequence substring) {\r
+ for (int j = 0; j < substring.length(); j++) {\r
+ int i = index + j;\r
+ if (i >= str.length() || str.charAt(i) != substring.charAt(j)) {\r
+ return false;\r
+ }\r
+ }\r
+ return true;\r
+ }\r
+\r
+ /**\r
+ * Count the occurrences of the substring in string s.\r
+ * @param str string to search in. Return 0 if this is null.\r
+ * @param sub string to search for. Return 0 if this is null.\r
+ */\r
+ public static int countOccurrencesOf(String str, String sub) {\r
+ if (str == null || sub == null || str.length() == 0 || sub.length() == 0) {\r
+ return 0;\r
+ }\r
+ int count = 0, pos = 0, idx = 0;\r
+ while ((idx = str.indexOf(sub, pos)) != -1) {\r
+ ++count;\r
+ pos = idx + sub.length();\r
+ }\r
+ return count;\r
+ }\r
+\r
+ /**\r
+ * Replace all occurences of a substring within a string with\r
+ * another string.\r
+ * @param inString String to examine\r
+ * @param oldPattern String to replace\r
+ * @param newPattern String to insert\r
+ * @return a String with the replacements\r
+ */\r
+ public static String replace(String inString, String oldPattern, String newPattern) {\r
+ if (!hasLength(inString) || !hasLength(oldPattern) || newPattern == null) {\r
+ return inString;\r
+ }\r
+ StringBuffer sbuf = new StringBuffer();\r
+ // output StringBuffer we'll build up\r
+ int pos = 0; // our position in the old string\r
+ int index = inString.indexOf(oldPattern);\r
+ // the index of an occurrence we've found, or -1\r
+ int patLen = oldPattern.length();\r
+ while (index >= 0) {\r
+ sbuf.append(inString.substring(pos, index));\r
+ sbuf.append(newPattern);\r
+ pos = index + patLen;\r
+ index = inString.indexOf(oldPattern, pos);\r
+ }\r
+ sbuf.append(inString.substring(pos));\r
+ // remember to append any characters to the right of a match\r
+ return sbuf.toString();\r
+ }\r
+\r
+ /**\r
+ * Delete all occurrences of the given substring.\r
+ * @param inString the original String\r
+ * @param pattern the pattern to delete all occurrences of\r
+ * @return the resulting String\r
+ */\r
+ public static String delete(String inString, String pattern) {\r
+ return replace(inString, pattern, "");\r
+ }\r
+\r
+ /**\r
+ * Delete any character in a given String.\r
+ * @param inString the original String\r
+ * @param charsToDelete a set of characters to delete.\r
+ * E.g. "az\n" will delete 'a's, 'z's and new lines.\r
+ * @return the resulting String\r
+ */\r
+ public static String deleteAny(String inString, String charsToDelete) {\r
+ if (!hasLength(inString) || !hasLength(charsToDelete)) {\r
+ return inString;\r
+ }\r
+ StringBuffer out = new StringBuffer();\r
+ for (int i = 0; i < inString.length(); i++) {\r
+ char c = inString.charAt(i);\r
+ if (charsToDelete.indexOf(c) == -1) {\r
+ out.append(c);\r
+ }\r
+ }\r
+ return out.toString();\r
+ }\r
+\r
+\r
+ //---------------------------------------------------------------------\r
+ // Convenience methods for working with formatted Strings\r
+ //---------------------------------------------------------------------\r
+\r
+ /**\r
+ * Quote the given String with single quotes.\r
+ * @param str the input String (e.g. "myString")\r
+ * @return the quoted String (e.g. "'myString'"),\r
+ * or <code>null<code> if the input was <code>null</code>\r
+ */\r
+ public static String quote(String str) {\r
+ return (str != null ? "'" + str + "'" : null);\r
+ }\r
+\r
+ /**\r
+ * Turn the given Object into a String with single quotes\r
+ * if it is a String; keeping the Object as-is else.\r
+ * @param obj the input Object (e.g. "myString")\r
+ * @return the quoted String (e.g. "'myString'"),\r
+ * or the input object as-is if not a String\r
+ */\r
+ public static Object quoteIfString(Object obj) {\r
+ return (obj instanceof String ? quote((String) obj) : obj);\r
+ }\r
+\r
+ /**\r
+ * Unqualify a string qualified by a '.' dot character. For example,\r
+ * "this.name.is.qualified", returns "qualified".\r
+ * @param qualifiedName the qualified name\r
+ */\r
+ public static String unqualify(String qualifiedName) {\r
+ return unqualify(qualifiedName, '.');\r
+ }\r
+\r
+ /**\r
+ * Unqualify a string qualified by a separator character. For example,\r
+ * "this:name:is:qualified" returns "qualified" if using a ':' separator.\r
+ * @param qualifiedName the qualified name\r
+ * @param separator the separator\r
+ */\r
+ public static String unqualify(String qualifiedName, char separator) {\r
+ return qualifiedName.substring(qualifiedName.lastIndexOf(separator) + 1);\r
+ }\r
+\r
+ /**\r
+ * Capitalize a <code>String</code>, changing the first letter to\r
+ * upper case as per {@link Character#toUpperCase(char)}.\r
+ * No other letters are changed.\r
+ * @param str the String to capitalize, may be <code>null</code>\r
+ * @return the capitalized String, <code>null</code> if null\r
+ */\r
+ public static String capitalize(String str) {\r
+ return changeFirstCharacterCase(str, true);\r
+ }\r
+\r
+ /**\r
+ * Uncapitalize a <code>String</code>, changing the first letter to\r
+ * lower case as per {@link Character#toLowerCase(char)}.\r
+ * No other letters are changed.\r
+ * @param str the String to uncapitalize, may be <code>null</code>\r
+ * @return the uncapitalized String, <code>null</code> if null\r
+ */\r
+ public static String uncapitalize(String str) {\r
+ return changeFirstCharacterCase(str, false);\r
+ }\r
+\r
+ private static String changeFirstCharacterCase(String str, boolean capitalize) {\r
+ if (str == null || str.length() == 0) {\r
+ return str;\r
+ }\r
+ StringBuffer buf = new StringBuffer(str.length());\r
+ if (capitalize) {\r
+ buf.append(Character.toUpperCase(str.charAt(0)));\r
+ }\r
+ else {\r
+ buf.append(Character.toLowerCase(str.charAt(0)));\r
+ }\r
+ buf.append(str.substring(1));\r
+ return buf.toString();\r
+ }\r
+\r
+ /**\r
+ * Extract the filename from the given path,\r
+ * e.g. "mypath/myfile.txt" -> "myfile.txt".\r
+ * @param path the file path (may be <code>null</code>)\r
+ * @return the extracted filename, or <code>null</code> if none\r
+ */\r
+ public static String getFilename(String path) {\r
+ if (path == null) {\r
+ return null;\r
+ }\r
+ int separatorIndex = path.lastIndexOf(FOLDER_SEPARATOR);\r
+ return (separatorIndex != -1 ? path.substring(separatorIndex + 1) : path);\r
+ }\r
+\r
+ /**\r
+ * Extract the filename extension from the given path,\r
+ * e.g. "mypath/myfile.txt" -> "txt".\r
+ * @param path the file path (may be <code>null</code>)\r
+ * @return the extracted filename extension, or <code>null</code> if none\r
+ */\r
+ public static String getFilenameExtension(String path) {\r
+ if (path == null) {\r
+ return null;\r
+ }\r
+ int sepIndex = path.lastIndexOf(EXTENSION_SEPARATOR);\r
+ return (sepIndex != -1 ? path.substring(sepIndex + 1) : null);\r
+ }\r
+\r
+ /**\r
+ * Strip the filename extension from the given path,\r
+ * e.g. "mypath/myfile.txt" -> "mypath/myfile".\r
+ * @param path the file path (may be <code>null</code>)\r
+ * @return the path with stripped filename extension,\r
+ * or <code>null</code> if none\r
+ */\r
+ public static String stripFilenameExtension(String path) {\r
+ if (path == null) {\r
+ return null;\r
+ }\r
+ int sepIndex = path.lastIndexOf(EXTENSION_SEPARATOR);\r
+ return (sepIndex != -1 ? path.substring(0, sepIndex) : path);\r
+ }\r
+\r
+ /**\r
+ * Apply the given relative path to the given path,\r
+ * assuming standard Java folder separation (i.e. "/" separators);\r
+ * @param path the path to start from (usually a full file path)\r
+ * @param relativePath the relative path to apply\r
+ * (relative to the full file path above)\r
+ * @return the full file path that results from applying the relative path\r
+ */\r
+ public static String applyRelativePath(String path, String relativePath) {\r
+ int separatorIndex = path.lastIndexOf(FOLDER_SEPARATOR);\r
+ if (separatorIndex != -1) {\r
+ String newPath = path.substring(0, separatorIndex);\r
+ if (!relativePath.startsWith(FOLDER_SEPARATOR)) {\r
+ newPath += FOLDER_SEPARATOR;\r
+ }\r
+ return newPath + relativePath;\r
+ }\r
+ else {\r
+ return relativePath;\r
+ }\r
+ }\r
+\r
+ /**\r
+ * Normalize the path by suppressing sequences like "path/.." and\r
+ * inner simple dots.\r
+ * <p>The result is convenient for path comparison. For other uses,\r
+ * notice that Windows separators ("\") are replaced by simple slashes.\r
+ * @param path the original path\r
+ * @return the normalized path\r
+ */\r
+ public static String cleanPath(String path) {\r
+ if (path == null) {\r
+ return null;\r
+ }\r
+ String pathToUse = replace(path, WINDOWS_FOLDER_SEPARATOR, FOLDER_SEPARATOR);\r
+\r
+ // Strip prefix from path to analyze, to not treat it as part of the\r
+ // first path element. This is necessary to correctly parse paths like\r
+ // "file:core/../core/io/Resource.class", where the ".." should just\r
+ // strip the first "core" directory while keeping the "file:" prefix.\r
+ int prefixIndex = pathToUse.indexOf(":");\r
+ String prefix = "";\r
+ if (prefixIndex != -1) {\r
+ prefix = pathToUse.substring(0, prefixIndex + 1);\r
+ pathToUse = pathToUse.substring(prefixIndex + 1);\r
+ }\r
+ if (pathToUse.startsWith(FOLDER_SEPARATOR)) {\r
+ prefix = prefix + FOLDER_SEPARATOR;\r
+ pathToUse = pathToUse.substring(1);\r
+ }\r
+\r
+ String[] pathArray = delimitedListToStringArray(pathToUse, FOLDER_SEPARATOR);\r
+ List pathElements = new LinkedList();\r
+ int tops = 0;\r
+\r
+ for (int i = pathArray.length - 1; i >= 0; i--) {\r
+ String element = pathArray[i];\r
+ if (CURRENT_PATH.equals(element)) {\r
+ // Points to current directory - drop it.\r
+ }\r
+ else if (TOP_PATH.equals(element)) {\r
+ // Registering top path found.\r
+ tops++;\r
+ }\r
+ else {\r
+ if (tops > 0) {\r
+ // Merging path element with element corresponding to top path.\r
+ tops--;\r
+ }\r
+ else {\r
+ // Normal path element found.\r
+ pathElements.add(0, element);\r
+ }\r
+ }\r
+ }\r
+\r
+ // Remaining top paths need to be retained.\r
+ for (int i = 0; i < tops; i++) {\r
+ pathElements.add(0, TOP_PATH);\r
+ }\r
+\r
+ return prefix + collectionToDelimitedString(pathElements, FOLDER_SEPARATOR);\r
+ }\r
+\r
+ /**\r
+ * Compare two paths after normalization of them.\r
+ * @param path1 first path for comparison\r
+ * @param path2 second path for comparison\r
+ * @return whether the two paths are equivalent after normalization\r
+ */\r
+ public static boolean pathEquals(String path1, String path2) {\r
+ return cleanPath(path1).equals(cleanPath(path2));\r
+ }\r
+\r
+ /**\r
+ * Parse the given <code>localeString</code> into a {@link Locale}.\r
+ * <p>This is the inverse operation of {@link Locale#toString Locale's toString}.\r
+ * @param localeString the locale string, following <code>Locale's</code>\r
+ * <code>toString()</code> format ("en", "en_UK", etc);\r
+ * also accepts spaces as separators, as an alternative to underscores\r
+ * @return a corresponding <code>Locale</code> instance\r
+ */\r
+ public static Locale parseLocaleString(String localeString) {\r
+ String[] parts = tokenizeToStringArray(localeString, "_ ", false, false);\r
+ String language = (parts.length > 0 ? parts[0] : "");\r
+ String country = (parts.length > 1 ? parts[1] : "");\r
+ String variant = "";\r
+ if (parts.length >= 2) {\r
+ // There is definitely a variant, and it is everything after the country\r
+ // code sans the separator between the country code and the variant.\r
+ int endIndexOfCountryCode = localeString.indexOf(country) + country.length();\r
+ // Strip off any leading '_' and whitespace, what's left is the variant.\r
+ variant = trimLeadingWhitespace(localeString.substring(endIndexOfCountryCode));\r
+ if (variant.startsWith("_")) {\r
+ variant = trimLeadingCharacter(variant, '_');\r
+ }\r
+ }\r
+ return (language.length() > 0 ? new Locale(language, country, variant) : null);\r
+ }\r
+\r
+ /**\r
+ * Determine the RFC 3066 compliant language tag,\r
+ * as used for the HTTP "Accept-Language" header.\r
+ * @param locale the Locale to transform to a language tag\r
+ * @return the RFC 3066 compliant language tag as String\r
+ */\r
+ public static String toLanguageTag(Locale locale) {\r
+ return locale.getLanguage() + (hasText(locale.getCountry()) ? "-" + locale.getCountry() : "");\r
+ }\r
+\r
+\r
+ //---------------------------------------------------------------------\r
+ // Convenience methods for working with String arrays\r
+ //---------------------------------------------------------------------\r
+\r
+ /**\r
+ * Append the given String to the given String array, returning a new array\r
+ * consisting of the input array contents plus the given String.\r
+ * @param array the array to append to (can be <code>null</code>)\r
+ * @param str the String to append\r
+ * @return the new array (never <code>null</code>)\r
+ */\r
+ public static String[] addStringToArray(String[] array, String str) {\r
+ if (ObjectUtils.isEmpty(array)) {\r
+ return new String[] {str};\r
+ }\r
+ String[] newArr = new String[array.length + 1];\r
+ System.arraycopy(array, 0, newArr, 0, array.length);\r
+ newArr[array.length] = str;\r
+ return newArr;\r
+ }\r
+\r
+ /**\r
+ * Concatenate the given String arrays into one,\r
+ * with overlapping array elements included twice.\r
+ * <p>The order of elements in the original arrays is preserved.\r
+ * @param array1 the first array (can be <code>null</code>)\r
+ * @param array2 the second array (can be <code>null</code>)\r
+ * @return the new array (<code>null</code> if both given arrays were <code>null</code>)\r
+ */\r
+ public static String[] concatenateStringArrays(String[] array1, String[] array2) {\r
+ if (ObjectUtils.isEmpty(array1)) {\r
+ return array2;\r
+ }\r
+ if (ObjectUtils.isEmpty(array2)) {\r
+ return array1;\r
+ }\r
+ String[] newArr = new String[array1.length + array2.length];\r
+ System.arraycopy(array1, 0, newArr, 0, array1.length);\r
+ System.arraycopy(array2, 0, newArr, array1.length, array2.length);\r
+ return newArr;\r
+ }\r
+\r
+ /**\r
+ * Merge the given String arrays into one, with overlapping\r
+ * array elements only included once.\r
+ * <p>The order of elements in the original arrays is preserved\r
+ * (with the exception of overlapping elements, which are only\r
+ * included on their first occurence).\r
+ * @param array1 the first array (can be <code>null</code>)\r
+ * @param array2 the second array (can be <code>null</code>)\r
+ * @return the new array (<code>null</code> if both given arrays were <code>null</code>)\r
+ */\r
+ public static String[] mergeStringArrays(String[] array1, String[] array2) {\r
+ if (ObjectUtils.isEmpty(array1)) {\r
+ return array2;\r
+ }\r
+ if (ObjectUtils.isEmpty(array2)) {\r
+ return array1;\r
+ }\r
+ List result = new ArrayList();\r
+ result.addAll(Arrays.asList(array1));\r
+ for (int i = 0; i < array2.length; i++) {\r
+ String str = array2[i];\r
+ if (!result.contains(str)) {\r
+ result.add(str);\r
+ }\r
+ }\r
+ return toStringArray(result);\r
+ }\r
+\r
+ /**\r
+ * Turn given source String array into sorted array.\r
+ * @param array the source array\r
+ * @return the sorted array (never <code>null</code>)\r
+ */\r
+ public static String[] sortStringArray(String[] array) {\r
+ if (ObjectUtils.isEmpty(array)) {\r
+ return new String[0];\r
+ }\r
+ Arrays.sort(array);\r
+ return array;\r
+ }\r
+\r
+ /**\r
+ * Copy the given Collection into a String array.\r
+ * The Collection must contain String elements only.\r
+ * @param collection the Collection to copy\r
+ * @return the String array (<code>null</code> if the passed-in\r
+ * Collection was <code>null</code>)\r
+ */\r
+ public static String[] toStringArray(Collection collection) {\r
+ if (collection == null) {\r
+ return null;\r
+ }\r
+ return (String[]) collection.toArray(new String[collection.size()]);\r
+ }\r
+\r
+ /**\r
+ * Copy the given Enumeration into a String array.\r
+ * The Enumeration must contain String elements only.\r
+ * @param enumeration the Enumeration to copy\r
+ * @return the String array (<code>null</code> if the passed-in\r
+ * Enumeration was <code>null</code>)\r
+ */\r
+ public static String[] toStringArray(Enumeration enumeration) {\r
+ if (enumeration == null) {\r
+ return null;\r
+ }\r
+ List list = Collections.list(enumeration);\r
+ return (String[]) list.toArray(new String[list.size()]);\r
+ }\r
+\r
+ /**\r
+ * Trim the elements of the given String array,\r
+ * calling <code>String.trim()</code> on each of them.\r
+ * @param array the original String array\r
+ * @return the resulting array (of the same size) with trimmed elements\r
+ */\r
+ public static String[] trimArrayElements(String[] array) {\r
+ if (ObjectUtils.isEmpty(array)) {\r
+ return new String[0];\r
+ }\r
+ String[] result = new String[array.length];\r
+ for (int i = 0; i < array.length; i++) {\r
+ String element = array[i];\r
+ result[i] = (element != null ? element.trim() : null);\r
+ }\r
+ return result;\r
+ }\r
+\r
+ /**\r
+ * Remove duplicate Strings from the given array.\r
+ * Also sorts the array, as it uses a TreeSet.\r
+ * @param array the String array\r
+ * @return an array without duplicates, in natural sort order\r
+ */\r
+ public static String[] removeDuplicateStrings(String[] array) {\r
+ if (ObjectUtils.isEmpty(array)) {\r
+ return array;\r
+ }\r
+ Set set = new TreeSet();\r
+ for (int i = 0; i < array.length; i++) {\r
+ set.add(array[i]);\r
+ }\r
+ return toStringArray(set);\r
+ }\r
+\r
+ /**\r
+ * Split a String at the first occurrence of the delimiter.\r
+ * Does not include the delimiter in the result.\r
+ * @param toSplit the string to split\r
+ * @param delimiter to split the string up with\r
+ * @return a two element array with index 0 being before the delimiter, and\r
+ * index 1 being after the delimiter (neither element includes the delimiter);\r
+ * or <code>null</code> if the delimiter wasn't found in the given input String\r
+ */\r
+ public static String[] split(String toSplit, String delimiter) {\r
+ if (!hasLength(toSplit) || !hasLength(delimiter)) {\r
+ return null;\r
+ }\r
+ int offset = toSplit.indexOf(delimiter);\r
+ if (offset < 0) {\r
+ return null;\r
+ }\r
+ String beforeDelimiter = toSplit.substring(0, offset);\r
+ String afterDelimiter = toSplit.substring(offset + delimiter.length());\r
+ return new String[] {beforeDelimiter, afterDelimiter};\r
+ }\r
+\r
+ /**\r
+ * Take an array Strings and split each element based on the given delimiter.\r
+ * A <code>Properties</code> instance is then generated, with the left of the\r
+ * delimiter providing the key, and the right of the delimiter providing the value.\r
+ * <p>Will trim both the key and value before adding them to the\r
+ * <code>Properties</code> instance.\r
+ * @param array the array to process\r
+ * @param delimiter to split each element using (typically the equals symbol)\r
+ * @return a <code>Properties</code> instance representing the array contents,\r
+ * or <code>null</code> if the array to process was null or empty\r
+ */\r
+ public static Properties splitArrayElementsIntoProperties(String[] array, String delimiter) {\r
+ return splitArrayElementsIntoProperties(array, delimiter, null);\r
+ }\r
+\r
+ /**\r
+ * Take an array Strings and split each element based on the given delimiter.\r
+ * A <code>Properties</code> instance is then generated, with the left of the\r
+ * delimiter providing the key, and the right of the delimiter providing the value.\r
+ * <p>Will trim both the key and value before adding them to the\r
+ * <code>Properties</code> instance.\r
+ * @param array the array to process\r
+ * @param delimiter to split each element using (typically the equals symbol)\r
+ * @param charsToDelete one or more characters to remove from each element\r
+ * prior to attempting the split operation (typically the quotation mark\r
+ * symbol), or <code>null</code> if no removal should occur\r
+ * @return a <code>Properties</code> instance representing the array contents,\r
+ * or <code>null</code> if the array to process was <code>null</code> or empty\r
+ */\r
+ public static Properties splitArrayElementsIntoProperties(\r
+ String[] array, String delimiter, String charsToDelete) {\r
+\r
+ if (ObjectUtils.isEmpty(array)) {\r
+ return null;\r
+ }\r
+ Properties result = new Properties();\r
+ for (int i = 0; i < array.length; i++) {\r
+ String element = array[i];\r
+ if (charsToDelete != null) {\r
+ element = deleteAny(array[i], charsToDelete);\r
+ }\r
+ String[] splittedElement = split(element, delimiter);\r
+ if (splittedElement == null) {\r
+ continue;\r
+ }\r
+ result.setProperty(splittedElement[0].trim(), splittedElement[1].trim());\r
+ }\r
+ return result;\r
+ }\r
+\r
+ /**\r
+ * Tokenize the given String into a String array via a StringTokenizer.\r
+ * Trims tokens and omits empty tokens.\r
+ * <p>The given delimiters string is supposed to consist of any number of\r
+ * delimiter characters. Each of those characters can be used to separate\r
+ * tokens. A delimiter is always a single character; for multi-character\r
+ * delimiters, consider using <code>delimitedListToStringArray</code>\r
+ * @param str the String to tokenize\r
+ * @param delimiters the delimiter characters, assembled as String\r
+ * (each of those characters is individually considered as delimiter).\r
+ * @return an array of the tokens\r
+ * @see java.util.StringTokenizer\r
+ * @see java.lang.String#trim()\r
+ * @see #delimitedListToStringArray\r
+ */\r
+ public static String[] tokenizeToStringArray(String str, String delimiters) {\r
+ return tokenizeToStringArray(str, delimiters, true, true);\r
+ }\r
+\r
+ /**\r
+ * Tokenize the given String into a String array via a StringTokenizer.\r
+ * <p>The given delimiters string is supposed to consist of any number of\r
+ * delimiter characters. Each of those characters can be used to separate\r
+ * tokens. A delimiter is always a single character; for multi-character\r
+ * delimiters, consider using <code>delimitedListToStringArray</code>\r
+ * @param str the String to tokenize\r
+ * @param delimiters the delimiter characters, assembled as String\r
+ * (each of those characters is individually considered as delimiter)\r
+ * @param trimTokens trim the tokens via String's <code>trim</code>\r
+ * @param ignoreEmptyTokens omit empty tokens from the result array\r
+ * (only applies to tokens that are empty after trimming; StringTokenizer\r
+ * will not consider subsequent delimiters as token in the first place).\r
+ * @return an array of the tokens (<code>null</code> if the input String\r
+ * was <code>null</code>)\r
+ * @see java.util.StringTokenizer\r
+ * @see java.lang.String#trim()\r
+ * @see #delimitedListToStringArray\r
+ */\r
+ public static String[] tokenizeToStringArray(\r
+ String str, String delimiters, boolean trimTokens, boolean ignoreEmptyTokens) {\r
+\r
+ if (str == null) {\r
+ return null;\r
+ }\r
+ StringTokenizer st = new StringTokenizer(str, delimiters);\r
+ List tokens = new ArrayList();\r
+ while (st.hasMoreTokens()) {\r
+ String token = st.nextToken();\r
+ if (trimTokens) {\r
+ token = token.trim();\r
+ }\r
+ if (!ignoreEmptyTokens || token.length() > 0) {\r
+ tokens.add(token);\r
+ }\r
+ }\r
+ return toStringArray(tokens);\r
+ }\r
+\r
+ /**\r
+ * Take a String which is a delimited list and convert it to a String array.\r
+ * <p>A single delimiter can consists of more than one character: It will still\r
+ * be considered as single delimiter string, rather than as bunch of potential\r
+ * delimiter characters - in contrast to <code>tokenizeToStringArray</code>.\r
+ * @param str the input String\r
+ * @param delimiter the delimiter between elements (this is a single delimiter,\r
+ * rather than a bunch individual delimiter characters)\r
+ * @return an array of the tokens in the list\r
+ * @see #tokenizeToStringArray\r
+ */\r
+ public static String[] delimitedListToStringArray(String str, String delimiter) {\r
+ return delimitedListToStringArray(str, delimiter, null);\r
+ }\r
+\r
+ /**\r
+ * Take a String which is a delimited list and convert it to a String array.\r
+ * <p>A single delimiter can consists of more than one character: It will still\r
+ * be considered as single delimiter string, rather than as bunch of potential\r
+ * delimiter characters - in contrast to <code>tokenizeToStringArray</code>.\r
+ * @param str the input String\r
+ * @param delimiter the delimiter between elements (this is a single delimiter,\r
+ * rather than a bunch individual delimiter characters)\r
+ * @param charsToDelete a set of characters to delete. Useful for deleting unwanted\r
+ * line breaks: e.g. "\r\n\f" will delete all new lines and line feeds in a String.\r
+ * @return an array of the tokens in the list\r
+ * @see #tokenizeToStringArray\r
+ */\r
+ public static String[] delimitedListToStringArray(String str, String delimiter, String charsToDelete) {\r
+ if (str == null) {\r
+ return new String[0];\r
+ }\r
+ if (delimiter == null) {\r
+ return new String[] {str};\r
+ }\r
+ List result = new ArrayList();\r
+ if ("".equals(delimiter)) {\r
+ for (int i = 0; i < str.length(); i++) {\r
+ result.add(deleteAny(str.substring(i, i + 1), charsToDelete));\r
+ }\r
+ }\r
+ else {\r
+ int pos = 0;\r
+ int delPos = 0;\r
+ while ((delPos = str.indexOf(delimiter, pos)) != -1) {\r
+ result.add(deleteAny(str.substring(pos, delPos), charsToDelete));\r
+ pos = delPos + delimiter.length();\r
+ }\r
+ if (str.length() > 0 && pos <= str.length()) {\r
+ // Add rest of String, but not in case of empty input.\r
+ result.add(deleteAny(str.substring(pos), charsToDelete));\r
+ }\r
+ }\r
+ return toStringArray(result);\r
+ }\r
+\r
+ /**\r
+ * Convert a CSV list into an array of Strings.\r
+ * @param str the input String\r
+ * @return an array of Strings, or the empty array in case of empty input\r
+ */\r
+ public static String[] commaDelimitedListToStringArray(String str) {\r
+ return delimitedListToStringArray(str, ",");\r
+ }\r
+\r
+ /**\r
+ * Convenience method to convert a CSV string list to a set.\r
+ * Note that this will suppress duplicates.\r
+ * @param str the input String\r
+ * @return a Set of String entries in the list\r
+ */\r
+ public static Set commaDelimitedListToSet(String str) {\r
+ Set set = new TreeSet();\r
+ String[] tokens = commaDelimitedListToStringArray(str);\r
+ for (int i = 0; i < tokens.length; i++) {\r
+ set.add(tokens[i]);\r
+ }\r
+ return set;\r
+ }\r
+\r
+ /**\r
+ * Convenience method to return a Collection as a delimited (e.g. CSV)\r
+ * String. E.g. useful for <code>toString()</code> implementations.\r
+ * @param coll the Collection to display\r
+ * @param delim the delimiter to use (probably a ",")\r
+ * @param prefix the String to start each element with\r
+ * @param suffix the String to end each element with\r
+ * @return the delimited String\r
+ */\r
+ public static String collectionToDelimitedString(Collection coll, String delim, String prefix, String suffix) {\r
+ if (CollectionUtils.isEmpty(coll)) {\r
+ return "";\r
+ }\r
+ StringBuffer sb = new StringBuffer();\r
+ Iterator it = coll.iterator();\r
+ while (it.hasNext()) {\r
+ sb.append(prefix).append(it.next()).append(suffix);\r
+ if (it.hasNext()) {\r
+ sb.append(delim);\r
+ }\r
+ }\r
+ return sb.toString();\r
+ }\r
+\r
+ /**\r
+ * Convenience method to return a Collection as a delimited (e.g. CSV)\r
+ * String. E.g. useful for <code>toString()</code> implementations.\r
+ * @param coll the Collection to display\r
+ * @param delim the delimiter to use (probably a ",")\r
+ * @return the delimited String\r
+ */\r
+ public static String collectionToDelimitedString(Collection coll, String delim) {\r
+ return collectionToDelimitedString(coll, delim, "", "");\r
+ }\r
+\r
+ /**\r
+ * Convenience method to return a Collection as a CSV String.\r
+ * E.g. useful for <code>toString()</code> implementations.\r
+ * @param coll the Collection to display\r
+ * @return the delimited String\r
+ */\r
+ public static String collectionToCommaDelimitedString(Collection coll) {\r
+ return collectionToDelimitedString(coll, ",");\r
+ }\r
+\r
+ /**\r
+ * Convenience method to return a String array as a delimited (e.g. CSV)\r
+ * String. E.g. useful for <code>toString()</code> implementations.\r
+ * @param arr the array to display\r
+ * @param delim the delimiter to use (probably a ",")\r
+ * @return the delimited String\r
+ */\r
+ public static String arrayToDelimitedString(Object[] arr, String delim) {\r
+ if (ObjectUtils.isEmpty(arr)) {\r
+ return "";\r
+ }\r
+ StringBuffer sb = new StringBuffer();\r
+ for (int i = 0; i < arr.length; i++) {\r
+ if (i > 0) {\r
+ sb.append(delim);\r
+ }\r
+ sb.append(arr[i]);\r
+ }\r
+ return sb.toString();\r
+ }\r
+\r
+ /**\r
+ * Convenience method to return a String array as a CSV String.\r
+ * E.g. useful for <code>toString()</code> implementations.\r
+ * @param arr the array to display\r
+ * @return the delimited String\r
+ */\r
+ public static String arrayToCommaDelimitedString(Object[] arr) {\r
+ return arrayToDelimitedString(arr, ",");\r
+ }\r
+\r
+}\r